Skip to content

Commit

Permalink
Cherry pick code from web-runner 1.2.32 for mobile
Browse files Browse the repository at this point in the history
  • Loading branch information
dominhquang authored and Quangdm-cdm committed Dec 31, 2024
1 parent 68fcf51 commit ff02920
Show file tree
Hide file tree
Showing 12 changed files with 63 additions and 85 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@
"@polkadot/types-support": "^12.0.2",
"@polkadot/util": "^12.6.2",
"@polkadot/util-crypto": "^12.6.2",
"@subwallet/chain-list": "0.2.89",
"@subwallet/chain-list": "0.2.95-beta.0",
"@subwallet/keyring": "^0.1.8-beta.0",
"@subwallet/react-ui": "5.1.2-b79",
"@subwallet/ui-keyring": "0.1.8-beta.0 ",
Expand Down
2 changes: 1 addition & 1 deletion packages/extension-base/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"@reduxjs/toolkit": "^1.9.1",
"@sora-substrate/type-definitions": "^1.17.7",
"@substrate/connect": "^0.8.9",
"@subwallet/chain-list": "0.2.89",
"@subwallet/chain-list": "0.2.95-beta.0",
"@subwallet/extension-base": "^1.3.2-0",
"@subwallet/extension-chains": "^1.3.2-0",
"@subwallet/extension-dapp": "^1.3.2-0",
Expand Down
7 changes: 4 additions & 3 deletions packages/extension-base/src/core/substrate/xcm-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,18 +227,19 @@ function _getAssetIdentifier (tokenInfo: _ChainAsset, version: number) {

const assetIdentifier = ['statemint-LOCAL-KSM', 'statemine-LOCAL-DOT'].includes(tokenInfo.slug) // todo: hotfix for ksm statemint recheck all chain
? _assetIdentifier
: _adaptX1Interior(structuredClone(_assetIdentifier), version);
: _adaptX1Interior(_assetIdentifier, version);

return version >= 4 // from V4, Concrete is removed
? assetIdentifier
: { Concrete: assetIdentifier };
}

export function _adaptX1Interior (assetIdentifier: Record<string, any>, version: number): Record<string, any> {
export function _adaptX1Interior (_assetIdentifier: Record<string, any>, version: number): Record<string, any> {
const assetIdentifier = structuredClone(_assetIdentifier);
const interior = assetIdentifier.interior as Record<string, any>;
const isInteriorObj = typeof interior === 'object' && interior !== null;
const isX1 = isInteriorObj && 'X1' in interior;
const needModifyX1 = version <= 4 && Array.isArray(interior.X1);
const needModifyX1 = version < 4 && Array.isArray(interior.X1);

if (isInteriorObj && isX1 && needModifyX1) { // X1 is an object for version < 4. From V4, it's an array
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
Expand Down
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 Expand Up @@ -225,12 +225,13 @@ const subscribeForeignAssetBalance = async ({ addresses, assetMap, callback, cha
const unsubList = await Promise.all(Object.values(tokenMap).map((tokenInfo) => {
try {
if (_isBridgedToken(tokenInfo)) {
const version: number = ['statemint', 'statemine'].includes(chainInfo.slug) ? 4 : 3;
const params: _SubstrateAdapterSubscriptionArgs[] = [
{
section: 'query',
module: foreignAssetsAccountKey.split('_')[1],
method: foreignAssetsAccountKey.split('_')[2],
args: addresses.map((address) => [_getTokenOnChainInfo(tokenInfo) || _adaptX1Interior(_getXcmAssetMultilocation(tokenInfo), 3), address])
args: addresses.map((address) => [_getTokenOnChainInfo(tokenInfo) || _adaptX1Interior(_getXcmAssetMultilocation(tokenInfo), version), address])
}
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,12 +229,12 @@ export const _TRANSFER_CHAIN_GROUP = {
kintsugi: ['kintsugi', 'kintsugi_test', 'interlay', 'mangatax_para'],
genshiro: ['genshiro_testnet', 'genshiro', 'equilibrium_parachain'],
// crab: ['crab', 'pangolin'],
bitcountry: ['pioneer', 'bitcountry', 'bifrost', 'bifrost_dot'],
bitcountry: ['pioneer', 'bitcountry'],
statemine: ['statemint', 'statemine', 'darwinia2', 'astar', 'shiden', 'shibuya', 'parallel', 'liberland', 'liberlandTest', 'dentnet', 'dbcchain'],
riochain: ['riochain'],
sora_substrate: ['sora_substrate'],
avail: ['kate', 'goldberg_testnet'],
pendulum: ['pendulum', 'amplitude', 'amplitude_test', 'hydradx_main'],
pendulum: ['pendulum', 'amplitude', 'amplitude_test', 'hydradx_main', 'bifrost', 'bifrost_dot'],
centrifuge: ['centrifuge'],
disable_transfer: ['invarch', 'crab', 'pangolin']
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export function validateNativeLocalTransferMetadata (chainAsset: _ChainAsset) {
}

const moonbeamGroup = ['moonbeam, moonbase, moonriver'];
const onChainInfoLocalGroup = [_TRANSFER_CHAIN_GROUP.centrifuge, ..._TRANSFER_CHAIN_GROUP.bitcountry, ..._TRANSFER_CHAIN_GROUP.acala, ..._TRANSFER_CHAIN_GROUP.kintsugi, 'pendulum', 'amplitude'];
const onChainInfoLocalGroup = [_TRANSFER_CHAIN_GROUP.centrifuge, ..._TRANSFER_CHAIN_GROUP.bitcountry, ..._TRANSFER_CHAIN_GROUP.acala, ..._TRANSFER_CHAIN_GROUP.kintsugi, 'pendulum', 'amplitude', 'bifrost', 'bifrost_dot'];
const onChainInfoNativeGroup = [_TRANSFER_CHAIN_GROUP.centrifuge, ..._TRANSFER_CHAIN_GROUP.acala, ..._TRANSFER_CHAIN_GROUP.kintsugi];
const assetIdLocalGroup = [..._TRANSFER_CHAIN_GROUP.statemine, ..._TRANSFER_CHAIN_GROUP.genshiro, ...moonbeamGroup, 'hydradx'];
const assetIdNativeGroup = [..._TRANSFER_CHAIN_GROUP.sora_substrate, 'hydradx'];
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,39 +25,36 @@ 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 || '';
export const BITTENSOR_API_KEY_3 = process.env.BITTENSOR_API_KEY_3 || '';
export const BITTENSOR_API_KEY_4 = process.env.BITTENSOR_API_KEY_4 || '';
export const BITTENSOR_API_KEY_5 = process.env.BITTENSOR_API_KEY_5 || '';
export const BITTENSOR_API_KEY_6 = process.env.BITTENSOR_API_KEY_6 || '';

function random (...keys: string[]) {
const validKeys = keys.filter((key) => key);
Expand All @@ -67,7 +64,7 @@ function random (...keys: string[]) {
}

export const bittensorApiKey = (): string => {
return random(BITTENSOR_API_KEY_1, BITTENSOR_API_KEY_2);
return random(BITTENSOR_API_KEY_1, BITTENSOR_API_KEY_2, BITTENSOR_API_KEY_3, BITTENSOR_API_KEY_4, BITTENSOR_API_KEY_5, BITTENSOR_API_KEY_6);
};

/* Fetch data */
Expand All @@ -76,7 +73,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 +89,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 +125,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 +293,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 +391,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 +406,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 +421,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 @@ -15,7 +15,6 @@ import MigrateEthProvider from './providers/MigrateEthProvider';
import MigratePioneerProvider from './providers/MigratePioneerProvider';
import MigrateProvidersV1M1P24 from './providers/MigrateProvidersV1M1P24';
import MigratePolygonUSDCProvider from './tokens/MigratePolygonUSDCProvider';
import AutoEnableChainsTokens from './AutoEnableChainsTokens';
import DeleteChain from './DeleteChain';
import DeleteChainStaking from './DeleteChainStaking';
import DeleteEarningData from './DeleteEarningData';
Expand All @@ -37,7 +36,7 @@ export default <Record<string, typeof BaseMigrationJob>>{
'1.0.1-11': MigrateNetworkSettings,
'1.0.1-20': MigrateImportedToken,
'1.0.1-30': MigrateTransactionHistory,
'1.0.1-40': AutoEnableChainsTokens,
// '1.0.1-40': AutoEnableChainsTokens,
'1.0.1-50': MigrateSettings,
'1.0.1-60': MigrateAuthUrls,
'1.0.3-01': MigrateAutoLock,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,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
10 changes: 5 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6265,14 +6265,14 @@ __metadata:
languageName: node
linkType: hard

"@subwallet/chain-list@npm:0.2.89":
version: 0.2.89
resolution: "@subwallet/chain-list@npm:0.2.89"
"@subwallet/chain-list@npm:0.2.95-beta.0":
version: 0.2.95-beta.0
resolution: "@subwallet/chain-list@npm:0.2.95-beta.0"
dependencies:
"@polkadot/dev": 0.67.167
"@polkadot/util": ^12.5.1
eventemitter3: ^5.0.1
checksum: c459adf97fdef6b949fb004ac52ddf38338d0ffcd75af2eb6e45b5097e0cd5d32f621ec4c1e1c061a8bd2ba45c12d59d7c1baa474509faafd456c43c3dc25a0a
checksum: 23710027b2df62ff33eb5cbfe38fe82b254354d2cf67dc5a284233dfc2269e0691c357cd47a2fc7c2ff5bb4d8d1f8a8b7d492b9ac30344f5b594f4bc53335847
languageName: node
linkType: hard

Expand Down Expand Up @@ -6315,7 +6315,7 @@ __metadata:
"@reduxjs/toolkit": ^1.9.1
"@sora-substrate/type-definitions": ^1.17.7
"@substrate/connect": ^0.8.9
"@subwallet/chain-list": 0.2.89
"@subwallet/chain-list": 0.2.95-beta.0
"@subwallet/extension-base": ^1.3.2-0
"@subwallet/extension-chains": ^1.3.2-0
"@subwallet/extension-dapp": ^1.3.2-0
Expand Down

0 comments on commit ff02920

Please sign in to comment.