Skip to content

Commit

Permalink
fix: eridanus REST urls now use new path (#170)
Browse files Browse the repository at this point in the history
* fix: eridanus REST urls now use new path

* fix: query supply by denom new url

* fix: eridanus block data

* fix: eridanus block data

* fix: broken block indexing from encoding changes on cosmos-sdk

* fix: tx buttons calling deprecated endpoints

previous endpoints used to simulate and broadcast txs from the explorer
got deprecated from the v0.46 update of cosmos-sdk.

This PR update the ways gas is estimated and transactions are broadcasted to use the new endpoints.

Co-authored-by: Ian Harris <[email protected]>
  • Loading branch information
daeMOn63 and Ian Harris authored Aug 30, 2022
1 parent 6329cca commit 85cdad9
Show file tree
Hide file tree
Showing 8 changed files with 279 additions and 67 deletions.
14 changes: 7 additions & 7 deletions imports/api/accounts/server/methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,25 @@ const fetchFromUrl = (url) => {
Meteor.methods({
'accounts.getAccountDetail': function (address) {
this.unblock();
let url = API + '/auth/accounts/'+ address;
let url = API + '/cosmos/auth/v1beta1/accounts/'+ address;
try{
let available = HTTP.get(url);
if (available.statusCode == 200){
// return JSON.parse(available.content).account
let response = JSON.parse(available.content).result;
let account;
let response = JSON.parse(available.content);
let account = response.account;
if ((response.type === 'cosmos-sdk/Account') || (response.type === 'cosmos-sdk/BaseAccount'))
account = response.value;
account = response.account;
else if (response.type === 'cosmos-sdk/DelayedVestingAccount' || response.type === 'cosmos-sdk/ContinuousVestingAccount')
account = response.value.BaseVestingAccount.BaseAccount

try{
url = API + '/bank/balances/' + address;
url = API + '/cosmos/bank/v1beta1/balances/' + address;
response = HTTP.get(url);
let balances = JSON.parse(response.content).result;
let balances = JSON.parse(response.content).balances;
account.coins = balances;

if (account && account.account_number != null)
if (account && account.account_number !== null)
return account
return null
}
Expand Down
19 changes: 13 additions & 6 deletions imports/api/blocks/server/methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ Meteor.methods({
this.unblock();
// let url = RPC+'/block?height=' + height;

url = `${API}/blocks/${height}`;
url = `${API}/cosmos/base/tendermint/v1beta1/blocks/${height}`;
let analyticsData = {};

const bulkValidators = Validators.rawCollection().initializeUnorderedBulkOp();
Expand All @@ -259,11 +259,11 @@ Meteor.methods({
let blockData = {};
let block = JSON.parse(response.content);
blockData.height = height;
blockData.hash = block.block_id.hash;
blockData.hash = Buffer.from(block.block_id.hash, "base64").toString("hex").toUpperCase();
blockData.transNum = block.block.data.txs ? block.block.data.txs.length : 0;
blockData.time = block.block.header.time;
blockData.lastBlockHash = block.block.header.last_block_id.hash;
blockData.proposerAddress = block.block.header.proposer_address;
blockData.lastBlockHash = Buffer.from(block.block.header.last_block_id.hash, "base64").toString("hex").toUpperCase();
blockData.proposerAddress = Buffer.from(block.block.header.proposer_address, "base64").toString("hex").toUpperCase();
blockData.validators = [];


Expand Down Expand Up @@ -365,7 +365,11 @@ Meteor.methods({
// console.log(precommits);
for (let i = 0; i < precommits.length; i++) {
if (precommits[i] != null) {
blockData.validators.push(precommits[i].validator_address);
blockData.validators.push(
precommits[i].validator_address
? Buffer.from(precommits[i].validator_address, "base64").toString("hex").toUpperCase()
: null
);
}
}

Expand All @@ -389,7 +393,10 @@ Meteor.methods({

for (j in precommits) {
if (precommits[j] != null) {
let precommitAddress = precommits[j].validator_address;
if (precommits[j].validator_address === null) {
continue;
}
let precommitAddress = Buffer.from(precommits[j].validator_address, "base64").toString("hex").toUpperCase();
if (address == precommitAddress) {
record.exists = true;
bulkUpdateLastSeen.find({ address: precommitAddress }).upsert().updateOne({ $set: { lastSeen: blockData.time } });
Expand Down
6 changes: 4 additions & 2 deletions imports/api/chain/server/methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Meteor.methods({
this.unblock();
let url = "";
try {
url = API + "/blocks/latest";
url = API + "/cosmos/base/tendermint/v1beta1/blocks/latest";
let response = HTTP.get(url);
let latestBlock = JSON.parse(response.content);

Expand Down Expand Up @@ -118,7 +118,9 @@ Meteor.methods({
if (Meteor.settings.public.modules.bank) {
try {
url =
API + "/cosmos/bank/v1beta1/supply/" + Coin.StakingCoin.denom;
API +
"/cosmos/bank/v1beta1/supply/by_denom?denom=" +
Coin.StakingCoin.denom;
let response = HTTP.get(url);
let supply = JSON.parse(response.content);
chainStates.totalSupply = parseInt(supply.amount.amount);
Expand Down
84 changes: 51 additions & 33 deletions imports/api/ledger/server/methods.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { HTTP } from "meteor/http";
import { Validators } from "../../validators/validators";

import Big from "big.js";
import {
encodePubkey,
makeAuthInfoBytes,
Expand Down Expand Up @@ -90,48 +90,66 @@ Meteor.methods({
return data.txhash;
}
},
"transaction.execute": function (body, path) {
"get.rewards": function (delegatorBech32) {
this.unblock();
const url = `${API}/${path}`;
data = {
base_req: {
...body,
chain_id: Meteor.settings.public.chainId,
simulate: false,
},
};
let response = HTTP.post(url, { data });
const url = `${API}/cosmos/distribution/v1beta1/delegators/${delegatorBech32}/rewards`;
console.log("getDelegations", url);
let response = HTTP.get(url);
if (response.statusCode == 200) {
return JSON.parse(response.content);
}
},
"transaction.simulate": function (
txMsg,
from,
accountNumber,
sequence,
path,
adjustment = "1.2"
) {
"transaction.simulate": function (txMsg, adjustment = "1.2") {
this.unblock();
const url = `${API}/${path}`;
console.log(txMsg);
data = {
...txMsg,
base_req: {
from: from,
chain_id: Meteor.settings.public.chainId,
gas_adjustment: adjustment,
account_number: accountNumber,
sequence: sequence.toString(),
simulate: true,
const url = `${API}/cosmos/tx/v1beta1/simulate`;
let aminoTypes = new AminoTypes({
...createAuthzAminoConverters(),
...createBankAminoConverters(),
...createDistributionAminoConverters(),
...createGovAminoConverters(),
...createStakingAminoConverters("fetch"),
...createIbcAminoConverters(),
...createFreegrantAminoConverters(),
});
let legacyTx = txMsg.value;
console.log("simulate", JSON.stringify(legacyTx));
const signedTxBody = {
typeUrl: "/cosmos.tx.v1beta1.TxBody",
value: {
messages: legacyTx.msg.map((msg) => aminoTypes.fromAmino(msg)),
memo: legacyTx.memo,
},
};
console.log(url);
console.log(data);

let registry = new Registry(defaultRegistryTypes);
const signedTxBodyBytes = registry.encode(signedTxBody);
const pubkey = encodePubkey(legacyTx.signatures[0].pub_key);
const signedSequence = Int53.fromString(
legacyTx.signatures[0].sequence
).toNumber();

const signedAuthInfoBytes = makeAuthInfoBytes(
[{ pubkey, sequence: signedSequence }],
[],
0,
SignMode.SIGN_MODE_LEGACY_AMINO_JSON
);

const rawTx = TxRaw.fromPartial({
bodyBytes: signedTxBodyBytes,
authInfoBytes: signedAuthInfoBytes,
signatures: legacyTx.signatures,
});

data = {
tx_bytes: toBase64(TxRaw.encode(rawTx).finish()),
};
let response = HTTP.post(url, { data });
if (response.statusCode == 200) {
return JSON.parse(response.content).gas_estimate;
return Big(JSON.parse(response.content).gas_info.gas_used)
.mul(Big(adjustment))
.round(0)
.toString();
}
},
isValidator: function (address) {
Expand Down
44 changes: 25 additions & 19 deletions imports/ui/ledger/LedgerActions.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,35 +72,35 @@ const TypeMeta = {
},
[Types.WITHDRAW]: {
button: 'withdraw',
pathPreFix: 'distribution/delegators',
pathPreFix: 'cosmos/distribution/v1beta1/delegators',
pathSuffix: 'rewards',
warning: '',
gasAdjustment: '1.6'
gasAdjustment: '1.5'
},
[Types.SEND]: {
button: 'transfer',
button_other: 'send',
pathPreFix: 'bank/accounts',
pathSuffix: 'transfers',
warning: '',
gasAdjustment: '1.8'
gasAdjustment: '1.5'
},
[Types.SUBMITPROPOSAL]: {
button: 'new',
path: 'gov/proposals',
gasAdjustment: '1.4'
gasAdjustment: '1.5'
},
[Types.VOTE]: {
button: 'vote',
pathPreFix: 'gov/proposals',
pathSuffix: 'votes',
gasAdjustment: '2.5'
gasAdjustment: '1.5'
},
[Types.DEPOSIT]: {
button: 'deposit',
pathPreFix: 'gov/proposals',
pathSuffix: 'deposits',
gasAdjustment: '2'
gasAdjustment: '1.5'
}
}

Expand Down Expand Up @@ -427,7 +427,7 @@ class LedgerButton extends Component {

runSimulatation = (txMsg, simulateBody) => {
let gasAdjustment = TypeMeta[this.state.actionType].gasAdjustment || DEFAULT_GAS_ADJUSTMENT;
Meteor.call('transaction.simulate', simulateBody, this.state.user, this.state.currentUser.accountNumber, this.state.currentUser.sequence, this.getPath(), gasAdjustment, (err, res) => {
Meteor.call('transaction.simulate', txMsg, gasAdjustment, (err, res) => {
if (res) {
Ledger.applyGas(txMsg, res, Meteor.settings.public.ledger.gasPrice, Coin.StakingCoin.denom);
this.setStateOnSuccess('simulating', {
Expand Down Expand Up @@ -790,26 +790,32 @@ class DelegationButtons extends LedgerButton {
class WithdrawButton extends LedgerButton {

createMessage = (callback) => {
Meteor.call('transaction.execute', { from: this.state.user }, this.getPath(), (err, res) => {
Meteor.call('get.rewards', this.state.user, (err, res) => {
if (res) {
let allDelegatedValidators = [];
let operatorAddress = null;
for (let reward of res.rewards) {
allDelegatedValidators.push(reward.validator_address);
}
Meteor.call('isValidator', this.state.user, (error, result) => {
if (result && result.operator_address) {
res.value.msg.push({
type: 'cosmos-sdk/MsgWithdrawValidatorCommission',
value: { validator_address: result.operator_address }
})
operatorAddress = result.operator_address
}
callback(res, res)
})
}
else {
let txMsgs = Ledger.createWithdraw(
this.getTxContext(),
allDelegatedValidators,
operatorAddress,
);
callback(txMsgs, this.getSimulateBody(txMsgs));
});
} else {
this.setState({
loading: false,
simulating: false,
errorMessage: 'something went wrong'
})
errorMessage: 'something went wrong ' + JSON.stringify(res),
});
}
})
});
}

supportAction(action) {
Expand Down
27 changes: 27 additions & 0 deletions imports/ui/ledger/ledger.js
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,33 @@ export class Ledger {
return Ledger.createSkeleton(txContext, [txMsg]);
}

// Creates a new withdraw rewards tx based on the input parameters
// the function expects a complete txContext
// if operatorAddress is given, it will also withdraw commissions.
static createWithdraw(txContext, validatorsBech32, operatorAddress) {
let msgs = [];
for (let validatorBech32 of validatorsBech32) {
msgs.push({
type: "cosmos-sdk/MsgWithdrawDelegationReward",
value: {
delegator_address: txContext.bech32,
validator_address: validatorBech32,
},
});
}

if (operatorAddress) {
msgs.push({
type: "cosmos-sdk/MsgWithdrawValidatorCommission",
value: {
validator_address: operatorAddress,
},
});
}

return Ledger.createSkeleton(txContext, msgs);
}

static createSubmitProposal(txContext, title, description, deposit) {
const txMsg = {
type: "cosmos-sdk/MsgSubmitProposal",
Expand Down
Loading

0 comments on commit 85cdad9

Please sign in to comment.