@subwallet/extension-base 1.2.33-0 → 1.3.2-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/background/KoniTypes.d.ts +5 -1
  2. package/cjs/constants/index.js +7 -1
  3. package/cjs/koni/api/nft/config.js +11 -1
  4. package/cjs/koni/api/nft/index.js +9 -0
  5. package/cjs/koni/api/nft/ternoa_nft/index.js +174 -0
  6. package/cjs/koni/api/staking/bonding/utils.js +1 -1
  7. package/cjs/koni/background/handlers/Extension.js +67 -32
  8. package/cjs/packageInfo.js +1 -1
  9. package/cjs/services/balance-service/helpers/subscribe/substrate/index.js +16 -6
  10. package/cjs/services/chain-service/constants.js +2 -1
  11. package/cjs/services/chain-service/index.js +11 -14
  12. package/cjs/services/earning-service/constants/chains.js +2 -1
  13. package/cjs/services/earning-service/handlers/native-staking/index.js +8 -1
  14. package/cjs/services/earning-service/handlers/native-staking/tao.js +415 -0
  15. package/cjs/services/earning-service/service.js +3 -0
  16. package/cjs/services/earning-service/utils/index.js +13 -0
  17. package/cjs/services/keyring-service/context/handlers/Modify.js +11 -3
  18. package/cjs/services/keyring-service/context/state.js +2 -3
  19. package/cjs/services/keyring-service/index.js +1 -1
  20. package/cjs/services/swap-service/handler/chainflip-handler.js +13 -5
  21. package/cjs/services/transaction-service/utils.js +3 -0
  22. package/cjs/types/swap/index.js +4 -2
  23. package/cjs/utils/account/derive/info/solo.js +2 -0
  24. package/cjs/utils/account/derive/info/unified.js +2 -0
  25. package/cjs/utils/account/transform.js +4 -4
  26. package/constants/index.d.ts +2 -0
  27. package/constants/index.js +2 -0
  28. package/koni/api/nft/config.d.ts +4 -0
  29. package/koni/api/nft/config.js +6 -0
  30. package/koni/api/nft/index.js +9 -0
  31. package/koni/api/nft/ternoa_nft/index.d.ts +32 -0
  32. package/koni/api/nft/ternoa_nft/index.js +167 -0
  33. package/koni/api/staking/bonding/utils.js +1 -1
  34. package/koni/background/handlers/Extension.d.ts +1 -0
  35. package/koni/background/handlers/Extension.js +38 -3
  36. package/package.json +16 -6
  37. package/packageInfo.js +1 -1
  38. package/services/balance-service/helpers/subscribe/substrate/index.js +10 -0
  39. package/services/chain-service/constants.d.ts +1 -0
  40. package/services/chain-service/constants.js +2 -1
  41. package/services/chain-service/index.js +11 -14
  42. package/services/earning-service/constants/chains.d.ts +1 -0
  43. package/services/earning-service/constants/chains.js +2 -1
  44. package/services/earning-service/handlers/native-staking/index.d.ts +1 -0
  45. package/services/earning-service/handlers/native-staking/index.js +2 -1
  46. package/services/earning-service/handlers/native-staking/tao.d.ts +49 -0
  47. package/services/earning-service/handlers/native-staking/tao.js +399 -0
  48. package/services/earning-service/service.js +4 -1
  49. package/services/earning-service/utils/index.d.ts +2 -0
  50. package/services/earning-service/utils/index.js +12 -0
  51. package/services/keyring-service/context/handlers/Modify.js +11 -3
  52. package/services/keyring-service/context/state.js +2 -3
  53. package/services/keyring-service/index.d.ts +1 -1
  54. package/services/keyring-service/index.js +1 -1
  55. package/services/swap-service/handler/chainflip-handler.js +13 -5
  56. package/services/transaction-service/utils.js +3 -0
  57. package/types/swap/index.d.ts +1 -0
  58. package/types/swap/index.js +2 -1
  59. package/utils/account/derive/info/solo.js +2 -0
  60. package/utils/account/derive/info/unified.js +2 -0
  61. package/utils/account/transform.js +4 -4
@@ -19,7 +19,9 @@ var _wasm = require("@subwallet/extension-base/koni/api/contract-handler/wasm");
19
19
  var _utils = require("@subwallet/extension-base/koni/api/contract-handler/wasm/utils");
20
20
  var _constants2 = require("@subwallet/extension-base/services/chain-service/constants");
21
21
  var _utils2 = require("@subwallet/extension-base/services/chain-service/utils");
22
- var _utils3 = require("@subwallet/extension-base/utils");
22
+ var _tao = require("@subwallet/extension-base/services/earning-service/handlers/native-staking/tao");
23
+ var _utils3 = require("@subwallet/extension-base/services/earning-service/utils");
24
+ var _utils4 = require("@subwallet/extension-base/utils");
23
25
  var _bignumber = _interopRequireDefault(require("bignumber.js"));
24
26
  var _evm = require("../evm");
25
27
  var _equilibrium = require("./equilibrium");
@@ -138,6 +140,13 @@ const subscribeWithSystemAccountPallet = async _ref => {
138
140
  args: addresses
139
141
  });
140
142
  }
143
+ let bittensorStakingBalances = new Array(addresses.length).fill(BigInt(0));
144
+ if (['bittensor'].includes(chainInfo.slug)) {
145
+ bittensorStakingBalances = await Promise.all(addresses.map(async address => {
146
+ const rawDelegateState = await (0, _tao.fetchTaoDelegateState)(address);
147
+ return (0, _utils3.getTaoTotalStake)(rawDelegateState);
148
+ }));
149
+ }
141
150
  const subscription = substrateApi.subscribeDataWithMulti(params, rs => {
142
151
  const balances = rs[systemAccountKey];
143
152
  const poolMemberInfos = rs[poolMembersKey];
@@ -151,6 +160,7 @@ const subscribeWithSystemAccountPallet = async _ref => {
151
160
  const nominationPoolBalance = poolMemberInfo ? (0, _nominationpoolsPallet._getTotalStakeInNominationPool)(poolMemberInfo) : BigInt(0);
152
161
  totalLockedFromTransfer += nominationPoolBalance;
153
162
  }
163
+ totalLockedFromTransfer += bittensorStakingBalances[index];
154
164
  return {
155
165
  address: addresses[index],
156
166
  tokenSlug: (0, _utils2._getChainNativeTokenSlug)(chainInfo),
@@ -189,7 +199,7 @@ const subscribeForeignAssetBalance = async _ref2 => {
189
199
  substrateApi
190
200
  } = _ref2;
191
201
  const foreignAssetsAccountKey = 'query_foreignAssets_account';
192
- const tokenMap = (0, _utils3.filterAssetsByChainAndType)(assetMap, chainInfo.slug, [_types._AssetType.LOCAL]);
202
+ const tokenMap = (0, _utils4.filterAssetsByChainAndType)(assetMap, chainInfo.slug, [_types._AssetType.LOCAL]);
193
203
  const unsubList = await Promise.all(Object.values(tokenMap).map(tokenInfo => {
194
204
  try {
195
205
  if ((0, _utils2._isBridgedToken)(tokenInfo)) {
@@ -256,7 +266,7 @@ const subscribePSP22Balance = _ref3 => {
256
266
  } = _ref3;
257
267
  const chain = chainInfo.slug;
258
268
  const psp22ContractMap = {};
259
- const tokenList = (0, _utils3.filterAssetsByChainAndType)(assetMap, chain, [_types._AssetType.PSP22]);
269
+ const tokenList = (0, _utils4.filterAssetsByChainAndType)(assetMap, chain, [_types._AssetType.PSP22]);
260
270
  Object.entries(tokenList).forEach(_ref4 => {
261
271
  let [slug, tokenInfo] = _ref4;
262
272
  psp22ContractMap[slug] = (0, _wasm.getPSP22ContractPromise)(substrateApi.api, (0, _utils2._getContractAddressOfToken)(tokenInfo));
@@ -317,7 +327,7 @@ const subscribeTokensAccountsPallet = async _ref5 => {
317
327
  } = _ref5;
318
328
  const tokensAccountsKey = 'query_tokens_accounts';
319
329
  const tokenTypes = includeNativeToken ? [_types._AssetType.NATIVE, _types._AssetType.LOCAL] : [_types._AssetType.LOCAL];
320
- const tokenMap = (0, _utils3.filterAssetsByChainAndType)(assetMap, chainInfo.slug, tokenTypes);
330
+ const tokenMap = (0, _utils4.filterAssetsByChainAndType)(assetMap, chainInfo.slug, tokenTypes);
321
331
  const unsubList = await Promise.all(Object.values(tokenMap).map(tokenInfo => {
322
332
  try {
323
333
  const params = [{
@@ -363,7 +373,7 @@ const subscribeAssetsAccountPallet = async _ref6 => {
363
373
  substrateApi
364
374
  } = _ref6;
365
375
  const assetsAccountKey = 'query_assets_account';
366
- const tokenMap = (0, _utils3.filterAssetsByChainAndType)(assetMap, chainInfo.slug, [_types._AssetType.LOCAL]);
376
+ const tokenMap = (0, _utils4.filterAssetsByChainAndType)(assetMap, chainInfo.slug, [_types._AssetType.LOCAL]);
367
377
  Object.values(tokenMap).forEach(token => {
368
378
  if (_constants2._MANTA_ZK_CHAIN_GROUP.includes(token.originChain) && token.symbol.startsWith(_constants2._ZK_ASSET_PREFIX)) {
369
379
  delete tokenMap[token.slug];
@@ -432,7 +442,7 @@ const subscribeOrmlTokensPallet = async _ref7 => {
432
442
  substrateApi
433
443
  } = _ref7;
434
444
  const ormlTokensAccountsKey = 'query_ormlTokens_accounts';
435
- const tokenMap = (0, _utils3.filterAssetsByChainAndType)(assetMap, chainInfo.slug, [_types._AssetType.LOCAL]);
445
+ const tokenMap = (0, _utils4.filterAssetsByChainAndType)(assetMap, chainInfo.slug, [_types._AssetType.LOCAL]);
436
446
  const unsubList = Object.values(tokenMap).map(tokenInfo => {
437
447
  try {
438
448
  const params = [{
@@ -64,7 +64,8 @@ const _NFT_CHAIN_GROUP = {
64
64
  unique_evm: ['unique_evm'],
65
65
  bitcountry: ['bitcountry', 'pioneer', 'continuum_network'],
66
66
  vara: ['vara_network'],
67
- avail: ['avail_mainnet']
67
+ avail: ['avail_mainnet'],
68
+ ternoa: ['ternoa', 'ternoa_alphanet']
68
69
  };
69
70
 
70
71
  // Staking--------------------------------------------------------------------------------------------------------------
@@ -1603,21 +1603,18 @@ class ChainService {
1603
1603
  const assetSettings = await this.getAssetSettings();
1604
1604
  const activeChainSlugs = this.getActiveChainSlugs();
1605
1605
  const assetRegistry = this.getAssetRegistry();
1606
- if (Object.keys(assetSettings).length === 0) {
1607
- // only initiate the first time
1608
- Object.values(assetRegistry).forEach(assetInfo => {
1609
- const isSettingExisted = (assetInfo.slug in assetSettings);
1606
+ Object.values(assetRegistry).forEach(assetInfo => {
1607
+ const isSettingExisted = (assetInfo.slug in assetSettings);
1610
1608
 
1611
- // Set visible for every enabled chains
1612
- if (activeChainSlugs.includes(assetInfo.originChain) && !isSettingExisted) {
1613
- // Setting only exist when set either by chain settings or user
1614
- assetSettings[assetInfo.slug] = {
1615
- visible: true
1616
- };
1617
- }
1618
- });
1619
- this.setAssetSettings(assetSettings, false);
1620
- }
1609
+ // Set visible for every enabled chains
1610
+ if (activeChainSlugs.includes(assetInfo.originChain) && !isSettingExisted) {
1611
+ // Setting only exist when set either by chain settings or user
1612
+ assetSettings[assetInfo.slug] = {
1613
+ visible: true
1614
+ };
1615
+ }
1616
+ });
1617
+ this.setAssetSettings(assetSettings, false);
1621
1618
  this.eventService.emit('asset.ready', true);
1622
1619
  }
1623
1620
  setAssetSettings(assetSettings) {
@@ -22,7 +22,8 @@ const _STAKING_CHAIN_GROUP = {
22
22
  liquidStaking: ['bifrost_dot', 'acala', 'parallel', 'moonbeam'],
23
23
  lending: ['interlay'],
24
24
  krest_network: ['krest_network'],
25
- manta: ['manta_network']
25
+ manta: ['manta_network'],
26
+ bittensor: ['bittensor', 'bittensor_devnet']
26
27
  };
27
28
  exports._STAKING_CHAIN_GROUP = _STAKING_CHAIN_GROUP;
28
29
  const TON_CHAINS = ['ton', 'ton_testnet'];
@@ -28,7 +28,14 @@ Object.defineProperty(exports, "RelayNativeStakingPoolHandler", {
28
28
  return _relayChain.default;
29
29
  }
30
30
  });
31
+ Object.defineProperty(exports, "TaoNativeStakingPoolHandler", {
32
+ enumerable: true,
33
+ get: function () {
34
+ return _tao.default;
35
+ }
36
+ });
31
37
  var _amplitude = _interopRequireDefault(require("./amplitude"));
32
38
  var _astar = _interopRequireDefault(require("./astar"));
33
39
  var _relayChain = _interopRequireDefault(require("./relay-chain"));
34
- var _paraChain = _interopRequireDefault(require("./para-chain"));
40
+ var _paraChain = _interopRequireDefault(require("./para-chain"));
41
+ var _tao = _interopRequireDefault(require("./tao"));
@@ -0,0 +1,415 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = exports.bittensorApiKey = exports.BITTENSOR_API_KEY_2 = exports.BITTENSOR_API_KEY_1 = void 0;
8
+ exports.fetchDelegates = fetchDelegates;
9
+ exports.fetchTaoDelegateState = fetchTaoDelegateState;
10
+ var _TransactionError = require("@subwallet/extension-base/background/errors/TransactionError");
11
+ var _KoniTypes = require("@subwallet/extension-base/background/KoniTypes");
12
+ var _constants = require("@subwallet/extension-base/constants");
13
+ var _utils = require("@subwallet/extension-base/koni/api/staking/bonding/utils");
14
+ var _basePara = _interopRequireDefault(require("@subwallet/extension-base/services/earning-service/handlers/native-staking/base-para"));
15
+ var _types = require("@subwallet/extension-base/types");
16
+ var _utils2 = require("@subwallet/extension-base/utils");
17
+ var _bignumber = _interopRequireDefault(require("bignumber.js"));
18
+ var _util = require("@polkadot/util");
19
+ var _utils3 = require("../../utils");
20
+ // Copyright 2019-2022 @subwallet/extension-base
21
+ // SPDX-License-Identifier: Apache-2.0
22
+
23
+ // interface ValidatorName {
24
+ // count: number;
25
+ // delegates: {
26
+ // name: string;
27
+ // }[];
28
+ // }
29
+ const BITTENSOR_API_KEY_1 = process.env.BITTENSOR_API_KEY_1 || '';
30
+ exports.BITTENSOR_API_KEY_1 = BITTENSOR_API_KEY_1;
31
+ const BITTENSOR_API_KEY_2 = process.env.BITTENSOR_API_KEY_2 || '';
32
+ exports.BITTENSOR_API_KEY_2 = BITTENSOR_API_KEY_2;
33
+ function random() {
34
+ for (var _len = arguments.length, keys = new Array(_len), _key = 0; _key < _len; _key++) {
35
+ keys[_key] = arguments[_key];
36
+ }
37
+ const validKeys = keys.filter(key => key);
38
+ const randomIndex = Math.floor(Math.random() * validKeys.length);
39
+ return validKeys[randomIndex];
40
+ }
41
+ const bittensorApiKey = () => {
42
+ return random(BITTENSOR_API_KEY_1, BITTENSOR_API_KEY_2);
43
+ };
44
+
45
+ /* Fetch data */
46
+ exports.bittensorApiKey = bittensorApiKey;
47
+ async function fetchDelegates() {
48
+ const apiKey = bittensorApiKey();
49
+ return new Promise(function (resolve) {
50
+ fetch('https://api.taostats.io/api/v1/validator?order=amount%3Adesc&limit=100', {
51
+ method: 'GET',
52
+ headers: {
53
+ 'Content-Type': 'application/json',
54
+ Authorization: `${apiKey}`
55
+ }
56
+ }).then(resp => {
57
+ resolve(resp.json());
58
+ }).catch(console.error);
59
+ });
60
+ }
61
+ async function fetchTaoDelegateState(address) {
62
+ const apiKey = bittensorApiKey();
63
+ return new Promise(function (resolve) {
64
+ fetch(`https://api.taostats.io/api/v1/delegate/balance?nominator_address=${address}`, {
65
+ method: 'GET',
66
+ headers: {
67
+ 'Content-Type': 'application/json',
68
+ Authorization: `${apiKey}`
69
+ }
70
+ }).then(resp => {
71
+ resolve(resp.json());
72
+ }).catch(console.error);
73
+ });
74
+ }
75
+
76
+ /* Fetch data */
77
+
78
+ const testnetDelegate = {
79
+ '5G6wdAdS7hpBuH1tjuZDhpzrGw9Wf71WEVakDCxHDm1cxEQ2': {
80
+ name: '0x436c6f776e4e616d65f09fa4a1',
81
+ url: 'https://example.com ',
82
+ image: 'https://example.com/image.png',
83
+ discord: '0xe28094446973636f7264',
84
+ description: 'This is an example identity.',
85
+ additional: ''
86
+ }
87
+ };
88
+ class TaoNativeStakingPoolHandler extends _basePara.default {
89
+ /* Unimplemented function */
90
+ handleYieldWithdraw(address, unstakingInfo) {
91
+ return Promise.reject(new _TransactionError.TransactionError(_types.BasicTxErrorType.UNSUPPORTED));
92
+ }
93
+ handleYieldCancelUnstake(params) {
94
+ return Promise.reject(new _TransactionError.TransactionError(_types.BasicTxErrorType.UNSUPPORTED));
95
+ }
96
+ /* Unimplemented function */
97
+
98
+ // async fetchDelegatesInfo (address: string): Promise<ValidatorName> {
99
+ // const apiKey = this.bittensorApiKey;
100
+
101
+ // return new Promise(function (resolve) {
102
+ // fetch(`https://api.taostats.io/api/v1/delegate/info?address=${address}`, {
103
+ // method: 'GET',
104
+ // headers: {
105
+ // 'Content-Type': 'application/json',
106
+ // Authorization: `${apiKey}`
107
+ // }
108
+ // }).then((resp) => {
109
+ // resolve(resp.json());
110
+ // }).catch(console.error);
111
+ // });
112
+ // }
113
+
114
+ /* Subscribe pool info */
115
+
116
+ async subscribePoolInfo(callback) {
117
+ let cancel = false;
118
+ const substrateApi = this.substrateApi;
119
+ const updateStakingInfo = async () => {
120
+ try {
121
+ if (cancel) {
122
+ return;
123
+ }
124
+ const minDelegatorStake = await substrateApi.api.query.subtensorModule.nominatorMinRequiredStake();
125
+ const BNminDelegatorStake = new _bignumber.default(minDelegatorStake.toString());
126
+ const data = {
127
+ ...this.baseInfo,
128
+ type: this.type,
129
+ metadata: {
130
+ ...this.metadataInfo,
131
+ description: this.getDescription('0')
132
+ },
133
+ statistic: {
134
+ assetEarning: [{
135
+ slug: this.nativeToken.slug
136
+ }],
137
+ maxCandidatePerFarmer: 16,
138
+ maxWithdrawalRequestPerFarmer: 1,
139
+ earningThreshold: {
140
+ join: BNminDelegatorStake.toString(),
141
+ defaultUnstake: '0',
142
+ fastUnstake: '0'
143
+ },
144
+ eraTime: 1.2,
145
+ era: 0,
146
+ unstakingPeriod: 1.2
147
+ }
148
+ };
149
+ callback(data);
150
+ } catch (error) {
151
+ console.log(error);
152
+ }
153
+ };
154
+ const subscribeStakingMetadataInterval = () => {
155
+ updateStakingInfo().catch(console.error);
156
+ };
157
+ await substrateApi.isReady;
158
+ subscribeStakingMetadataInterval();
159
+ const interval = setInterval(subscribeStakingMetadataInterval, _constants.BITTENSOR_REFRESH_STAKE_APY);
160
+ return () => {
161
+ cancel = true;
162
+ clearInterval(interval);
163
+ };
164
+ }
165
+
166
+ /* Subscribe pool position */
167
+
168
+ async parseNominatorMetadata(chainInfo, address, delegatorState) {
169
+ const nominationList = [];
170
+ const getMinDelegatorStake = this.substrateApi.api.query.subtensorModule.nominatorMinRequiredStake();
171
+ const minDelegatorStake = (await getMinDelegatorStake).toString();
172
+ let allActiveStake = _util.BN_ZERO;
173
+ for (const delegate of delegatorState) {
174
+ const activeStake = delegate.amount;
175
+ const bnActiveStake = new _util.BN(activeStake);
176
+ if (bnActiveStake.gt(_util.BN_ZERO)) {
177
+ const delegationStatus = _types.EarningStatus.EARNING_REWARD;
178
+ allActiveStake = allActiveStake.add(bnActiveStake);
179
+ nominationList.push({
180
+ status: delegationStatus,
181
+ chain: chainInfo.slug,
182
+ validatorAddress: delegate.owner,
183
+ activeStake: activeStake,
184
+ validatorMinStake: minDelegatorStake
185
+ });
186
+ }
187
+ }
188
+ const stakingStatus = (0, _utils.getEarningStatusByNominations)(allActiveStake, nominationList);
189
+ return {
190
+ status: stakingStatus,
191
+ balanceToken: this.nativeToken.slug,
192
+ totalStake: allActiveStake.toString(),
193
+ activeStake: allActiveStake.toString(),
194
+ unstakeBalance: '0',
195
+ isBondedBefore: true,
196
+ nominations: nominationList,
197
+ unstakings: []
198
+ };
199
+ }
200
+ async subscribePoolPosition(useAddresses, rsCallback) {
201
+ let cancel = false;
202
+ const substrateApi = await this.substrateApi.isReady;
203
+ const defaultInfo = this.baseInfo;
204
+ const chainInfo = this.chainInfo;
205
+ const getDevnetPoolPosition = async () => {
206
+ const testnetAddress = Object.keys(testnetDelegate)[0];
207
+ const delegatorState = [];
208
+ let bnTotalBalance = _util.BN_ZERO;
209
+ const stakePromises = useAddresses.map(async address => {
210
+ const stakeAmount = (await substrateApi.api.query.subtensorModule.stake(testnetAddress, address)).toString();
211
+ const bnStakeAmount = new _util.BN(stakeAmount);
212
+ bnTotalBalance = bnTotalBalance.add(bnStakeAmount);
213
+ delegatorState.push({
214
+ owner: testnetAddress,
215
+ amount: bnStakeAmount.toString()
216
+ });
217
+ rsCallback({
218
+ ...defaultInfo,
219
+ type: this.type,
220
+ address: address,
221
+ balanceToken: this.nativeToken.slug,
222
+ totalStake: bnTotalBalance.toString(),
223
+ activeStake: bnStakeAmount.toString(),
224
+ unstakeBalance: '0',
225
+ status: _types.EarningStatus.EARNING_REWARD,
226
+ isBondedBefore: true,
227
+ nominations: delegatorState.map(delegate => ({
228
+ chain: this.chain,
229
+ validatorAddress: delegate.owner,
230
+ activeStake: delegate.amount,
231
+ status: _types.EarningStatus.EARNING_REWARD
232
+ })),
233
+ unstakings: []
234
+ });
235
+ });
236
+ await Promise.all(stakePromises);
237
+ };
238
+ const getMainnetPoolPosition = async () => {
239
+ const rawDelegateStateInfos = await Promise.all(useAddresses.map(address => fetchTaoDelegateState(address)));
240
+ if (rawDelegateStateInfos.length > 0) {
241
+ rawDelegateStateInfos.forEach((rawDelegateStateInfo, i) => {
242
+ const owner = (0, _utils2.reformatAddress)(useAddresses[i], 42);
243
+ const delegatorState = [];
244
+ let bnTotalBalance = _util.BN_ZERO;
245
+ const delegateStateInfo = rawDelegateStateInfo.items;
246
+ for (const delegate of delegateStateInfo) {
247
+ bnTotalBalance = bnTotalBalance.add(new _util.BN(delegate.balance));
248
+ delegatorState.push({
249
+ owner: delegate.delegate_address.ss58,
250
+ amount: delegate.balance.toString()
251
+ });
252
+ }
253
+ if (delegateStateInfo && delegateStateInfo.length > 0) {
254
+ this.parseNominatorMetadata(chainInfo, owner, delegatorState).then(nominatorMetadata => {
255
+ rsCallback({
256
+ ...defaultInfo,
257
+ ...nominatorMetadata,
258
+ address: owner,
259
+ type: this.type
260
+ });
261
+ }).catch(console.error);
262
+ } else {
263
+ rsCallback({
264
+ ...defaultInfo,
265
+ type: this.type,
266
+ address: owner,
267
+ balanceToken: this.nativeToken.slug,
268
+ totalStake: '0',
269
+ activeStake: '0',
270
+ unstakeBalance: '0',
271
+ status: _types.EarningStatus.NOT_STAKING,
272
+ isBondedBefore: false,
273
+ nominations: [],
274
+ unstakings: []
275
+ });
276
+ }
277
+ });
278
+ }
279
+ };
280
+ const getStakingPositionInterval = async () => {
281
+ if (cancel) {
282
+ return;
283
+ }
284
+ if (this.chain === 'bittensor_devnet') {
285
+ await getDevnetPoolPosition();
286
+ } else {
287
+ await getMainnetPoolPosition();
288
+ }
289
+ };
290
+ getStakingPositionInterval().catch(console.error);
291
+ const intervalId = setInterval(() => {
292
+ getStakingPositionInterval().catch(console.error);
293
+ }, _constants.BITTENSOR_REFRESH_STAKE_INFO);
294
+ return () => {
295
+ cancel = true;
296
+ clearInterval(intervalId);
297
+ };
298
+ }
299
+
300
+ /* Subscribe pool position */
301
+
302
+ /* Get pool targets */
303
+
304
+ // eslint-disable-next-line @typescript-eslint/require-await
305
+ async getDevnetPoolTargets() {
306
+ const _topValidator = testnetDelegate;
307
+ const validatorAddresses = Object.keys(_topValidator);
308
+ return validatorAddresses.map(address => {
309
+ return {
310
+ address: address,
311
+ totalStake: '0',
312
+ ownStake: '0',
313
+ otherStake: '0',
314
+ minBond: '0',
315
+ nominatorCount: 0,
316
+ commission: '0',
317
+ expectedReturn: 0,
318
+ blocked: false,
319
+ isVerified: false,
320
+ chain: this.chain,
321
+ isCrowded: false,
322
+ identity: address
323
+ };
324
+ });
325
+ }
326
+ async getMainnetPoolTargets() {
327
+ const _topValidator = await fetchDelegates();
328
+ const topValidator = _topValidator;
329
+ const getNominatorMinRequiredStake = this.substrateApi.api.query.subtensorModule.nominatorMinRequiredStake();
330
+ const nominatorMinRequiredStake = (await getNominatorMinRequiredStake).toString();
331
+ const bnMinBond = new _util.BN(nominatorMinRequiredStake);
332
+ const validatorList = topValidator.validators;
333
+ const validatorAddresses = Object.keys(validatorList);
334
+ const results = await Promise.all(validatorAddresses.map(i => {
335
+ const address = validatorList[i].hot_key.ss58;
336
+ const bnTotalStake = new _util.BN(validatorList[i].amount);
337
+ const bnOwnStake = new _util.BN(validatorList[i].validator_stake);
338
+ const otherStake = bnTotalStake.sub(bnOwnStake);
339
+ const nominatorCount = validatorList[i].nominators;
340
+ const commission = validatorList[i].take;
341
+ const roundedCommission = (parseFloat(commission) * 100).toFixed(0);
342
+ const apr = (parseFloat(validatorList[i].apr) / 10 ** 9 * 100).toFixed(2);
343
+ const apyCalculate = (0, _utils3.calculateReward)(parseFloat(apr));
344
+
345
+ // let name = '';
346
+ // const delegateInfo = await this.fetchDelegatesInfo(address);
347
+
348
+ // name = delegateInfo.delegates[0]?.name || address;
349
+
350
+ return {
351
+ address: address,
352
+ totalStake: bnTotalStake.toString(),
353
+ ownStake: bnOwnStake.toString(),
354
+ otherStake: otherStake.toString(),
355
+ minBond: bnMinBond.toString(),
356
+ nominatorCount: nominatorCount,
357
+ commission: roundedCommission,
358
+ expectedReturn: apyCalculate.apy,
359
+ blocked: false,
360
+ isVerified: false,
361
+ chain: this.chain,
362
+ isCrowded: false,
363
+ identity: address // name
364
+ };
365
+ }));
366
+
367
+ return results;
368
+ }
369
+ async getPoolTargets() {
370
+ if (this.chain === 'bittensor_devnet') {
371
+ return this.getDevnetPoolTargets();
372
+ } else {
373
+ return this.getMainnetPoolTargets();
374
+ }
375
+ }
376
+
377
+ /* Get pool targets */
378
+
379
+ /* Join pool action */
380
+
381
+ async createJoinExtrinsic(data, positionInfo) {
382
+ let bondDest = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'Staked';
383
+ const {
384
+ amount,
385
+ selectedValidators: targetValidators
386
+ } = data;
387
+ const chainApi = await this.substrateApi.isReady;
388
+ const binaryAmount = new _util.BN(amount);
389
+ const selectedValidatorInfo = targetValidators[0];
390
+ const hotkey = selectedValidatorInfo.address;
391
+ const extrinsic = chainApi.api.tx.subtensorModule.addStake(hotkey, binaryAmount);
392
+ return [extrinsic, {
393
+ slug: this.nativeToken.slug,
394
+ amount: '0'
395
+ }];
396
+ }
397
+
398
+ /* Join pool action */
399
+
400
+ /* Leave pool action */
401
+
402
+ async handleYieldUnstake(amount, address, selectedTarget) {
403
+ const apiPromise = await this.substrateApi.isReady;
404
+ const binaryAmount = new _util.BN(amount);
405
+ const poolPosition = await this.getPoolPosition(address);
406
+ if (!selectedTarget || !poolPosition) {
407
+ return Promise.reject(new _TransactionError.TransactionError(_types.BasicTxErrorType.INVALID_PARAMS));
408
+ }
409
+ const extrinsic = apiPromise.api.tx.subtensorModule.removeStake(selectedTarget, binaryAmount);
410
+ return [_KoniTypes.ExtrinsicType.STAKING_LEAVE_POOL, extrinsic];
411
+ }
412
+
413
+ /* Leave pool action */
414
+ }
415
+ exports.default = TaoNativeStakingPoolHandler;
@@ -72,6 +72,9 @@ class EarningService {
72
72
  if (_constants2._STAKING_CHAIN_GROUP.amplitude.includes(chain)) {
73
73
  handlers.push(new _handlers.AmplitudeNativeStakingPoolHandler(this.state, chain));
74
74
  }
75
+ if (_constants2._STAKING_CHAIN_GROUP.bittensor.includes(chain)) {
76
+ handlers.push(new _handlers.TaoNativeStakingPoolHandler(this.state, chain));
77
+ }
75
78
  if (_constants2._STAKING_CHAIN_GROUP.nominationPool.includes(chain)) {
76
79
  handlers.push(new _handlers.NominationPoolHandler(this.state, chain));
77
80
  }
@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.applyDecimal = applyDecimal;
7
7
  exports.calculateReward = calculateReward;
8
+ exports.getTaoTotalStake = getTaoTotalStake;
8
9
  exports.isActionFromValidator = isActionFromValidator;
9
10
  exports.isNominationPool = exports.isNativeStakingPool = exports.isLiquidPool = exports.isLendingPool = void 0;
10
11
  exports.parseIdentity = parseIdentity;
@@ -116,6 +117,8 @@ function isActionFromValidator(stakingType, chain) {
116
117
  return true;
117
118
  } else if (_constants._STAKING_CHAIN_GROUP.para.includes(chain)) {
118
119
  return true;
120
+ } else if (_constants._STAKING_CHAIN_GROUP.bittensor.includes(chain)) {
121
+ return true;
119
122
  }
120
123
  return false;
121
124
  }
@@ -138,4 +141,14 @@ exports.isLendingPool = isLendingPool;
138
141
  function applyDecimal(bnNumber, decimals) {
139
142
  const bnDecimals = new _util.BN((10 ** decimals).toString());
140
143
  return bnNumber.div(bnDecimals);
144
+ }
145
+ function getTaoTotalStake(rawDelegateState) {
146
+ const nodeInfos = rawDelegateState.items;
147
+ const stakes = nodeInfos.map(stake => stake.balance);
148
+ let totalStake = BigInt(0);
149
+ for (const _stake of stakes) {
150
+ const stakeAmount = BigInt(_stake);
151
+ totalStake += stakeAmount;
152
+ }
153
+ return totalStake;
141
154
  }
@@ -121,14 +121,16 @@ class AccountModifyHandler extends _Base.AccountBaseHandler {
121
121
  } = _ref2;
122
122
  const modifyPairs = this.state.modifyPairs;
123
123
  const isUnified = this.state.isUnifiedAccount(proxyId);
124
+ const oldAccounts = Object.keys(this.state.accounts);
125
+ const afterDeleteAccounts = oldAccounts.filter(id => id !== proxyId);
124
126
  let addresses;
125
127
  if (!isUnified) {
126
128
  addresses = [proxyId];
127
129
  } else {
128
130
  addresses = Object.keys(modifyPairs).filter(address => modifyPairs[address].accountProxyId === proxyId);
129
- this.state.deleteAccountProxy(proxyId);
130
- this.parentService.eventRemoveAccount(proxyId);
131
131
  }
132
+ this.state.deleteAccountProxy(proxyId);
133
+ this.parentService.eventRemoveAccountProxy(proxyId);
132
134
  for (const address of addresses) {
133
135
  delete modifyPairs[address];
134
136
  }
@@ -137,7 +139,13 @@ class AccountModifyHandler extends _Base.AccountBaseHandler {
137
139
  _uiKeyring.keyring.forgetAccount(address);
138
140
  }
139
141
  await Promise.all(addresses.map(address => new Promise(resolve => this.state.removeAccountRef(address, resolve))));
140
- this.state.saveCurrentAccountProxyId(_constants.ALL_ACCOUNT_KEY);
142
+
143
+ // Cannot use `this.state.accounts` because it is not completely updated yet
144
+ if (afterDeleteAccounts.length > 1) {
145
+ this.state.saveCurrentAccountProxyId(_constants.ALL_ACCOUNT_KEY);
146
+ } else {
147
+ this.state.saveCurrentAccountProxyId(afterDeleteAccounts[0]);
148
+ }
141
149
  return addresses;
142
150
  }
143
151
  tonGetAllTonWalletContractVersion(request) {
@@ -450,12 +450,11 @@ class AccountState {
450
450
  if (proxyId === _constants.ALL_ACCOUNT_KEY) {
451
451
  return allowGetAllAccount ? this.getAllAddresses() : [];
452
452
  }
453
- const accountProxies = this._accountProxy.value;
454
- const modifyPairs = this._modifyPair.value;
453
+ const accountProxies = this.accounts;
455
454
  if (!accountProxies[proxyId]) {
456
455
  return [proxyId];
457
456
  } else {
458
- return Object.keys(modifyPairs).filter(address => modifyPairs[address].accountProxyId === proxyId);
457
+ return accountProxies[proxyId].accounts.map(account => account.address);
459
458
  }
460
459
  }
461
460
 
@@ -29,7 +29,7 @@ class KeyringService {
29
29
  eventInjectReady() {
30
30
  this.state.eventService.emit('inject.ready', true);
31
31
  }
32
- eventRemoveAccount(proxyId) {
32
+ eventRemoveAccountProxy(proxyId) {
33
33
  this.state.eventService.emit('accountProxy.remove', proxyId);
34
34
  }
35
35
  updateKeyringState() {