Skip to content

Commit

Permalink
WebRunner for TAO inappp-staking feature
Browse files Browse the repository at this point in the history
  • Loading branch information
dominhquang committed Oct 15, 2024
1 parent 0f2bf25 commit 667f5f7
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ import { getDefaultWeightV2 } from '@subwallet/extension-base/koni/api/contract-
import { _BALANCE_CHAIN_GROUP, _MANTA_ZK_CHAIN_GROUP, _ZK_ASSET_PREFIX } from '@subwallet/extension-base/services/chain-service/constants';
import { _EvmApi, _SubstrateAdapterSubscriptionArgs, _SubstrateApi } from '@subwallet/extension-base/services/chain-service/types';
import { _checkSmartContractSupportByChain, _getAssetExistentialDeposit, _getChainExistentialDeposit, _getChainNativeTokenSlug, _getContractAddressOfToken, _getTokenOnChainAssetId, _getTokenOnChainInfo, _getTokenTypesSupportedByChain, _getXcmAssetMultilocation, _isBridgedToken, _isChainEvmCompatible } from '@subwallet/extension-base/services/chain-service/utils';
import { fetchTaoDelegateState } from '@subwallet/extension-base/services/earning-service/handlers/native-staking/tao';
import { getTaoTotalStake } from '@subwallet/extension-base/services/earning-service/utils';
import { BalanceItem, SubscribeBasePalletBalance, SubscribeSubstratePalletBalance } from '@subwallet/extension-base/types';
import { filterAssetsByChainAndType } from '@subwallet/extension-base/utils';
import BigN from 'bignumber.js';
Expand Down Expand Up @@ -144,13 +142,13 @@ const subscribeWithSystemAccountPallet = async ({ addresses, callback, chainInfo
);
}

let bittensorStakingBalances = new Array<bigint>(addresses.length).fill(BigInt(0));
let bittensorStakingBalances: BigN[] = new Array<BigN>(addresses.length).fill(new BigN(0));

if (['bittensor'].includes(chainInfo.slug)) {
bittensorStakingBalances = await Promise.all(addresses.map(async (address) => {
const rawDelegateState = await fetchTaoDelegateState(address);
const TaoTotalStake = await substrateApi.api.query.subtensorModule.totalColdkeyStake(address);

return getTaoTotalStake(rawDelegateState);
return new BigN(TaoTotalStake.toString());
}));
}

Expand All @@ -173,7 +171,9 @@ const subscribeWithSystemAccountPallet = async ({ addresses, callback, chainInfo
totalLockedFromTransfer += nominationPoolBalance;
}

totalLockedFromTransfer += bittensorStakingBalances[index];
const stakeValue = BigInt(bittensorStakingBalances[index].toString());

totalLockedFromTransfer += stakeValue;

return ({
address: addresses[index],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ export default abstract class BasePoolHandler {
const decimals = this.nativeToken.decimals || 0;
const defaultMaintainBalance = new BN(1).mul(BN_TEN.pow(new BN(decimals)));
const ed = new BN(this.nativeToken.minAmount || '0');
const maintainBalance = ed.gte(defaultMaintainBalance) ? new BN(15).mul(ed).div(BN_TEN) : defaultMaintainBalance;
const calculateMaintainBalance = new BN(15).mul(ed).div(BN_TEN);

const maintainBalance = ed.gte(defaultMaintainBalance) ? calculateMaintainBalance : defaultMaintainBalance;

return maintainBalance.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { BaseYieldPositionInfo, BasicTxErrorType, EarningStatus, NativeYieldPool
import { reformatAddress } from '@subwallet/extension-base/utils';
import BigN from 'bignumber.js';

import { BN, BN_ZERO } from '@polkadot/util';
import { BN, BN_TEN, BN_ZERO } from '@polkadot/util';

import { calculateReward } from '../../utils';

Expand All @@ -25,37 +25,30 @@ interface Hotkey {
}

export interface RawDelegateState {
items: Array<{
balance: string;
delegate_address: {
data: Array<{
delegate: {
ss58: string;
};
balance: string;
}>;
}

interface ValidatorResponse {
count: number;
validators: Validator[];
data: Validator[];
}

interface Validator {
validator_stake: string;
amount: string;
nominators: number;
apr: string;
hot_key: {
hotkey: {
ss58: string;
};
name: string;
nominators: number;
stake: string;
validator_stake: string;
take: string;
system_total_stake: string;
apr: string;
}

// interface ValidatorName {
// count: number;
// delegates: {
// name: string;
// }[];
// }
export const BITTENSOR_API_KEY_1 = process.env.BITTENSOR_API_KEY_1 || '';
export const BITTENSOR_API_KEY_2 = process.env.BITTENSOR_API_KEY_2 || '';

Expand All @@ -76,7 +69,7 @@ export async function fetchDelegates (): Promise<ValidatorResponse> {
const apiKey = bittensorApiKey();

return new Promise(function (resolve) {
fetch('https://api.taostats.io/api/v1/validator?order=amount%3Adesc&limit=100', {
fetch('https://api-prod-v2.taostats.io/api/validator/latest/v1', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Expand All @@ -92,7 +85,7 @@ export async function fetchTaoDelegateState (address: string): Promise<RawDelega
const apiKey = bittensorApiKey();

return new Promise(function (resolve) {
fetch(`https://api.taostats.io/api/v1/delegate/balance?nominator_address=${address}`, {
fetch(`https://api-prod-v2.taostats.io/api/delegation/balance/latest/v1?nominator=${address}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Expand Down Expand Up @@ -128,21 +121,14 @@ export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHand
}
/* Unimplemented function */

// async fetchDelegatesInfo (address: string): Promise<ValidatorName> {
// const apiKey = this.bittensorApiKey;

// return new Promise(function (resolve) {
// fetch(`https://api.taostats.io/api/v1/delegate/info?address=${address}`, {
// method: 'GET',
// headers: {
// 'Content-Type': 'application/json',
// Authorization: `${apiKey}`
// }
// }).then((resp) => {
// resolve(resp.json());
// }).catch(console.error);
// });
// }
public override get maintainBalance (): string {
const ed = new BN(this.nativeToken.minAmount || '0');
const calculateMaintainBalance = new BN(15).mul(ed).div(BN_TEN);

const maintainBalance = calculateMaintainBalance;

return maintainBalance.toString();
}

/* Subscribe pool info */

Expand Down Expand Up @@ -303,12 +289,12 @@ export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHand
const owner = reformatAddress(useAddresses[i], 42);
const delegatorState: TaoStakingStakeOption[] = [];
let bnTotalBalance = BN_ZERO;
const delegateStateInfo = rawDelegateStateInfo.items;
const delegateStateInfo = rawDelegateStateInfo.data;

for (const delegate of delegateStateInfo) {
bnTotalBalance = bnTotalBalance.add(new BN(delegate.balance));
delegatorState.push({
owner: delegate.delegate_address.ss58,
owner: delegate.delegate.ss58,
amount: delegate.balance.toString()
});
}
Expand Down Expand Up @@ -401,13 +387,13 @@ export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHand
const getNominatorMinRequiredStake = this.substrateApi.api.query.subtensorModule.nominatorMinRequiredStake();
const nominatorMinRequiredStake = (await getNominatorMinRequiredStake).toString();
const bnMinBond = new BN(nominatorMinRequiredStake);
const validatorList = topValidator.validators;
const validatorList = topValidator.data;
const validatorAddresses = Object.keys(validatorList);

const results = await Promise.all(
validatorAddresses.map((i) => {
const address = (validatorList[i].hot_key as unknown as Hotkey).ss58;
const bnTotalStake = new BN(validatorList[i].amount);
const address = (validatorList[i].hotkey as unknown as Hotkey).ss58;
const bnTotalStake = new BN(validatorList[i].stake);
const bnOwnStake = new BN(validatorList[i].validator_stake);
const otherStake = bnTotalStake.sub(bnOwnStake);
const nominatorCount = validatorList[i].nominators;
Expand All @@ -416,11 +402,7 @@ export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHand

const apr = ((parseFloat(validatorList[i].apr) / 10 ** 9) * 100).toFixed(2);
const apyCalculate = calculateReward(parseFloat(apr));

// let name = '';
// const delegateInfo = await this.fetchDelegatesInfo(address);

// name = delegateInfo.delegates[0]?.name || address;
const name = validatorList[i].name || address;

return {
address: address,
Expand All @@ -435,7 +417,7 @@ export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHand
isVerified: false,
chain: this.chain,
isCrowded: false,
identity: address // name
identity: name
} as unknown as ValidatorInfo;
})
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import { PalletIdentityRegistration, PalletIdentitySuper } from '@subwallet/extension-base/koni/api/staking/bonding/utils';
import { _SubstrateApi } from '@subwallet/extension-base/services/chain-service/types';
import { _STAKING_CHAIN_GROUP } from '@subwallet/extension-base/services/earning-service/constants';
import { RawDelegateState } from '@subwallet/extension-base/services/earning-service/handlers/native-staking/tao';
import { LendingYieldPoolInfo, LiquidYieldPoolInfo, NativeYieldPoolInfo, NominationYieldPoolInfo, YieldAssetExpectedEarning, YieldCompoundingPeriod, YieldPoolInfo, YieldPoolType } from '@subwallet/extension-base/types';

import { BN, hexToString, isHex } from '@polkadot/util';
Expand Down Expand Up @@ -155,17 +154,3 @@ export function applyDecimal (bnNumber: BN, decimals: number) {

return bnNumber.div(bnDecimals);
}

export function getTaoTotalStake (rawDelegateState: RawDelegateState) {
const nodeInfos = rawDelegateState.items;
const stakes = nodeInfos.map((stake) => stake.balance);
let totalStake = BigInt(0);

for (const _stake of stakes) {
const stakeAmount = BigInt(_stake);

totalStake += stakeAmount;
}

return totalStake;
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ export function getExplorerLink (chainInfo: _ChainInfo, value: string, type: 'ac
}

if (explorerLink && value.startsWith('0x')) {
if (chainInfo.slug === 'bittensor') {
return undefined;
}

const route = getBlockExplorerTxRoute(chainInfo);

return (`${explorerLink}${explorerLink.endsWith('/') ? '' : '/'}${route}/${value}`);
Expand Down

1 comment on commit 667f5f7

@saltict
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.