Skip to content

Commit

Permalink
fix: update query state with stagate client
Browse files Browse the repository at this point in the history
  • Loading branch information
thanhnv2303 committed Oct 19, 2022
1 parent 28ead90 commit e820c90
Show file tree
Hide file tree
Showing 19 changed files with 389 additions and 282 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@tovchain/cosms",
"version": "0.5.0",
"version": "0.6.0-beta.0.2",
"description": "query data form cosmos base networks template",
"main": "build/main/index.js",
"typings": "build/main/index.d.ts",
Expand Down
198 changes: 112 additions & 86 deletions src/lib/apr/index.ts
Original file line number Diff line number Diff line change
@@ -1,90 +1,116 @@
import Cosmos from "../cosmos";
import { BaseProvider } from "../providers";
import Cosmos from '../cosmos';
import { BaseProvider } from '../providers';

export default class APRCalCulator {
cosmos: Cosmos
provider: BaseProvider | any;
constructor(cosmos: any, provider: BaseProvider | any) {
this.cosmos = cosmos;
this.provider = provider;
}
async stakingAPR(decimal: number): Promise<number> {
let inflation = await this.inflation(decimal);
let communityTax = await this.communityTax(decimal);
let bondedTokensRatio = await this.bondedTokensRatio();
return (inflation * (1 - communityTax)) / bondedTokensRatio;
}
async annualProvisions(decimal: number): Promise<number> {
let annualProvisions = await this.cosmos.mint.query.AnnualProvisions({});
return uint8ArrayStringToNumber(annualProvisions.annualProvisions, decimal);
}
async actualStakingAPR(decimal: number): Promise<number> {
let stakingAPR = await this.stakingAPR(decimal);
let actualProvisionsRatio = await this.actualProvisionsRatio();
return stakingAPR * actualProvisionsRatio;
}
async finalStakingAPR(validatorAddress: string, mintDecimal: number, distributionDecimal: number): Promise<number> {
let actualStakingAPR = await this.actualStakingAPR(mintDecimal);
let validatorCommission = await this.validatorCommission(validatorAddress, distributionDecimal);
return actualStakingAPR * (1 - validatorCommission);
}
async inflation(decimal: number): Promise<number> {
let data = await this.cosmos.mint.query.Inflation({});
let inflation = uint8ArrayStringToNumber(data.inflation, decimal);
return inflation;
}
async communityTax(decimal: number): Promise<number> {
let data = await this.cosmos.distribution.query.Params({});
let communityTax = uint8ArrayStringToNumber(data.params.communityTax, decimal);
return communityTax
}
async bondedTokens(): Promise<number> {
let data = await this.cosmos.staking.query.Pool({});
let bondedTokens = uint8ArrayStringToNumber(data.pool.bondedTokens, 0);
return bondedTokens
}
async notBondedTokens(): Promise<number> {
let data = await this.cosmos.staking.query.Pool({});
let notBondedTokens = uint8ArrayStringToNumber(data.pool.notBondedTokens, 0);
return notBondedTokens
}
async bondedTokensRatio(): Promise<number> {
let mintDenom = (await this.cosmos.mint.query.Params({})).params.mintDenom;
let currentSupply: any = (await this.cosmos.bank.query.SupplyOf({ denom: mintDenom })).amount.amount;
currentSupply = parseFloat(currentSupply);
let bondedTokens = await this.bondedTokens();
let bondedTokensRatio = bondedTokens / currentSupply;
return bondedTokensRatio;
}
async actualProvisionsRatio(): Promise<number> {
let estBlockPerYear = (await this.cosmos.mint.query.Params({})).params.blocksPerYear.toNumber();
let estBlockTime = 86400 * 365.25 / estBlockPerYear;
let height = await this.provider.batchQueryClient.getHeight();
let block = await this.provider.batchQueryClient.getBlock(height);
let preBlock = await this.provider.batchQueryClient.getBlock(height - 1000);
let currentBlockTime = Date.parse(block.header.time);
let preBlockTime = Date.parse(preBlock.header.time);
let statBlockTime = (currentBlockTime - preBlockTime) / 1000000
let actualProvisionsRatio = estBlockTime / statBlockTime;
return actualProvisionsRatio;
}
async validatorCommission(validatorAddress: string, decimal: number): Promise<number> {
let data = await this.cosmos.distribution.query.ValidatorCommission({ validatorAddress: validatorAddress })
let validatorCommission = uint8ArrayStringToNumber(data.commission.commission[0].amount, decimal)
return validatorCommission;
}
cosmos: Cosmos;
provider: BaseProvider | any;
constructor(cosmos: any, provider: BaseProvider | any) {
this.cosmos = cosmos;
this.provider = provider;
}
async stakingAPR(decimal: number): Promise<number> {
const inflation = await this.inflation(decimal);
const communityTax = await this.communityTax(decimal);
const bondedTokensRatio = await this.bondedTokensRatio();
return (inflation * (1 - communityTax)) / bondedTokensRatio;
}
async annualProvisions(decimal: number): Promise<number> {
const annualProvisions = await this.cosmos.mint.query.AnnualProvisions({});
return uint8ArrayStringToNumber(annualProvisions.annualProvisions, decimal);
}
async actualStakingAPR(decimal: number): Promise<number> {
const stakingAPR = await this.stakingAPR(decimal);
const actualProvisionsRatio = await this.actualProvisionsRatio();
return stakingAPR * actualProvisionsRatio;
}
async finalStakingAPR(
validatorAddress: string,
mintDecimal: number,
distributionDecimal: number
): Promise<number> {
const actualStakingAPR = await this.actualStakingAPR(mintDecimal);
const validatorCommission = await this.validatorCommission(
validatorAddress,
distributionDecimal
);
return actualStakingAPR * (1 - validatorCommission);
}
async inflation(decimal: number): Promise<number> {
const data = await this.cosmos.mint.query.Inflation({});
const inflation = uint8ArrayStringToNumber(data.inflation, decimal);
return inflation;
}
async communityTax(decimal: number): Promise<number> {
const data = await this.cosmos.distribution.query.Params({});
const communityTax = uint8ArrayStringToNumber(
data.params.communityTax,
decimal
);
return communityTax;
}
async bondedTokens(): Promise<number> {
const data = await this.cosmos.staking.query.Pool({});
const bondedTokens = uint8ArrayStringToNumber(data.pool.bondedTokens, 0);
return bondedTokens;
}
async notBondedTokens(): Promise<number> {
const data = await this.cosmos.staking.query.Pool({});
const notBondedTokens = uint8ArrayStringToNumber(
data.pool.notBondedTokens,
0
);
return notBondedTokens;
}
async bondedTokensRatio(): Promise<number> {
const mintDenom = (await this.cosmos.mint.query.Params({})).params.mintDenom;
let currentSupply: any = (
await this.cosmos.bank.query.SupplyOf({ denom: mintDenom })
).amount.amount;
currentSupply = parseFloat(currentSupply);
const bondedTokens = await this.bondedTokens();
const bondedTokensRatio = bondedTokens / currentSupply;
return bondedTokensRatio;
}
async actualProvisionsRatio(): Promise<number> {
const estBlockPerYear = (
await this.cosmos.mint.query.Params({})
).params.blocksPerYear.toNumber();
const estBlockTime = (86400 * 365.25) / estBlockPerYear;
const height = await this.provider.batchQueryClient.getHeight();
const block = await this.provider.batchQueryClient.getBlock(height);
const preBlock = await this.provider.batchQueryClient.getBlock(height - 1000);
const currentBlockTime = Date.parse(block.header.time);
const preBlockTime = Date.parse(preBlock.header.time);
const statBlockTime = (currentBlockTime - preBlockTime) / 1000000;
const actualProvisionsRatio = estBlockTime / statBlockTime;
return actualProvisionsRatio;
}
async validatorCommission(
validatorAddress: string,
decimal: number
): Promise<number> {
const data = await this.cosmos.distribution.query.ValidatorCommission({
validatorAddress: validatorAddress,
});
const validatorCommission = uint8ArrayStringToNumber(
data.commission.commission[0].amount,
decimal
);
return validatorCommission;
}
}
function uint8ArrayStringToNumber(x: Uint8Array | string, decimal: number): number {
let xStr = Buffer.from(x).toString();
let xlen = xStr.length;
if (xlen < decimal) {
xStr = "." + "0".repeat(decimal - xlen) + xStr;
}
else if (xlen === decimal) {
xStr = "." + xStr;
}
else {
xStr = xStr.slice(0, xlen - decimal) + "." + xStr.slice(xlen - decimal);
}
return parseFloat(xStr);
function uint8ArrayStringToNumber(
x: Uint8Array | string,
decimal: number
): number {
let xStr = Buffer.from(x).toString();
const xlen = xStr.length;
if (xlen < decimal) {
xStr = '.' + '0'.repeat(decimal - xlen) + xStr;
} else if (xlen === decimal) {
xStr = '.' + xStr;
} else {
xStr = xStr.slice(0, xlen - decimal) + '.' + xStr.slice(xlen - decimal);
}
return parseFloat(xStr);
}
21 changes: 12 additions & 9 deletions src/lib/apr/test.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
import Cosm from '../cosm';
import { BaseProvider } from '../providers';

import APRCalculator from './index';

async function test() {
let data: any;
// let rpc = 'https://rpc.orai.io';
// let rpc2 = 'https://rpc.cosmos.directory/cosmoshub';
// let rpc = 'https://osmosis-rpc.polkachu.com';
let rpc = 'https://sifchain-rpc.polkachu.com';
const rpc = 'https://sifchain-rpc.polkachu.com';
// let rpc3 = "https://rpc.cosmos.directory/juno"
// let rpc3 = 'https://osmosis-testnet-rpc.allthatnode.com:26657';
let provider = new BaseProvider();
const provider = new BaseProvider();

await provider.connect(rpc);

let cosm = new Cosm(provider);
const cosm = new Cosm(provider);
// cosm.cosmos.mint.prefixServices("osmosis");
let annualProvisions = await cosm.cosmos.mint.query.AnnualProvisions({});
const annualProvisions = await cosm.cosmos.mint.query.AnnualProvisions({});

// cosm.cosmos.distribution.prefixServices("osmosis");
// cosm.cosmos.distribution.prefixServices("osmosis");
let APR = new APRCalculator(cosm.cosmos, provider);
const APR = new APRCalculator(cosm.cosmos, provider);
// let denominator = await cosm.cosmos.mint.query.Params({})
// console.log(denominator)
// let estBlockPerYear = (await cosm.cosmos.mint.query.Params({})).params.blocksPerYear.toNumber();


let validatorAddress = 'cosmosvaloper1c4k24jzduc365kywrsvf5ujz4ya6mwympnc4en';
const validatorAddress = 'cosmosvaloper1c4k24jzduc365kywrsvf5ujz4ya6mwympnc4en';
// let height = await cosm.provider.batchQueryClient.getHeight();
// console.log('height: ', height);
// let blockNow = await cosm.provider.batchQueryClient.getBlock(height);
Expand Down Expand Up @@ -81,9 +81,12 @@ async function test() {

test();

function uint8ArrayStringToNumber(x: Uint8Array | string, decimal: number): number {
function uint8ArrayStringToNumber(
x: Uint8Array | string,
decimal: number
): number {
let xStr = Buffer.from(x).toString();
let xlen = xStr.length;
const xlen = xStr.length;
if (xlen < decimal) {
xStr = '.' + '0'.repeat(decimal - xlen) + xStr;
} else if (xlen === decimal) {
Expand Down
7 changes: 2 additions & 5 deletions src/lib/cosm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import { OfflineSigner } from '@cosmjs/proto-signing';

import Cosmos from '../cosmos';
import { Provider } from '../providers';
import {
TendermintBatchClient
} from '../tendermint-batch-rpc/tendermintbatchclient';
import { TendermintBatchClient } from '../tendermint-batch-rpc/tendermintbatchclient';
import { Utils } from '../utils';
import { Wallet } from '../wallet';
import { Wasm } from '../wasm';
Expand Down Expand Up @@ -36,11 +34,10 @@ export default class Cosm {
this._provider = provider;
this.cosmos = new Cosmos(provider);
this.wasm = new Wasm(provider);
this.tendermint = provider.tendermintClient
this.tendermint = provider.tendermintClient;
this.utils = new Utils();
}


setWallet(wallet: Wallet) {
this._wallet = wallet;
this.cosmos.setWallet(wallet);
Expand Down
35 changes: 18 additions & 17 deletions src/lib/cosm/message_index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import 'mocha';
import { BaseProvider } from '../providers';
import { Wallet } from '../wallet';

import Cosm from './index';

import { defaultAccount, defaultSigningClientOptions } from './testutils.spec';

import Cosm from './index';


const rpcUrl = 'https://testnet.rpc.orai.io';
// const rpcUrl = "https://public-rpc1.stafihub.io";
Expand All @@ -38,13 +38,15 @@ describe('Cosm test', async () => {
await provider.connect(rpcUrl);
cosm = new Cosm(provider);

wallet = await Wallet.getWalletFromMnemonic(provider, defaultAccount.mnemonic, prefix);

wallet = await Wallet.getWalletFromMnemonic(
provider,
defaultAccount.mnemonic,
prefix
);

const registry = new Registry();
registry.register('/custom.MsgCustom', MsgSend);
const options = { ...defaultSigningClientOptions, registry: registry };

});
before('setup network info', async () => {
currentBlock = await provider.batchQueryClient.getHeight();
Expand All @@ -65,40 +67,39 @@ describe('Cosm test', async () => {
});

describe('Test message', async () => {
it('should get account', async function() {
it('should get account', async function () {
console.log(wallet.address);
let balance = await cosm.cosmos.bank.query.AllBalances({ address: wallet.address });
const balance = await cosm.cosmos.bank.query.AllBalances({
address: wallet.address,
});
console.log(balance);
console.log(delegation);

cosm.setWallet(wallet);

let delegateInfo = {
const delegateInfo = {
delegatorAddress: wallet.address,
validatorAddress: delegation.validatorAddress,
amount: coin(100000, denom)
amount: coin(100000, denom),
};


await cosm.cosmos.staking.message.Delegate(delegateInfo);


let currentMessage = cosm.cosmos.staking.getCurrentMessage();
const currentMessage = cosm.cosmos.staking.getCurrentMessage();
console.log(currentMessage);

const fee = {
amount: [
{
denom: 'orai',
amount: '2000'
}
amount: '2000',
},
],
gas: '180000' // 180k
gas: '180000', // 180k
};

let tx = await cosm.cosmos.staking.sendMessage(fee);
const tx = await cosm.cosmos.staking.sendMessage(fee);
console.log(tx);
});

});
});
11 changes: 5 additions & 6 deletions src/lib/cosm/query_batch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,13 @@ describe('Cosm test', async () => {
});

describe('Test message', async () => {
it('should get account', async function() {
const tendermint = cosm.tendermint
for(let i = 8568000; i < 8568202; i++ ){
it('should get account', async function () {
const tendermint = cosm.tendermint;
for (let i = 8568000; i < 8568202; i++) {
await tendermint.block(i);
}
const txs = await tendermint.doCallBatch()
console.log(txs)
const txs = await tendermint.doCallBatch();
console.log(txs);
});

});
});
Loading

0 comments on commit e820c90

Please sign in to comment.