@subwallet/extension-base 1.3.31-0 → 1.3.32-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 (129) hide show
  1. package/background/KoniTypes.d.ts +70 -3
  2. package/background/KoniTypes.js +14 -0
  3. package/background/errors/CardanoProviderError.d.ts +6 -0
  4. package/background/errors/CardanoProviderError.js +61 -0
  5. package/background/types.d.ts +2 -2
  6. package/cjs/background/KoniTypes.js +16 -1
  7. package/cjs/background/errors/CardanoProviderError.js +67 -0
  8. package/cjs/constants/index.js +4 -1
  9. package/cjs/core/logic-validation/request.js +50 -3
  10. package/cjs/koni/api/contract-handler/evm/web3.js +21 -0
  11. package/cjs/koni/api/staking/bonding/utils.js +24 -3
  12. package/cjs/koni/background/handlers/Extension.js +115 -107
  13. package/cjs/koni/background/handlers/State.js +228 -5
  14. package/cjs/koni/background/handlers/Tabs.js +277 -55
  15. package/cjs/packageInfo.js +1 -1
  16. package/cjs/page/cardano/cips/cip30.js +63 -0
  17. package/cjs/page/cardano/cips/index.js +20 -0
  18. package/cjs/page/cardano/index.js +41 -0
  19. package/cjs/page/{SubWalleEvmProvider.js → evm/index.js} +2 -2
  20. package/cjs/page/index.js +9 -4
  21. package/cjs/services/balance-service/helpers/subscribe/substrate/index.js +33 -1
  22. package/cjs/services/balance-service/transfer/xcm/acrossBridge/index.js +6 -2
  23. package/cjs/services/balance-service/transfer/xcm/index.js +2 -0
  24. package/cjs/services/chain-service/handler/CardanoApi.js +33 -0
  25. package/cjs/services/chain-service/index.js +31 -0
  26. package/cjs/services/chain-service/utils/patch.js +1 -1
  27. package/cjs/services/earning-service/handlers/liquid-staking/stella-swap.js +3 -3
  28. package/cjs/services/earning-service/handlers/native-staking/dtao.js +2 -2
  29. package/cjs/services/earning-service/handlers/native-staking/mythos.js +42 -8
  30. package/cjs/services/earning-service/handlers/native-staking/relay-chain.js +1 -1
  31. package/cjs/services/earning-service/handlers/native-staking/tao.js +13 -13
  32. package/cjs/services/earning-service/handlers/nomination-pool/index.js +1 -1
  33. package/cjs/services/migration-service/scripts/MigrateAuthUrls.js +1 -1
  34. package/cjs/services/request-service/constants.js +3 -1
  35. package/cjs/services/request-service/handler/AuthRequestHandler.js +38 -5
  36. package/cjs/services/request-service/handler/CardanoRequestHandler.js +45 -3
  37. package/cjs/services/request-service/helper/index.js +419 -1
  38. package/cjs/services/swap-service/handler/asset-hub/handler.js +1 -1
  39. package/cjs/services/swap-service/handler/base-handler.js +81 -21
  40. package/cjs/services/swap-service/handler/hydradx-handler.js +1 -1
  41. package/cjs/services/swap-service/handler/uniswap-handler.js +274 -45
  42. package/cjs/services/swap-service/index.js +33 -11
  43. package/cjs/services/swap-service/utils.js +15 -2
  44. package/cjs/utils/auth.js +2 -1
  45. package/cjs/utils/cardano.js +20 -0
  46. package/cjs/utils/index.js +4 -4
  47. package/constants/index.d.ts +1 -0
  48. package/constants/index.js +1 -0
  49. package/core/logic-validation/request.d.ts +6 -2
  50. package/core/logic-validation/request.js +51 -5
  51. package/koni/api/contract-handler/evm/web3.d.ts +2 -0
  52. package/koni/api/contract-handler/evm/web3.js +19 -0
  53. package/koni/api/staking/bonding/utils.d.ts +2 -1
  54. package/koni/api/staking/bonding/utils.js +23 -3
  55. package/koni/background/handlers/Extension.js +7 -2
  56. package/koni/background/handlers/State.d.ts +6 -1
  57. package/koni/background/handlers/State.js +223 -4
  58. package/koni/background/handlers/Tabs.d.ts +11 -1
  59. package/koni/background/handlers/Tabs.js +242 -19
  60. package/package.json +62 -42
  61. package/packageInfo.js +1 -1
  62. package/page/cardano/cips/cip30.d.ts +22 -0
  63. package/page/cardano/cips/cip30.js +55 -0
  64. package/page/cardano/cips/index.d.ts +3 -0
  65. package/page/cardano/cips/index.js +7 -0
  66. package/page/cardano/index.d.ts +13 -0
  67. package/page/cardano/index.js +34 -0
  68. package/page/{SubWalleEvmProvider.d.ts → evm/index.d.ts} +3 -2
  69. package/page/{SubWalleEvmProvider.js → evm/index.js} +1 -1
  70. package/page/index.d.ts +3 -2
  71. package/page/index.js +6 -2
  72. package/page/{Accounts.d.ts → substrate/Accounts.d.ts} +1 -1
  73. package/page/{Metadata.d.ts → substrate/Metadata.d.ts} +1 -1
  74. package/page/{PostMessageProvider.d.ts → substrate/PostMessageProvider.d.ts} +1 -1
  75. package/page/{Signer.d.ts → substrate/Signer.d.ts} +1 -1
  76. package/page/{Injected.d.ts → substrate/index.d.ts} +1 -1
  77. package/services/balance-service/helpers/subscribe/cardano/types.d.ts +14 -0
  78. package/services/balance-service/helpers/subscribe/substrate/index.js +34 -2
  79. package/services/balance-service/transfer/xcm/acrossBridge/index.d.ts +4 -0
  80. package/services/balance-service/transfer/xcm/acrossBridge/index.js +4 -1
  81. package/services/balance-service/transfer/xcm/index.js +2 -0
  82. package/services/chain-service/handler/CardanoApi.d.ts +3 -1
  83. package/services/chain-service/handler/CardanoApi.js +33 -0
  84. package/services/chain-service/index.d.ts +5 -1
  85. package/services/chain-service/index.js +32 -1
  86. package/services/chain-service/utils/patch.js +1 -1
  87. package/services/earning-service/handlers/liquid-staking/stella-swap.js +3 -3
  88. package/services/earning-service/handlers/native-staking/dtao.js +2 -2
  89. package/services/earning-service/handlers/native-staking/mythos.js +42 -8
  90. package/services/earning-service/handlers/native-staking/relay-chain.js +1 -1
  91. package/services/earning-service/handlers/native-staking/tao.js +14 -14
  92. package/services/earning-service/handlers/nomination-pool/index.js +1 -1
  93. package/services/migration-service/scripts/MigrateAuthUrls.js +1 -1
  94. package/services/request-service/constants.js +3 -1
  95. package/services/request-service/handler/AuthRequestHandler.js +40 -7
  96. package/services/request-service/handler/CardanoRequestHandler.d.ts +2 -0
  97. package/services/request-service/handler/CardanoRequestHandler.js +45 -3
  98. package/services/request-service/helper/index.d.ts +54 -0
  99. package/services/request-service/helper/index.js +406 -1
  100. package/services/request-service/types.d.ts +3 -1
  101. package/services/swap-service/handler/asset-hub/handler.js +1 -1
  102. package/services/swap-service/handler/base-handler.d.ts +3 -1
  103. package/services/swap-service/handler/base-handler.js +82 -22
  104. package/services/swap-service/handler/hydradx-handler.js +1 -1
  105. package/services/swap-service/handler/uniswap-handler.d.ts +5 -0
  106. package/services/swap-service/handler/uniswap-handler.js +275 -46
  107. package/services/swap-service/index.js +34 -12
  108. package/services/swap-service/utils.d.ts +3 -2
  109. package/services/swap-service/utils.js +13 -1
  110. package/types/swap/index.d.ts +1 -0
  111. package/types/transaction/process.d.ts +2 -0
  112. package/utils/auth.js +3 -2
  113. package/utils/cardano.d.ts +2 -0
  114. package/utils/cardano.js +12 -0
  115. package/utils/index.d.ts +1 -1
  116. package/utils/index.js +1 -1
  117. package/cjs/utils/canDerive.js +0 -12
  118. package/utils/canDerive.d.ts +0 -2
  119. package/utils/canDerive.js +0 -6
  120. /package/cjs/page/{Accounts.js → substrate/Accounts.js} +0 -0
  121. /package/cjs/page/{Metadata.js → substrate/Metadata.js} +0 -0
  122. /package/cjs/page/{PostMessageProvider.js → substrate/PostMessageProvider.js} +0 -0
  123. /package/cjs/page/{Signer.js → substrate/Signer.js} +0 -0
  124. /package/cjs/page/{Injected.js → substrate/index.js} +0 -0
  125. /package/page/{Accounts.js → substrate/Accounts.js} +0 -0
  126. /package/page/{Metadata.js → substrate/Metadata.js} +0 -0
  127. /package/page/{PostMessageProvider.js → substrate/PostMessageProvider.js} +0 -0
  128. /package/page/{Signer.js → substrate/Signer.js} +0 -0
  129. /package/page/{Injected.js → substrate/index.js} +0 -0
@@ -0,0 +1,34 @@
1
+ // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { CIP30Api, ExtensionCIPsSupported } from '@subwallet/extension-base/page/cardano/cips';
5
+ const WALLET_NAME = 'SubWallet';
6
+ const WALLET_VERSION = process.env.PKG_VERSION;
7
+ const WALLET_ICON = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYwIiBoZWlnaHQ9IjE2MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNODAgNGM1Ny42MyAwIDc2IDE4LjM3IDc2IDc2IDAgNTcuNjMtMTguMzcgNzYtNzYgNzYtNTcuNjMgMC03Ni0xOC4zNy03Ni03NkM0IDIyLjM3IDIyLjM3IDQgODAgNFoiIGZpbGw9InVybCgjYSkiLz48ZyBjbGlwLXBhdGg9InVybCgjYikiPjxwYXRoIGQ9Ik0xMTIuNjE1IDY2LjcyVjUzLjM5OEw1OC43NiAzMiA0OCAzNy40MTJsLjA1NyA0MS40NjQgNDAuMjkyIDE2LjA3LTIxLjUyIDkuMDc1di03LjAxOEw1Ni45NSA5My4wM2wtOC44OTMgNC4xNjN2MjUuMzk1TDU4Ljc2OSAxMjhsNTMuODQ2LTI0LjA2MlY4Ni44NjlMNjQuMTU0IDY3LjY1N1Y1NmwzOC40NDkgMTUuMjE2IDEwLjAxMi00LjQ5NloiIGZpbGw9IiNmZmYiLz48L2c+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJhIiB4MT0iODAiIHkxPSI0IiB4Mj0iODAiIHkyPSIxNTYiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj48c3RvcCBzdG9wLWNvbG9yPSIjMDA0QkZGIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjNENFQUFDIi8+PC9saW5lYXJHcmFkaWVudD48Y2xpcFBhdGggaWQ9ImIiPjxwYXRoIGZpbGw9IiNmZmYiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDQ4IDMyKSIgZD0iTTAgMGg2NC42MTV2OTZIMHoiLz48L2NsaXBQYXRoPjwvZGVmcz48L3N2Zz4=';
8
+ export default class SubWalletCardanoProvider {
9
+ apiVersion = WALLET_VERSION;
10
+ icon = WALLET_ICON;
11
+ name = WALLET_NAME;
12
+ supportedExtensions = [...ExtensionCIPsSupported];
13
+ constructor(sendMessage) {
14
+ this.icon = WALLET_ICON;
15
+ this.sendMessage = sendMessage;
16
+ }
17
+ async enable() {
18
+ const isEnabled = await this.sendMessage('pub(authorize.tabV2)', {
19
+ origin,
20
+ accountAuthTypes: ['cardano']
21
+ });
22
+ if (!isEnabled) {
23
+ throw new Error('Access to the wallet is denied');
24
+ }
25
+ const CIP30 = new CIP30Api(this.sendMessage);
26
+ return Object.freeze(CIP30);
27
+ }
28
+ async isEnable() {
29
+ const accountList = await this.sendMessage('pub(accounts.list)', {
30
+ accountAuthType: 'cardano'
31
+ });
32
+ return accountList.length > 0;
33
+ }
34
+ }
@@ -3,10 +3,10 @@ import SafeEventEmitter from '@metamask/safe-event-emitter';
3
3
  import { SendRequest } from '@subwallet/extension-base/page/types';
4
4
  import { JsonRpcRequest, JsonRpcResponse } from 'json-rpc-engine';
5
5
  import { RequestArguments } from 'web3-core';
6
- export interface SendSyncJsonRpcRequest extends JsonRpcRequest<unknown> {
6
+ interface SendSyncJsonRpcRequest extends JsonRpcRequest<unknown> {
7
7
  method: 'net_version';
8
8
  }
9
- export declare class SubWalletEvmProvider extends SafeEventEmitter implements EvmProvider {
9
+ export default class SubWalletEvmProvider extends SafeEventEmitter implements EvmProvider {
10
10
  readonly isSubWallet = true;
11
11
  readonly isMetaMask = false;
12
12
  readonly version: string;
@@ -26,3 +26,4 @@ export declare class SubWalletEvmProvider extends SafeEventEmitter implements Ev
26
26
  send<T>(payload: SendSyncJsonRpcRequest): JsonRpcResponse<T>;
27
27
  sendAsync<T>(payload: JsonRpcRequest<T>, callback: (error: (Error | null), result?: JsonRpcResponse<T>) => void): void;
28
28
  }
29
+ export {};
@@ -3,7 +3,7 @@
3
3
 
4
4
  import SafeEventEmitter from '@metamask/safe-event-emitter';
5
5
  let subscribeFlag = false;
6
- export class SubWalletEvmProvider extends SafeEventEmitter {
6
+ export default class SubWalletEvmProvider extends SafeEventEmitter {
7
7
  isSubWallet = true;
8
8
  isMetaMask = false;
9
9
  _connected = false;
package/page/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { MessageTypes, MessageTypesWithNoSubscriptions, MessageTypesWithNullRequest, MessageTypesWithSubscriptions, RequestTypes, ResponseTypes, SubscriptionMessageTypes, TransportResponseMessage } from '../background/types';
2
- import { AuthRequestOption, EvmProvider } from '@subwallet/extension-inject/types';
3
- import Injected from './Injected';
2
+ import Injected from '@subwallet/extension-base/page/substrate';
3
+ import { AuthRequestOption, CardanoProvider, EvmProvider } from '@subwallet/extension-inject/types';
4
4
  export interface Handler {
5
5
  resolve: (data?: any) => void;
6
6
  reject: (error: Error) => void;
@@ -15,3 +15,4 @@ export declare function handleResponse<TMessageType extends MessageTypes>(data:
15
15
  subscription?: string;
16
16
  }): void;
17
17
  export declare function initEvmProvider(version: string): EvmProvider;
18
+ export declare function initCardanoProvider(): CardanoProvider;
package/page/index.js CHANGED
@@ -3,10 +3,11 @@
3
3
 
4
4
  import { ProviderError } from '@subwallet/extension-base/background/errors/ProviderError';
5
5
  import { ProviderErrorType } from '@subwallet/extension-base/background/KoniTypes';
6
- import { SubWalletEvmProvider } from '@subwallet/extension-base/page/SubWalleEvmProvider';
6
+ import SubWalletCardanoProvider from '@subwallet/extension-base/page/cardano';
7
+ import SubWalletEvmProvider from '@subwallet/extension-base/page/evm';
8
+ import Injected from '@subwallet/extension-base/page/substrate';
7
9
  import { MESSAGE_ORIGIN_PAGE } from "../defaults.js";
8
10
  import { getId } from "../utils/getId.js";
9
- import Injected from "./Injected.js";
10
11
  // when sending a message from the injector to the extension, we
11
12
  // - create an event - this we send to the loader
12
13
  // - the loader takes this event and uses port.postMessage to background
@@ -68,4 +69,7 @@ export function handleResponse(data) {
68
69
  }
69
70
  export function initEvmProvider(version) {
70
71
  return new SubWalletEvmProvider(sendMessage, version);
72
+ }
73
+ export function initCardanoProvider() {
74
+ return new SubWalletCardanoProvider(sendMessage);
71
75
  }
@@ -1,5 +1,5 @@
1
1
  import type { InjectedAccount, InjectedAccounts, Unsubcall } from '@subwallet/extension-inject/types';
2
- import type { SendRequest } from './types';
2
+ import type { SendRequest } from '../types';
3
3
  export default class Accounts implements InjectedAccounts {
4
4
  constructor(_sendRequest: SendRequest);
5
5
  get(anyType?: boolean): Promise<InjectedAccount[]>;
@@ -1,5 +1,5 @@
1
1
  import type { InjectedMetadata, InjectedMetadataKnown, MetadataDef } from '@subwallet/extension-inject/types';
2
- import type { SendRequest } from './types';
2
+ import type { SendRequest } from '../types';
3
3
  import { RequestAddPspToken } from '@subwallet/extension-base/background/KoniTypes';
4
4
  export default class Metadata implements InjectedMetadata {
5
5
  constructor(_sendRequest: SendRequest);
@@ -1,7 +1,7 @@
1
1
  import type { InjectedProvider, ProviderList, ProviderMeta } from '@subwallet/extension-inject/types';
2
2
  import type { ProviderInterfaceEmitCb, ProviderInterfaceEmitted } from '@polkadot/rpc-provider/types';
3
3
  import type { AnyFunction } from '@polkadot/types/types';
4
- import type { SendRequest } from './types';
4
+ import type { SendRequest } from '../types';
5
5
  declare type CallbackHandler = (error?: null | Error, value?: unknown) => void;
6
6
  interface SubscriptionHandler {
7
7
  callback: CallbackHandler;
@@ -1,6 +1,6 @@
1
1
  import type { Signer as SignerInterface, SignerResult } from '@polkadot/api/types';
2
2
  import type { SignerPayloadJSON, SignerPayloadRaw } from '@polkadot/types/types';
3
- import type { SendRequest } from './types';
3
+ import type { SendRequest } from '../types';
4
4
  export default class Signer implements SignerInterface {
5
5
  constructor(_sendRequest: SendRequest);
6
6
  signPayload(payload: SignerPayloadJSON): Promise<SignerResult>;
@@ -1,5 +1,5 @@
1
1
  import type { Injected } from '@subwallet/extension-inject/types';
2
- import type { SendRequest } from './types';
2
+ import type { SendRequest } from '../types';
3
3
  import Accounts from './Accounts';
4
4
  import Metadata from './Metadata';
5
5
  import PostMessageProvider from './PostMessageProvider';
@@ -9,6 +9,20 @@ export interface CardanoBalanceItem {
9
9
  unit: string;
10
10
  quantity: string;
11
11
  }
12
+ export interface CardanoUtxosItem {
13
+ address: string;
14
+ tx_hash: string;
15
+ output_index: number;
16
+ amount: CardanoBalanceItem[];
17
+ data_hash: string | null;
18
+ inline_datum: string | null;
19
+ reference_script_hash: string | null;
20
+ }
21
+ export interface TransactionUtxosItem {
22
+ hash: string;
23
+ inputs: CardanoUtxosItem[];
24
+ outputs: CardanoUtxosItem[];
25
+ }
12
26
  export interface CardanoTxJson {
13
27
  body: {
14
28
  inputs: CardanoTxInput[];
@@ -3,7 +3,7 @@
3
3
 
4
4
  import { _AssetType } from '@subwallet/chain-list/types';
5
5
  import { APIItemState } from '@subwallet/extension-base/background/KoniTypes';
6
- import { SUB_TOKEN_REFRESH_BALANCE_INTERVAL } from '@subwallet/extension-base/constants';
6
+ import { CRON_REFRESH_PRICE_INTERVAL, SUB_TOKEN_REFRESH_BALANCE_INTERVAL } from '@subwallet/extension-base/constants';
7
7
  import { _getAssetsPalletLocked, _getAssetsPalletTransferable } from '@subwallet/extension-base/core/substrate/assets-pallet';
8
8
  import { _getForeignAssetPalletLockedBalance, _getForeignAssetPalletTransferable } from '@subwallet/extension-base/core/substrate/foreign-asset-pallet';
9
9
  import { _getTotalStakeInNominationPool } from '@subwallet/extension-base/core/substrate/nominationpools-pallet';
@@ -17,6 +17,7 @@ import { _BALANCE_CHAIN_GROUP, _MANTA_ZK_CHAIN_GROUP, _ZK_ASSET_PREFIX } from '@
17
17
  import { _checkSmartContractSupportByChain, _getAssetExistentialDeposit, _getAssetNetuid, _getChainExistentialDeposit, _getChainNativeTokenSlug, _getContractAddressOfToken, _getTokenOnChainAssetId, _getTokenOnChainInfo, _getTokenTypesSupportedByChain, _getXcmAssetMultilocation, _isBridgedToken, _isChainEvmCompatible } from '@subwallet/extension-base/services/chain-service/utils';
18
18
  import { filterAlphaAssetsByChain, filterAssetsByChainAndType } from '@subwallet/extension-base/utils';
19
19
  import BigN from 'bignumber.js';
20
+ import { timer } from 'rxjs';
20
21
  import { subscribeERC20Interval } from "../evm.js";
21
22
  import { subscribeEquilibriumTokenBalance } from "./equilibrium.js";
22
23
  import { subscribeGRC20Balance, subscribeVftBalance } from "./gear.js";
@@ -323,7 +324,19 @@ const subscribeTokensAccountsPallet = async ({
323
324
  const tokensAccountsKey = 'query_tokens_accounts';
324
325
  const tokenTypes = includeNativeToken ? [_AssetType.NATIVE, _AssetType.LOCAL] : [_AssetType.LOCAL];
325
326
  const tokenMap = filterAssetsByChainAndType(assetMap, chainInfo.slug, tokenTypes);
327
+
328
+ // Hotfix balance for gdot
329
+ const getGdotBalance = async () => {
330
+ const gdotBalances = await queryGdotBalance(substrateApi, addresses, assetMap[gdotSlug], extrinsicType);
331
+ callback(gdotBalances);
332
+ };
326
333
  const unsubList = await Promise.all(Object.values(tokenMap).map(tokenInfo => {
334
+ // Hotfix balance for gdot
335
+ if (tokenInfo.slug === gdotSlug) {
336
+ return timer(0, CRON_REFRESH_PRICE_INTERVAL).subscribe(() => {
337
+ getGdotBalance().catch(console.error);
338
+ });
339
+ }
327
340
  try {
328
341
  const params = [{
329
342
  section: 'query',
@@ -529,4 +542,23 @@ const subscribeSubnetAlphaPallet = async ({
529
542
  cancel = true;
530
543
  clearInterval(interval);
531
544
  };
532
- };
545
+ };
546
+
547
+ // Hot fix for gdot balance
548
+
549
+ const gdotSlug = 'hydradx_main-LOCAL-GDOT';
550
+ async function queryGdotBalance(substrateApi, addresses, tokenInfo, extrinsicType) {
551
+ return await Promise.all(addresses.map(async address => {
552
+ const _balanceInfo = await substrateApi.api.call.currenciesApi.account(_getTokenOnChainAssetId(tokenInfo), address);
553
+ const balanceInfo = _balanceInfo.toPrimitive();
554
+ const transferableBalance = _getTokensPalletTransferable(balanceInfo, _getAssetExistentialDeposit(tokenInfo), extrinsicType);
555
+ const totalLockedFromTransfer = _getTokensPalletLocked(balanceInfo);
556
+ return {
557
+ address,
558
+ tokenSlug: tokenInfo.slug,
559
+ state: APIItemState.READY,
560
+ free: transferableBalance.toString(),
561
+ locked: totalLockedFromTransfer.toString()
562
+ };
563
+ }));
564
+ }
@@ -7,6 +7,10 @@ export declare const SpokePoolMapping: Record<number, {
7
7
  blockNumber: number;
8
8
  };
9
9
  }>;
10
+ export declare const AcrossErrorMsg: {
11
+ AMOUNT_TOO_LOW: string;
12
+ AMOUNT_TOO_HIGH: string;
13
+ };
10
14
  interface AcrossQuote {
11
15
  outputAmount: string;
12
16
  rate: string;
@@ -185,6 +185,10 @@ export const SpokePoolMapping = {
185
185
  }
186
186
  }
187
187
  };
188
+ export const AcrossErrorMsg = {
189
+ AMOUNT_TOO_LOW: 'amount too low',
190
+ AMOUNT_TOO_HIGH: 'amount too high'
191
+ };
188
192
  // Calculate fee for across bridge transfer
189
193
  export const getAcrossQuote = async ({
190
194
  destinationChain,
@@ -196,7 +200,6 @@ export const getAcrossQuote = async ({
196
200
  sendingValue
197
201
  }) => {
198
202
  const isAcrossBridgeXcm = _isAcrossBridgeXcm(originChain, destinationChain);
199
- console.log('sendingValue', sendingValue);
200
203
  if (!isAcrossBridgeXcm) {
201
204
  throw new Error('This is not a valid AcrossBridge transfer');
202
205
  }
@@ -182,6 +182,8 @@ export const createAcrossBridgeExtrinsic = async ({
182
182
  const data = await ((_subwalletApiSdk$xcmA = subwalletApiSdk.xcmApi) === null || _subwalletApiSdk$xcmA === void 0 ? void 0 : _subwalletApiSdk$xcmA.fetchXcmData(sender, originTokenInfo.slug, destinationTokenInfo.slug, recipient, sendingValue));
183
183
  const _feeCustom = feeCustom;
184
184
  const feeCombine = combineEthFee(feeInfo, feeOption, _feeCustom);
185
+
186
+ // todo: validate data before sending
185
187
  const transactionConfig = {
186
188
  from: data === null || data === void 0 ? void 0 : data.sender,
187
189
  to: data === null || data === void 0 ? void 0 : data.to,
@@ -1,4 +1,4 @@
1
- import { CardanoBalanceItem } from '@subwallet/extension-base/services/balance-service/helpers/subscribe/cardano/types';
1
+ import { CardanoBalanceItem, CardanoUtxosItem, TransactionUtxosItem } from '@subwallet/extension-base/services/balance-service/helpers/subscribe/cardano/types';
2
2
  import { _ApiOptions } from '@subwallet/extension-base/services/chain-service/handler/types';
3
3
  import { _CardanoApi, _ChainConnectionStatus } from '@subwallet/extension-base/services/chain-service/types';
4
4
  import { PromiseHandler } from '@subwallet/extension-base/utils';
@@ -33,6 +33,8 @@ export declare class CardanoApi implements _CardanoApi {
33
33
  onConnect(): void;
34
34
  onDisconnect(): void;
35
35
  getBalanceMap(address: string): Promise<CardanoBalanceItem[]>;
36
+ getUtxos(address: string, page: number, limit: number): Promise<CardanoUtxosItem[]>;
37
+ getSpecificUtxo(txHash: string): Promise<TransactionUtxosItem>;
36
38
  sendCardanoTxReturnHash(tx: string): Promise<string>;
37
39
  getStatusByTxHash(txHash: string, ttl: number): Promise<boolean>;
38
40
  }
@@ -121,6 +121,39 @@ export class CardanoApi {
121
121
  return [];
122
122
  }
123
123
  }
124
+ async getUtxos(address, page, limit) {
125
+ try {
126
+ let url = this.isTestnet ? `https://cardano-preprod.blockfrost.io/api/v0/addresses/${address}/utxos` : `https://cardano-mainnet.blockfrost.io/api/v0/addresses/${address}/utxos`;
127
+ url += `?page=${page}&count=${limit}`;
128
+ const response = await fetch(url, {
129
+ method: 'GET',
130
+ headers: {
131
+ Project_id: this.projectId
132
+ }
133
+ });
134
+ const utxos = await response.json();
135
+ return utxos;
136
+ } catch (e) {
137
+ console.error('Error on getting account balance', e);
138
+ return [];
139
+ }
140
+ }
141
+ async getSpecificUtxo(txHash) {
142
+ try {
143
+ const url = this.isTestnet ? `https://cardano-preprod.blockfrost.io/api/v0/txs/${txHash}/utxos` : `https://cardano-mainnet.blockfrost.io/api/v0/txs/${txHash}/utxos`;
144
+ const response = await fetch(url, {
145
+ method: 'GET',
146
+ headers: {
147
+ Project_id: this.projectId
148
+ }
149
+ });
150
+ const utxo = await response.json();
151
+ return utxo;
152
+ } catch (e) {
153
+ console.error('Error on getting account balance', e);
154
+ return {};
155
+ }
156
+ }
124
157
  async sendCardanoTxReturnHash(tx) {
125
158
  try {
126
159
  const url = this.isTestnet ? 'https://cardano-preprod.blockfrost.io/api/v0/tx/submit' : 'https://cardano-mainnet.blockfrost.io/api/v0/tx/submit';
@@ -1,6 +1,8 @@
1
1
  /// <reference types="node" />
2
+ import { TransactionUnspentOutput } from '@emurgo/cardano-serialization-lib-nodejs';
2
3
  import { _AssetRef, _AssetType, _ChainAsset, _ChainInfo, _MultiChainAsset } from '@subwallet/chain-list/types';
3
- import { AssetSetting, MetadataItem, SufficientChainsDetails, TokenPriorityDetails, ValidateNetworkResponse } from '@subwallet/extension-base/background/KoniTypes';
4
+ import { AssetSetting, CardanoPaginate, MetadataItem, SufficientChainsDetails, TokenPriorityDetails, ValidateNetworkResponse } from '@subwallet/extension-base/background/KoniTypes';
5
+ import { CardanoUtxosItem } from '@subwallet/extension-base/services/balance-service/helpers/subscribe/cardano/types';
4
6
  import { MantaPrivateHandler } from '@subwallet/extension-base/services/chain-service/handler/manta/MantaPrivateHandler';
5
7
  import { _ChainApiStatus, _ChainConnectionStatus, _ChainState, _NetworkUpsertParams, _SubstrateApi, _ValidateCustomAssetRequest, _ValidateCustomAssetResponse } from '@subwallet/extension-base/services/chain-service/types';
6
8
  import { EventService } from '@subwallet/extension-base/services/event-service';
@@ -59,6 +61,8 @@ export declare class ChainService {
59
61
  getTonApi(slug: string): import("./handler/TonApi").TonApi;
60
62
  getTonApiMap(): Record<string, import("./handler/TonApi").TonApi>;
61
63
  getCardanoApi(slug: string): import("./handler/CardanoApi").CardanoApi;
64
+ getUtxosByAddress(address: string, slug: string, paginate?: CardanoPaginate): Promise<TransactionUnspentOutput[]>;
65
+ getSpecificUtxo(slug: string): (txHash: string, txId: number) => Promise<CardanoUtxosItem | undefined>;
62
66
  getCardanoApiMap(): Record<string, import("./handler/CardanoApi").CardanoApi>;
63
67
  getChainCurrentProviderByKey(slug: string): {
64
68
  endpoint: string;
@@ -13,10 +13,12 @@ import { _CHAIN_VALIDATION_ERROR } from '@subwallet/extension-base/services/chai
13
13
  import { _ChainConnectionStatus, _CUSTOM_PREFIX, _NFT_CONTRACT_STANDARDS, _SMART_CONTRACT_STANDARDS } from '@subwallet/extension-base/services/chain-service/types';
14
14
  import { _getAssetOriginChain, _getTokenOnChainAssetId, _isAssetAutoEnable, _isAssetCanPayTxFee, _isAssetFungibleToken, _isChainEnabled, _isCustomAsset, _isCustomChain, _isCustomProvider, _isEqualContractAddress, _isEqualSmartContractAsset, _isLocalToken, _isMantaZkAsset, _isNativeToken, _isPureEvmChain, _isPureSubstrateChain, _parseAssetRefKey, randomizeProvider, updateLatestChainInfo } from '@subwallet/extension-base/services/chain-service/utils';
15
15
  import { MYTHOS_MIGRATION_KEY } from '@subwallet/extension-base/services/migration-service/scripts';
16
+ import { convertUtxoRawToUtxo } from '@subwallet/extension-base/services/request-service/helper';
16
17
  import AssetSettingStore from '@subwallet/extension-base/stores/AssetSetting';
17
- import { addLazy, calculateMetadataHash, fetchStaticData, filterAssetsByChainAndType, getShortMetadata, MODULE_SUPPORT } from '@subwallet/extension-base/utils';
18
+ import { addLazy, calculateMetadataHash, fetchStaticData, filterAssetsByChainAndType, getShortMetadata, MODULE_SUPPORT, reformatAddress } from '@subwallet/extension-base/utils';
18
19
  import { BehaviorSubject, Subject } from 'rxjs';
19
20
  import Web3 from 'web3';
21
+ import { isArray } from '@polkadot/util';
20
22
  import { logger as createLogger } from '@polkadot/util/logger';
21
23
  const filterChainInfoMap = (data, ignoredChains) => {
22
24
  return Object.fromEntries(Object.entries(data).filter(([slug, info]) => !info.bitcoinInfo && !ignoredChains.includes(slug)));
@@ -155,6 +157,35 @@ export class ChainService {
155
157
  getCardanoApi(slug) {
156
158
  return this.cardanoChainHandler.getCardanoApiByChain(slug);
157
159
  }
160
+ async getUtxosByAddress(address, slug, paginate) {
161
+ const cardanoApi = this.getCardanoApi(slug);
162
+ const isTestnet = slug === 'cardano_preproduction';
163
+ const formattedAddress = isTestnet ? reformatAddress(address, 0) : address;
164
+ const limit = (paginate === null || paginate === void 0 ? void 0 : paginate.limit) || 100;
165
+ const utxos = [];
166
+ let needStop = false;
167
+ let page = ((paginate === null || paginate === void 0 ? void 0 : paginate.page) || 0) + 1;
168
+ while (!needStop) {
169
+ const utxoRaw = await cardanoApi.getUtxos(formattedAddress, page, limit);
170
+ if (utxoRaw.length === 0 || !isArray(utxoRaw)) {
171
+ needStop = true;
172
+ } else {
173
+ utxos.push(...utxoRaw);
174
+ page++;
175
+ }
176
+ }
177
+ return convertUtxoRawToUtxo(utxos);
178
+ }
179
+ getSpecificUtxo(slug) {
180
+ const cardanoApi = this.getCardanoApi(slug);
181
+ return async (txHash, txId) => {
182
+ const utxoRaw = await cardanoApi.getSpecificUtxo(txHash);
183
+ if (!(utxoRaw !== null && utxoRaw !== void 0 && utxoRaw.outputs)) {
184
+ return undefined;
185
+ }
186
+ return utxoRaw.outputs[txId];
187
+ };
188
+ }
158
189
  getCardanoApiMap() {
159
190
  return this.cardanoChainHandler.getCardanoApiMap();
160
191
  }
@@ -5,7 +5,7 @@ const PRODUCTION_BRANCHES = ['master', 'webapp', 'webapp-dev'];
5
5
  const branchName = process.env.BRANCH_NAME || 'subwallet-dev';
6
6
  const fetchDomain = PRODUCTION_BRANCHES.indexOf(branchName) > -1 ? 'https://chain-list-assets.subwallet.app' : 'https://dev.sw-chain-list-assets.pages.dev';
7
7
  const fetchFile = PRODUCTION_BRANCHES.indexOf(branchName) > -1 ? 'list.json' : 'preview.json';
8
- const ChainListVersion = '0.2.103'; // update this when build chainlist
8
+ const ChainListVersion = '0.2.104'; // update this when build chainlist
9
9
 
10
10
  // todo: move this interface to chainlist
11
11
 
@@ -16,7 +16,7 @@ export const getStellaswapLiquidStakingContract = (networkKey, assetAddress, evm
16
16
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument,@typescript-eslint/no-unsafe-member-access
17
17
  return new evmApi.api.eth.Contract(ST_LIQUID_TOKEN_ABI, assetAddress, options);
18
18
  };
19
- const APR_STATS_URL = 'https://apr-api.stellaswap.com/api/v1/stdot';
19
+ const APR_STATS_URL = 'https://stdot-apr.stellaswap.com/';
20
20
  const SUBWALLET_REFERRAL = '0x7e6815f45E624768548d085231f2d453f16FD7DD';
21
21
  const TOP_HOLDER = '0x4300e09284e3bB4d9044DdAB31EfAF5f3301DABa';
22
22
  export default class StellaSwapLiquidStakingPoolHandler extends BaseLiquidStakingPoolHandler {
@@ -86,7 +86,7 @@ export default class StellaSwapLiquidStakingPoolHandler extends BaseLiquidStakin
86
86
  statistic: {
87
87
  assetEarning: [{
88
88
  slug: this.rewardAssets[0],
89
- apr: aprObject.result,
89
+ apr: aprObject.stDOTAPR,
90
90
  exchangeRate: exchangeRate
91
91
  }],
92
92
  unstakingPeriod: 24 * 28,
@@ -97,7 +97,7 @@ export default class StellaSwapLiquidStakingPoolHandler extends BaseLiquidStakin
97
97
  defaultUnstake: '0',
98
98
  fastUnstake: '0'
99
99
  },
100
- totalApr: aprObject.result,
100
+ totalApr: aprObject.stDOTAPR,
101
101
  tvl: tvl.toString()
102
102
  }
103
103
  };
@@ -453,7 +453,7 @@ export default class SubnetTaoStakingPoolHandler extends BaseParaStakingPoolHand
453
453
  const BNlimitPrice = new BigN(limitPrice.integerValue(BigN.ROUND_CEIL).toFixed());
454
454
  const selectedValidatorInfo = targetValidators[0];
455
455
  const hotkey = selectedValidatorInfo.address;
456
- const extrinsic = chainApi.api.tx.subtensorModule.addStakeLimit(hotkey, netuid, binaryAmount, BNlimitPrice, false);
456
+ const extrinsic = chainApi.api.tx.subtensorModule.addStakeLimit(hotkey, netuid, binaryAmount.toFixed(), BNlimitPrice.toFixed(), false);
457
457
  return [extrinsic, {
458
458
  slug: this.nativeToken.slug,
459
459
  amount: '0'
@@ -486,7 +486,7 @@ export default class SubnetTaoStakingPoolHandler extends BaseParaStakingPoolHand
486
486
  const alphaToTaoPrice = new BigN(await getAlphaToTaoRate(this.substrateApi, netuid || 0));
487
487
  const limitPrice = alphaToTaoPrice.multipliedBy(10 ** _getAssetDecimals(this.nativeToken)).multipliedBy(1 - (slippage || DEFAULT_BITTENSOR_SLIPPAGE));
488
488
  const BNlimitPrice = new BigN(limitPrice.integerValue(BigN.ROUND_CEIL).toFixed());
489
- const extrinsic = apiPromise.api.tx.subtensorModule.removeStakeLimit(selectedTarget, netuid, binaryAmount, BNlimitPrice, false);
489
+ const extrinsic = apiPromise.api.tx.subtensorModule.removeStakeLimit(selectedTarget, netuid, binaryAmount.toFixed(), BNlimitPrice.toFixed(), false);
490
490
  return [ExtrinsicType.STAKING_UNBOND, extrinsic];
491
491
  }
492
492
  async validateYieldLeave(amount, address, fastLeave, selectedTarget, slug, poolInfo) {
@@ -8,6 +8,21 @@ import { _EXPECTED_BLOCK_TIME, _STAKING_ERA_LENGTH_MAP } from '@subwallet/extens
8
8
  import BaseParaStakingPoolHandler from '@subwallet/extension-base/services/earning-service/handlers/native-staking/base-para';
9
9
  import { BasicTxErrorType, EarningStatus, UnstakingStatus } from '@subwallet/extension-base/types';
10
10
  import { balanceFormatter, formatNumber, reformatAddress } from '@subwallet/extension-base/utils';
11
+ import BigN from 'bignumber.js';
12
+ const FIXED_DAY_REWARD = '123287670000000000000000';
13
+ const COMMISSION = 0.1;
14
+ const DAYS_PER_YEAR = 365;
15
+ function calculateCollatorApy(numberOfCollators, totalStakeStr) {
16
+ const totalStake = new BigN(totalStakeStr);
17
+ const collatorRewardPerDay = new BigN(FIXED_DAY_REWARD).div(numberOfCollators);
18
+ const dayRate = collatorRewardPerDay.div(totalStake);
19
+ const finalTokens = totalStake.multipliedBy(dayRate.multipliedBy(DAYS_PER_YEAR).plus(1));
20
+ const yearReward = finalTokens.minus(totalStake).multipliedBy(1 - COMMISSION);
21
+ return yearReward.div(totalStake).multipliedBy(100).toNumber();
22
+ }
23
+ function calculateNetworkApy(totalStake) {
24
+ return new BigN(FIXED_DAY_REWARD).multipliedBy(DAYS_PER_YEAR).multipliedBy(1 - COMMISSION).div(totalStake).multipliedBy(100).toNumber();
25
+ }
11
26
  export default class MythosNativeStakingPoolHandler extends BaseParaStakingPoolHandler {
12
27
  availableMethod = {
13
28
  join: true,
@@ -56,7 +71,12 @@ export default class MythosNativeStakingPoolHandler extends BaseParaStakingPoolH
56
71
  const sessionTime = _STAKING_ERA_LENGTH_MAP[this.chain] || _STAKING_ERA_LENGTH_MAP.default; // in hours
57
72
  const blockTime = _EXPECTED_BLOCK_TIME[this.chain];
58
73
  const unstakingPeriod = parseInt(unstakeDelay) * blockTime / 60 / 60;
59
- const _minStake = await substrateApi.api.query.collatorStaking.minStake();
74
+ const [_minStake, _candidates] = await Promise.all([substrateApi.api.query.collatorStaking.minStake(), substrateApi.api.query.collatorStaking.candidates.entries()]);
75
+ const bnTotalChainStake = _candidates.reduce((total, _candidate) => {
76
+ const collatorInfo = _candidate[1].toPrimitive();
77
+ const collatorTotalStake = new BigN(collatorInfo.stake);
78
+ return total.plus(collatorTotalStake);
79
+ }, new BigN(0));
60
80
  const minStake = _minStake.toString();
61
81
  const minStakeToHuman = formatNumber(minStake, nativeToken.decimals || 0, balanceFormatter);
62
82
  const data = {
@@ -80,7 +100,7 @@ export default class MythosNativeStakingPoolHandler extends BaseParaStakingPoolH
80
100
  era: parseInt(currentSession),
81
101
  eraTime: sessionTime,
82
102
  unstakingPeriod: unstakingPeriod,
83
- totalApy: undefined
103
+ totalApy: calculateNetworkApy(bnTotalChainStake)
84
104
  // tvl: totalStake.toString(),
85
105
  // inflation
86
106
  },
@@ -208,27 +228,41 @@ export default class MythosNativeStakingPoolHandler extends BaseParaStakingPoolH
208
228
 
209
229
  async getPoolTargets() {
210
230
  const substrateApi = await this.substrateApi.isReady;
211
- const [_allCollators, _minStake, _commission] = await Promise.all([substrateApi.api.query.collatorStaking.candidates.entries(), substrateApi.api.query.collatorStaking.minStake(), substrateApi.api.query.collatorStaking.collatorRewardPercentage()]);
231
+ const [_allCollators, _minStake, _commission, _desiredCandidates] = await Promise.all([substrateApi.api.query.collatorStaking.candidates.entries(), substrateApi.api.query.collatorStaking.minStake(), substrateApi.api.query.collatorStaking.collatorRewardPercentage(), substrateApi.api.query.collatorStaking.desiredCandidates()]);
212
232
  const maxStakersPerCollator = substrateApi.api.consts.collatorStaking.maxStakers.toPrimitive();
213
- return _allCollators.map(_collator => {
233
+ const numberOfRewardCollators = parseInt(_desiredCandidates.toString());
234
+ const numberOfCollators = _allCollators.length;
235
+ const allTargets = _allCollators.map(_collator => {
214
236
  const _collatorAddress = _collator[0].toHuman();
215
237
  const collatorAddress = _collatorAddress[0];
216
238
  const collatorInfo = _collator[1].toPrimitive();
217
- const bnTotalStake = BigInt(collatorInfo.stake);
239
+ const totalStake = collatorInfo.stake;
218
240
  const numOfStakers = parseInt(collatorInfo.stakers);
219
241
  const isCrowded = numOfStakers >= maxStakersPerCollator;
220
242
  return {
221
243
  address: collatorAddress,
222
244
  chain: this.chain,
223
- totalStake: bnTotalStake.toString(),
245
+ totalStake: totalStake,
224
246
  ownStake: '0',
225
- otherStake: bnTotalStake.toString(),
247
+ otherStake: totalStake,
226
248
  minBond: _minStake.toPrimitive(),
227
249
  nominatorCount: numOfStakers,
228
250
  commission: getCommission(_commission.toString()),
229
251
  blocked: false,
230
252
  isVerified: false,
231
- isCrowded
253
+ isCrowded,
254
+ expectedReturn: calculateCollatorApy(numberOfCollators, totalStake)
255
+ };
256
+ });
257
+ const sortTargetsByStake = allTargets.sort((a, b) => BigN(b.totalStake).minus(BigN(a.totalStake)).toNumber());
258
+ return sortTargetsByStake.map((target, rank) => {
259
+ let expectedReturn = target.expectedReturn;
260
+ if (rank >= numberOfRewardCollators) {
261
+ expectedReturn = 0.000000000000001;
262
+ }
263
+ return {
264
+ ...target,
265
+ expectedReturn
232
266
  };
233
267
  });
234
268
  }
@@ -75,7 +75,7 @@ export default class RelayNativeStakingPoolHandler extends BaseNativeStakingPool
75
75
  const bnTotalEraStake = new BN(rawTotalEraStake);
76
76
  const bnTotalIssuance = new BN(rawTotalIssuance);
77
77
  const inflation = calculateInflation(bnTotalEraStake, bnTotalIssuance, numAuctions, chainInfo.slug);
78
- const expectedReturn = calculateChainStakedReturnV2(chainInfo, rawTotalIssuance, erasPerDay, lastTotalStaked, validatorEraReward, new BigN(inflation), true);
78
+ const expectedReturn = await calculateChainStakedReturnV2(chainInfo, rawTotalIssuance, erasPerDay, lastTotalStaked, validatorEraReward, new BigN(inflation), true);
79
79
  const eraTime = _STAKING_ERA_LENGTH_MAP[chainInfo.slug] || _STAKING_ERA_LENGTH_MAP.default; // in hours
80
80
  const unlockingPeriod = parseInt(unlockingEras) * eraTime; // in hours
81
81
  const farmerCount = _counterForNominators.toPrimitive();