From ff02920da2a3595457f4a761db84c701e0581be7 Mon Sep 17 00:00:00 2001 From: dominhquang Date: Thu, 19 Dec 2024 10:22:50 +0700 Subject: [PATCH] Cherry pick code from web-runner 1.2.32 for mobile --- package.json | 2 +- packages/extension-base/package.json | 2 +- .../src/core/substrate/xcm-parser.ts | 7 +- .../helpers/subscribe/substrate/index.ts | 15 ++-- .../src/services/chain-service/constants.ts | 4 +- .../utils/new-utils/asset-asset-validate.ts | 2 +- .../services/earning-service/handlers/base.ts | 4 +- .../handlers/native-staking/tao.ts | 80 ++++++++----------- .../services/earning-service/utils/index.ts | 15 ---- .../migration-service/scripts/index.ts | 3 +- .../src/services/transaction-service/utils.ts | 4 + yarn.lock | 10 +-- 12 files changed, 63 insertions(+), 85 deletions(-) diff --git a/package.json b/package.json index 176e5dd7b7..90a38655b2 100644 --- a/package.json +++ b/package.json @@ -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 ", diff --git a/packages/extension-base/package.json b/packages/extension-base/package.json index 2d848a3178..c65b5726ac 100644 --- a/packages/extension-base/package.json +++ b/packages/extension-base/package.json @@ -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", diff --git a/packages/extension-base/src/core/substrate/xcm-parser.ts b/packages/extension-base/src/core/substrate/xcm-parser.ts index 4799c230f6..6ff9d36633 100644 --- a/packages/extension-base/src/core/substrate/xcm-parser.ts +++ b/packages/extension-base/src/core/substrate/xcm-parser.ts @@ -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, version: number): Record { +export function _adaptX1Interior (_assetIdentifier: Record, version: number): Record { + const assetIdentifier = structuredClone(_assetIdentifier); const interior = assetIdentifier.interior as Record; 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 diff --git a/packages/extension-base/src/services/balance-service/helpers/subscribe/substrate/index.ts b/packages/extension-base/src/services/balance-service/helpers/subscribe/substrate/index.ts index 80fc3ffc1b..f9c5c91950 100644 --- a/packages/extension-base/src/services/balance-service/helpers/subscribe/substrate/index.ts +++ b/packages/extension-base/src/services/balance-service/helpers/subscribe/substrate/index.ts @@ -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'; @@ -144,13 +142,13 @@ const subscribeWithSystemAccountPallet = async ({ addresses, callback, chainInfo ); } - let bittensorStakingBalances = new Array(addresses.length).fill(BigInt(0)); + let bittensorStakingBalances: BigN[] = new Array(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()); })); } @@ -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], @@ -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]) } ]; diff --git a/packages/extension-base/src/services/chain-service/constants.ts b/packages/extension-base/src/services/chain-service/constants.ts index 41e7a66e71..bde3bec11f 100644 --- a/packages/extension-base/src/services/chain-service/constants.ts +++ b/packages/extension-base/src/services/chain-service/constants.ts @@ -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'] }; diff --git a/packages/extension-base/src/services/chain-service/health-check/utils/new-utils/asset-asset-validate.ts b/packages/extension-base/src/services/chain-service/health-check/utils/new-utils/asset-asset-validate.ts index 1f32dd3f23..2483d81992 100644 --- a/packages/extension-base/src/services/chain-service/health-check/utils/new-utils/asset-asset-validate.ts +++ b/packages/extension-base/src/services/chain-service/health-check/utils/new-utils/asset-asset-validate.ts @@ -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']; diff --git a/packages/extension-base/src/services/earning-service/handlers/base.ts b/packages/extension-base/src/services/earning-service/handlers/base.ts index 7ac0b8d859..c2c8a07200 100644 --- a/packages/extension-base/src/services/earning-service/handlers/base.ts +++ b/packages/extension-base/src/services/earning-service/handlers/base.ts @@ -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(); } diff --git a/packages/extension-base/src/services/earning-service/handlers/native-staking/tao.ts b/packages/extension-base/src/services/earning-service/handlers/native-staking/tao.ts index 01eac870f7..b7ca273b6b 100644 --- a/packages/extension-base/src/services/earning-service/handlers/native-staking/tao.ts +++ b/packages/extension-base/src/services/earning-service/handlers/native-staking/tao.ts @@ -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'; @@ -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); @@ -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 */ @@ -76,7 +73,7 @@ export async function fetchDelegates (): Promise { 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', @@ -92,7 +89,7 @@ export async function fetchTaoDelegateState (address: string): Promise { - // 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 */ @@ -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() }); } @@ -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; @@ -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, @@ -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; }) ); diff --git a/packages/extension-base/src/services/earning-service/utils/index.ts b/packages/extension-base/src/services/earning-service/utils/index.ts index 8819111c75..6f6250a7aa 100644 --- a/packages/extension-base/src/services/earning-service/utils/index.ts +++ b/packages/extension-base/src/services/earning-service/utils/index.ts @@ -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'; @@ -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; -} diff --git a/packages/extension-base/src/services/migration-service/scripts/index.ts b/packages/extension-base/src/services/migration-service/scripts/index.ts index 5f54bf6af8..58b6219678 100644 --- a/packages/extension-base/src/services/migration-service/scripts/index.ts +++ b/packages/extension-base/src/services/migration-service/scripts/index.ts @@ -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'; @@ -37,7 +36,7 @@ export default >{ '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, diff --git a/packages/extension-base/src/services/transaction-service/utils.ts b/packages/extension-base/src/services/transaction-service/utils.ts index f1f547117c..953ab1431e 100644 --- a/packages/extension-base/src/services/transaction-service/utils.ts +++ b/packages/extension-base/src/services/transaction-service/utils.ts @@ -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}`); diff --git a/yarn.lock b/yarn.lock index 00779becac..c17cc9dd91 100644 --- a/yarn.lock +++ b/yarn.lock @@ -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 @@ -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