@subwallet/extension-base 1.0.12-0 → 1.0.13-1

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 (124) hide show
  1. package/background/KoniTypes.d.ts +89 -0
  2. package/background/KoniTypes.js +18 -19
  3. package/background/handlers/Extension.js +17 -2
  4. package/background/handlers/State.d.ts +0 -1
  5. package/background/handlers/State.js +4 -8
  6. package/background/types.d.ts +6 -1
  7. package/cjs/background/KoniTypes.js +21 -11
  8. package/cjs/background/handlers/Extension.js +22 -6
  9. package/cjs/background/handlers/State.js +4 -8
  10. package/cjs/constants/index.js +7 -1
  11. package/cjs/defaults.js +1 -1
  12. package/cjs/koni/api/dotsama/balance.js +5 -0
  13. package/cjs/koni/api/dotsama/transfer.js +6 -0
  14. package/cjs/koni/api/nft/config.js +11 -6
  15. package/cjs/koni/api/xcm/polkadotXcm.js +1 -1
  16. package/cjs/koni/api/xcm/xTokens.js +2 -2
  17. package/cjs/koni/background/cron.js +12 -1
  18. package/cjs/koni/background/handlers/Extension.js +457 -131
  19. package/cjs/koni/background/handlers/State.js +236 -53
  20. package/cjs/koni/background/handlers/Tabs.js +61 -9
  21. package/cjs/koni/background/subscription.js +3 -0
  22. package/cjs/packageInfo.js +1 -1
  23. package/cjs/page/Metadata.js +3 -0
  24. package/cjs/services/chain-service/constants.js +10 -4
  25. package/cjs/services/chain-service/handler/SubstrateApi.js +2 -1
  26. package/cjs/services/chain-service/handler/SubstrateChainHandler.js +3 -1
  27. package/cjs/services/chain-service/handler/manta/MantaPrivateHandler.js +147 -0
  28. package/cjs/services/chain-service/index.js +54 -5
  29. package/cjs/services/chain-service/utils.js +32 -0
  30. package/cjs/services/event-service/types.js +3 -1
  31. package/cjs/services/request-service/handler/AuthRequestHandler.js +4 -9
  32. package/cjs/services/request-service/handler/SubstrateRequestHandler.js +2 -2
  33. package/cjs/services/request-service/handler/WalletConnectRequestHandler.js +71 -0
  34. package/cjs/services/request-service/index.js +24 -6
  35. package/cjs/services/storage-service/DatabaseService.js +31 -1
  36. package/cjs/services/storage-service/databases/index.js +3 -0
  37. package/cjs/services/storage-service/db-stores/MantaPay.js +40 -0
  38. package/cjs/services/transaction-service/helpers/index.js +3 -2
  39. package/cjs/services/transaction-service/index.js +2 -1
  40. package/cjs/services/wallet-connect-service/constants.js +38 -0
  41. package/cjs/services/wallet-connect-service/handler/Eip155RequestHandler.js +113 -0
  42. package/cjs/services/wallet-connect-service/handler/PolkadotRequestHandler.js +123 -0
  43. package/cjs/services/wallet-connect-service/helpers.js +81 -0
  44. package/cjs/services/wallet-connect-service/index.js +273 -0
  45. package/cjs/services/wallet-connect-service/types.js +27 -0
  46. package/cjs/utils/array.js +17 -0
  47. package/cjs/utils/environment.js +66 -0
  48. package/cjs/utils/index.js +78 -1
  49. package/cjs/utils/lazy.js +52 -0
  50. package/constants/index.d.ts +2 -0
  51. package/constants/index.js +2 -0
  52. package/defaults.d.ts +1 -1
  53. package/defaults.js +1 -1
  54. package/koni/api/dotsama/balance.js +6 -1
  55. package/koni/api/dotsama/transfer.js +7 -1
  56. package/koni/api/nft/config.js +11 -6
  57. package/koni/api/xcm/polkadotXcm.js +1 -1
  58. package/koni/api/xcm/xTokens.js +2 -2
  59. package/koni/background/cron.d.ts +1 -0
  60. package/koni/background/cron.js +13 -2
  61. package/koni/background/handlers/Extension.d.ts +11 -0
  62. package/koni/background/handlers/Extension.js +329 -12
  63. package/koni/background/handlers/State.d.ts +17 -3
  64. package/koni/background/handlers/State.js +238 -52
  65. package/koni/background/handlers/Tabs.d.ts +2 -0
  66. package/koni/background/handlers/Tabs.js +58 -7
  67. package/koni/background/subscription.js +3 -0
  68. package/package.json +72 -6
  69. package/packageInfo.js +1 -1
  70. package/page/Metadata.d.ts +2 -0
  71. package/page/Metadata.js +3 -0
  72. package/services/chain-service/constants.d.ts +3 -0
  73. package/services/chain-service/constants.js +5 -2
  74. package/services/chain-service/handler/SubstrateApi.d.ts +1 -1
  75. package/services/chain-service/handler/SubstrateApi.js +2 -1
  76. package/services/chain-service/handler/SubstrateChainHandler.d.ts +1 -1
  77. package/services/chain-service/handler/SubstrateChainHandler.js +3 -1
  78. package/services/chain-service/handler/manta/MantaPrivateHandler.d.ts +30 -0
  79. package/services/chain-service/handler/manta/MantaPrivateHandler.js +140 -0
  80. package/services/chain-service/handler/types.d.ts +2 -0
  81. package/services/chain-service/index.d.ts +7 -3
  82. package/services/chain-service/index.js +56 -7
  83. package/services/chain-service/utils.d.ts +3 -0
  84. package/services/chain-service/utils.js +28 -0
  85. package/services/event-service/types.d.ts +3 -0
  86. package/services/event-service/types.js +3 -1
  87. package/services/request-service/handler/AuthRequestHandler.d.ts +0 -1
  88. package/services/request-service/handler/AuthRequestHandler.js +5 -10
  89. package/services/request-service/handler/SubstrateRequestHandler.d.ts +1 -1
  90. package/services/request-service/handler/SubstrateRequestHandler.js +2 -2
  91. package/services/request-service/handler/WalletConnectRequestHandler.d.ts +15 -0
  92. package/services/request-service/handler/WalletConnectRequestHandler.js +62 -0
  93. package/services/request-service/index.d.ts +7 -2
  94. package/services/request-service/index.js +24 -6
  95. package/services/storage-service/DatabaseService.d.ts +10 -1
  96. package/services/storage-service/DatabaseService.js +31 -1
  97. package/services/storage-service/databases/index.d.ts +2 -0
  98. package/services/storage-service/databases/index.js +3 -0
  99. package/services/storage-service/db-stores/MantaPay.d.ts +9 -0
  100. package/services/storage-service/db-stores/MantaPay.js +32 -0
  101. package/services/transaction-service/helpers/index.d.ts +1 -1
  102. package/services/transaction-service/helpers/index.js +2 -2
  103. package/services/transaction-service/index.js +2 -1
  104. package/services/transaction-service/types.d.ts +2 -1
  105. package/services/wallet-connect-service/constants.d.ts +11 -0
  106. package/services/wallet-connect-service/constants.js +23 -0
  107. package/services/wallet-connect-service/handler/Eip155RequestHandler.d.ts +8 -0
  108. package/services/wallet-connect-service/handler/Eip155RequestHandler.js +106 -0
  109. package/services/wallet-connect-service/handler/PolkadotRequestHandler.d.ts +8 -0
  110. package/services/wallet-connect-service/handler/PolkadotRequestHandler.js +114 -0
  111. package/services/wallet-connect-service/helpers.d.ts +12 -0
  112. package/services/wallet-connect-service/helpers.js +67 -0
  113. package/services/wallet-connect-service/index.d.ts +20 -0
  114. package/services/wallet-connect-service/index.js +265 -0
  115. package/services/wallet-connect-service/types.d.ts +46 -0
  116. package/services/wallet-connect-service/types.js +20 -0
  117. package/utils/array.d.ts +1 -0
  118. package/utils/array.js +10 -0
  119. package/utils/environment.d.ts +2 -0
  120. package/utils/environment.js +59 -0
  121. package/utils/index.d.ts +4 -0
  122. package/utils/index.js +10 -2
  123. package/utils/lazy.d.ts +2 -0
  124. package/utils/lazy.js +43 -0
@@ -7,7 +7,7 @@ import { TransactionError } from '@subwallet/extension-base/background/errors/Tr
7
7
  import { isJsonPayload, SEED_DEFAULT_LENGTH, SEED_LENGTHS } from '@subwallet/extension-base/background/handlers/Extension';
8
8
  import { withErrorLog } from '@subwallet/extension-base/background/handlers/helpers';
9
9
  import { createSubscription } from '@subwallet/extension-base/background/handlers/subscriptions';
10
- import { AccountExternalErrorCode, BasicTxErrorType, BasicTxWarningCode, ChainType, ExternalRequestPromiseStatus, ExtrinsicType, StakingType, TransferTxErrorType } from '@subwallet/extension-base/background/KoniTypes';
10
+ import { AccountExternalErrorCode, BasicTxErrorType, BasicTxWarningCode, ChainType, ExternalRequestPromiseStatus, ExtrinsicType, MantaPayEnableMessage, StakingType, TransferTxErrorType } from '@subwallet/extension-base/background/KoniTypes';
11
11
  import { TransactionWarning } from '@subwallet/extension-base/background/warnings/TransactionWarning';
12
12
  import { ALL_ACCOUNT_KEY, ALL_GENESIS_HASH, XCM_MIN_AMOUNT_RATIO } from '@subwallet/extension-base/constants';
13
13
  import { ALLOWED_PATH } from '@subwallet/extension-base/defaults';
@@ -20,16 +20,21 @@ import { getPoolingBondingExtrinsic, getPoolingUnbondingExtrinsic, validatePoolB
20
20
  import { getERC20TransactionObject, getERC721Transaction, getEVMTransactionObject } from '@subwallet/extension-base/koni/api/tokens/evm/transfer';
21
21
  import { getPSP34TransferExtrinsic } from '@subwallet/extension-base/koni/api/tokens/wasm';
22
22
  import { createXcmExtrinsic } from '@subwallet/extension-base/koni/api/xcm';
23
- import { _getChainNativeTokenBasicInfo, _getContractAddressOfToken, _getEvmChainId, _getSubstrateGenesisHash, _getTokenMinAmount, _isAssetSmartContractNft, _isChainEvmCompatible, _isCustomAsset, _isLocalToken, _isNativeToken, _isTokenEvmSmartContract, _isTokenTransferredByEvm } from '@subwallet/extension-base/services/chain-service/utils';
23
+ import { _DEFAULT_MANTA_ZK_CHAIN, _MANTA_ZK_CHAIN_GROUP, _ZK_ASSET_PREFIX } from '@subwallet/extension-base/services/chain-service/constants';
24
+ import { _ChainConnectionStatus } from '@subwallet/extension-base/services/chain-service/types';
25
+ import { _getChainNativeTokenBasicInfo, _getContractAddressOfToken, _getEvmChainId, _getSubstrateGenesisHash, _getTokenMinAmount, _isAssetSmartContractNft, _isChainEvmCompatible, _isCustomAsset, _isLocalToken, _isMantaZkAsset, _isNativeToken, _isTokenEvmSmartContract, _isTokenTransferredByEvm } from '@subwallet/extension-base/services/chain-service/utils';
24
26
  import { EXTENSION_REQUEST_URL } from '@subwallet/extension-base/services/request-service/constants';
25
27
  import { DEFAULT_AUTO_LOCK_TIME } from '@subwallet/extension-base/services/setting-service/constants';
26
- import { reformatAddress } from '@subwallet/extension-base/utils';
28
+ import { WALLET_CONNECT_EIP155_NAMESPACE } from '@subwallet/extension-base/services/wallet-connect-service/constants';
29
+ import { isProposalExpired, isSupportWalletConnectChain, isSupportWalletConnectNamespace } from '@subwallet/extension-base/services/wallet-connect-service/helpers';
30
+ import { reformatAddress, uniqueStringArray } from '@subwallet/extension-base/utils';
27
31
  import { convertSubjectInfoToAddresses } from '@subwallet/extension-base/utils/address';
28
32
  import { createTransactionFromRLP, signatureToHex } from '@subwallet/extension-base/utils/eth';
29
33
  import { parseContractInput, parseEvmRlp } from '@subwallet/extension-base/utils/eth/parseTransaction';
30
34
  import { balanceFormatter, formatNumber } from '@subwallet/extension-base/utils/number';
31
35
  import { createPair } from '@subwallet/keyring';
32
36
  import { keyring } from '@subwallet/ui-keyring';
37
+ import { getSdkError } from '@walletconnect/utils';
33
38
  import BigN from 'bignumber.js';
34
39
  import { Transaction } from 'ethereumjs-tx';
35
40
  import { TypeRegistry } from '@polkadot/types';
@@ -60,13 +65,16 @@ export default class KoniExtension {
60
65
  #lockTimeOut = undefined;
61
66
  #koniState;
62
67
  #timeAutoLock = DEFAULT_AUTO_LOCK_TIME;
68
+ #skipAutoLock = false;
63
69
  constructor(state) {
64
70
  this.#koniState = state;
65
71
  const updateTimeAutoLock = rs => {
66
72
  this.#timeAutoLock = rs.timeAutoLock;
67
73
  clearTimeout(this.#lockTimeOut);
68
74
  this.#lockTimeOut = setTimeout(() => {
69
- this.keyringLock();
75
+ if (!this.#skipAutoLock) {
76
+ this.keyringLock();
77
+ }
70
78
  }, this.#timeAutoLock * 60 * 1000);
71
79
  };
72
80
  this.#koniState.settingService.getSettings(updateTimeAutoLock);
@@ -339,9 +347,25 @@ export default class KoniExtension {
339
347
  });
340
348
  return true;
341
349
  }
342
- windowOpen(path) {
343
- const url = `${chrome.extension.getURL('index.html')}#${path}`;
350
+ windowOpen({
351
+ allowedPath: path,
352
+ params,
353
+ subPath
354
+ }) {
355
+ let paramString = '';
356
+ if (params) {
357
+ paramString += '?';
358
+ for (let i = 0; i < Object.keys(params).length; i++) {
359
+ const [key, value] = Object.entries(params)[i];
360
+ paramString += `${key}=${value}`;
361
+ if (i !== Object.keys(params).length - 1) {
362
+ paramString += '&';
363
+ }
364
+ }
365
+ }
366
+ const url = `${chrome.extension.getURL('index.html')}#${path}${subPath || ''}${paramString}`;
344
367
  if (!ALLOWED_PATH.includes(path)) {
368
+ console.error('Not allowed to open the url:', url);
345
369
  return false;
346
370
  }
347
371
  withErrorLog(() => chrome.tabs.create({
@@ -489,7 +513,7 @@ export default class KoniExtension {
489
513
  const account = keyring.getAccount(address);
490
514
  const contact = keyring.getAddress(address);
491
515
  return account || contact || {
492
- ...keyring.saveRecent(accountId).json,
516
+ ...keyring.saveRecent(address).json,
493
517
  publicKey: decodeAddress(address)
494
518
  };
495
519
  } else {
@@ -1110,6 +1134,7 @@ export default class KoniExtension {
1110
1134
  address: ALL_ACCOUNT_KEY
1111
1135
  }, resolve);
1112
1136
  });
1137
+ await this.#koniState.disableMantaPay(address);
1113
1138
  return true;
1114
1139
  }
1115
1140
  seedCreateV2({
@@ -1404,7 +1429,11 @@ export default class KoniExtension {
1404
1429
  let transaction;
1405
1430
 
1406
1431
  // Get native token amount
1407
- const freeBalance = await this.#koniState.balanceService.getTokenFreeBalance(from, networkKey, tokenSlug);
1432
+ const freeBalance = await this.getAddressFreeBalance({
1433
+ address: from,
1434
+ networkKey,
1435
+ token: tokenSlug
1436
+ });
1408
1437
  try {
1409
1438
  if (isEthereumAddress(from) && isEthereumAddress(to) && _isTokenTransferredByEvm(tokenInfo)) {
1410
1439
  // TODO: review this
@@ -1417,6 +1446,10 @@ export default class KoniExtension {
1417
1446
  } else {
1418
1447
  [transaction, transferAmount.value] = await getEVMTransactionObject(chainInfo, to, txVal, !!transferAll, evmApiMap);
1419
1448
  }
1449
+ } else if (_isMantaZkAsset(tokenInfo)) {
1450
+ // TODO
1451
+ transaction = undefined;
1452
+ transferAmount.value = '0';
1420
1453
  } else {
1421
1454
  const substrateApi = this.#koniState.getSubstrateApi(networkKey);
1422
1455
  [transaction, transferAmount.value] = await createTransferExtrinsic({
@@ -1445,14 +1478,22 @@ export default class KoniExtension {
1445
1478
  if (!isTransferNativeToken) {
1446
1479
  const {
1447
1480
  value: balance
1448
- } = await this.#koniState.balanceService.getTokenFreeBalance(from, networkKey, tokenSlug);
1481
+ } = await this.getAddressFreeBalance({
1482
+ address: from,
1483
+ networkKey,
1484
+ token: tokenSlug
1485
+ });
1449
1486
  if (new BigN(balance).minus(transferAmount.value).lt(minAmount)) {
1450
1487
  inputTransaction.warnings.push(new TransactionWarning(BasicTxWarningCode.NOT_ENOUGH_EXISTENTIAL_DEPOSIT, ''));
1451
1488
  }
1452
1489
  }
1453
1490
  const {
1454
1491
  value: receiverBalance
1455
- } = await this.#koniState.balanceService.getTokenFreeBalance(to, networkKey, tokenSlug);
1492
+ } = await this.getAddressFreeBalance({
1493
+ address: from,
1494
+ networkKey,
1495
+ token: tokenSlug
1496
+ });
1456
1497
  if (new BigN(receiverBalance).plus(transferAmount.value).lt(minAmount)) {
1457
1498
  const atLeast = new BigN(minAmount).minus(receiverBalance).plus((tokenInfo.decimals || 0) === 0 ? 0 : 1);
1458
1499
  const atLeastStr = formatNumber(atLeast, tokenInfo.decimals || 0, balanceFormatter);
@@ -1656,6 +1697,12 @@ export default class KoniExtension {
1656
1697
  networkKey,
1657
1698
  token
1658
1699
  }) {
1700
+ if (token && _MANTA_ZK_CHAIN_GROUP.includes(networkKey)) {
1701
+ const tokenInfo = this.#koniState.chainService.getAssetBySlug(token);
1702
+ if (tokenInfo.symbol.startsWith(_ZK_ASSET_PREFIX)) {
1703
+ return await this.#koniState.getMantaPayZkBalance(address, tokenInfo);
1704
+ }
1705
+ }
1659
1706
  return await this.#koniState.balanceService.getTokenFreeBalance(address, networkKey, token);
1660
1707
  }
1661
1708
  async transferGetMaxTransferable({
@@ -1665,7 +1712,11 @@ export default class KoniExtension {
1665
1712
  networkKey,
1666
1713
  token
1667
1714
  }) {
1668
- const freeBalance = await this.#koniState.balanceService.getTokenFreeBalance(address, networkKey, token);
1715
+ const freeBalance = await this.getAddressFreeBalance({
1716
+ address,
1717
+ networkKey,
1718
+ token
1719
+ });
1669
1720
  const tokenInfo = token ? this.#koniState.chainService.getAssetBySlug(token) : this.#koniState.chainService.getNativeTokenInfo(networkKey);
1670
1721
  if (!_isNativeToken(tokenInfo)) {
1671
1722
  return freeBalance;
@@ -2609,6 +2660,7 @@ export default class KoniExtension {
2609
2660
  }) {
2610
2661
  try {
2611
2662
  keyring.unlockKeyring(password);
2663
+ this.#koniState.initMantaPay(password).catch(console.error);
2612
2664
  } catch (e) {
2613
2665
  return {
2614
2666
  errors: [e.message],
@@ -3012,12 +3064,254 @@ export default class KoniExtension {
3012
3064
  return await this.#koniState.approvePassPhishingPage(url);
3013
3065
  }
3014
3066
 
3067
+ /// Wallet connect
3068
+
3069
+ // Connect
3070
+ async connectWalletConnect({
3071
+ uri
3072
+ }) {
3073
+ await this.#koniState.walletConnectService.connect(uri);
3074
+ return true;
3075
+ }
3076
+ connectWCSubscribe(id, port) {
3077
+ const cb = createSubscription(id, port);
3078
+ const subscription = this.#koniState.requestService.connectWCSubject.subscribe(requests => cb(requests));
3079
+ port.onDisconnect.addListener(() => {
3080
+ this.cancelSubscription(id);
3081
+ subscription.unsubscribe();
3082
+ });
3083
+ return this.#koniState.requestService.allConnectWCRequests;
3084
+ }
3085
+ async approveWalletConnectSession({
3086
+ accounts: selectedAccounts,
3087
+ id
3088
+ }) {
3089
+ const request = this.#koniState.requestService.getConnectWCRequest(id);
3090
+ if (isProposalExpired(request.request.params)) {
3091
+ throw new Error('The proposal has been expired');
3092
+ }
3093
+ const wcId = request.request.id;
3094
+ const params = request.request.params;
3095
+ const requiredNamespaces = params.requiredNamespaces;
3096
+ const optionalNamespaces = params.optionalNamespaces;
3097
+ const availableNamespaces = {};
3098
+ const namespaces = {};
3099
+ const chainInfoMap = this.#koniState.getChainInfoMap();
3100
+ Object.entries(requiredNamespaces).forEach(([key, namespace]) => {
3101
+ if (isSupportWalletConnectNamespace(key)) {
3102
+ if (namespace.chains) {
3103
+ const unSupportChains = namespace.chains.filter(chain => !isSupportWalletConnectChain(chain, chainInfoMap));
3104
+ if (unSupportChains.length) {
3105
+ throw new Error(getSdkError('UNSUPPORTED_CHAINS').message + ' ' + unSupportChains.toString());
3106
+ }
3107
+ availableNamespaces[key] = namespace;
3108
+ }
3109
+ } else {
3110
+ throw new Error(getSdkError('UNSUPPORTED_NAMESPACE_KEY').message + ' ' + key);
3111
+ }
3112
+ });
3113
+ Object.entries(optionalNamespaces).forEach(([key, namespace]) => {
3114
+ if (isSupportWalletConnectNamespace(key)) {
3115
+ if (namespace.chains) {
3116
+ const supportChains = namespace.chains.filter(chain => isSupportWalletConnectChain(chain, chainInfoMap)) || [];
3117
+ const requiredNameSpace = availableNamespaces[key];
3118
+ const defaultChains = [];
3119
+ if (requiredNameSpace) {
3120
+ availableNamespaces[key] = {
3121
+ chains: [...(requiredNameSpace.chains || defaultChains), ...(supportChains || defaultChains)],
3122
+ events: requiredNameSpace.events,
3123
+ methods: requiredNameSpace.methods
3124
+ };
3125
+ } else {
3126
+ if (supportChains.length) {
3127
+ availableNamespaces[key] = {
3128
+ chains: supportChains,
3129
+ events: namespace.events,
3130
+ methods: namespace.methods
3131
+ };
3132
+ }
3133
+ }
3134
+ }
3135
+ }
3136
+ });
3137
+ Object.entries(availableNamespaces).forEach(([key, namespace]) => {
3138
+ if (namespace.chains) {
3139
+ const accounts = [];
3140
+ const chains = uniqueStringArray(namespace.chains);
3141
+ chains.forEach(chain => {
3142
+ accounts.push(...selectedAccounts.filter(address => isEthereumAddress(address) === (key === WALLET_CONNECT_EIP155_NAMESPACE)).map(address => `${chain}:${address}`));
3143
+ });
3144
+ namespaces[key] = {
3145
+ accounts,
3146
+ methods: namespace.methods,
3147
+ events: namespace.events,
3148
+ chains: chains
3149
+ };
3150
+ }
3151
+ });
3152
+ const result = {
3153
+ id: wcId,
3154
+ namespaces: namespaces,
3155
+ relayProtocol: params.relays[0].protocol
3156
+ };
3157
+ await this.#koniState.walletConnectService.approveSession(result);
3158
+ request.resolve();
3159
+ return true;
3160
+ }
3161
+ async rejectWalletConnectSession({
3162
+ id
3163
+ }) {
3164
+ const request = this.#koniState.requestService.getConnectWCRequest(id);
3165
+ const wcId = request.request.id;
3166
+ if (isProposalExpired(request.request.params)) {
3167
+ request.reject(new Error('The proposal has been expired'));
3168
+ return true;
3169
+ }
3170
+ await this.#koniState.walletConnectService.rejectSession(wcId);
3171
+ request.reject(new Error('USER_REJECTED'));
3172
+ return true;
3173
+ }
3174
+ subscribeWalletConnectSessions(id, port) {
3175
+ const cb = createSubscription(id, port);
3176
+ const subscription = this.#koniState.walletConnectService.sessionSubject.subscribe(rs => {
3177
+ cb(rs);
3178
+ });
3179
+ port.onDisconnect.addListener(() => {
3180
+ subscription.unsubscribe();
3181
+ this.cancelSubscription(id);
3182
+ });
3183
+ return this.#koniState.walletConnectService.sessions;
3184
+ }
3185
+ async disconnectWalletConnectSession({
3186
+ topic
3187
+ }) {
3188
+ await this.#koniState.walletConnectService.disconnect(topic);
3189
+ return true;
3190
+ }
3191
+ async enableMantaPay({
3192
+ address,
3193
+ password
3194
+ }) {
3195
+ // always takes the current account
3196
+ function timeout() {
3197
+ return new Promise(resolve => setTimeout(resolve, 1500));
3198
+ }
3199
+ try {
3200
+ await this.#koniState.chainService.enableChain(_DEFAULT_MANTA_ZK_CHAIN);
3201
+ this.#koniState.chainService.setMantaZkAssetSettings(true);
3202
+ const mnemonic = this.keyringExportMnemonic({
3203
+ address,
3204
+ password
3205
+ });
3206
+ const {
3207
+ connectionStatus
3208
+ } = this.#koniState.chainService.getChainStateByKey(_DEFAULT_MANTA_ZK_CHAIN);
3209
+ if (connectionStatus !== _ChainConnectionStatus.CONNECTED) {
3210
+ // TODO: do better
3211
+ await timeout();
3212
+ }
3213
+ const result = await this.#koniState.enableMantaPay(true, address, password, mnemonic.result);
3214
+ this.#skipAutoLock = true;
3215
+ await this.saveCurrentAccountAddress({
3216
+ address
3217
+ });
3218
+ const unsubSyncProgress = await this.#koniState.chainService.mantaPay.subscribeSyncProgress();
3219
+ console.debug('Start initial sync for MantaPay');
3220
+ this.#koniState.initialSyncMantaPay(address).then(() => {
3221
+ console.debug('Finished initial sync for MantaPay');
3222
+ this.#skipAutoLock = false;
3223
+ unsubSyncProgress();
3224
+ }).catch(e => {
3225
+ console.error('Error syncing MantaPay', e);
3226
+ this.#skipAutoLock = false;
3227
+ unsubSyncProgress();
3228
+ });
3229
+ return {
3230
+ success: !!result,
3231
+ message: result ? MantaPayEnableMessage.SUCCESS : MantaPayEnableMessage.UNKNOWN_ERROR
3232
+ };
3233
+ } catch (e) {
3234
+ // @ts-ignore
3235
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
3236
+ if (e.toString() === 'Error: Unable to decode using the supplied passphrase') {
3237
+ return {
3238
+ success: false,
3239
+ message: MantaPayEnableMessage.WRONG_PASSWORD
3240
+ };
3241
+ }
3242
+ return {
3243
+ success: false,
3244
+ message: MantaPayEnableMessage.UNKNOWN_ERROR
3245
+ };
3246
+ }
3247
+ }
3248
+ async initSyncMantaPay(address) {
3249
+ if (this.#koniState.chainService.mantaPay.getSyncState().isSyncing) {
3250
+ return;
3251
+ }
3252
+ this.#skipAutoLock = true;
3253
+ await this.saveCurrentAccountAddress({
3254
+ address
3255
+ });
3256
+ const unsubSyncProgress = await this.#koniState.chainService.mantaPay.subscribeSyncProgress();
3257
+ console.debug('Start initial sync for MantaPay');
3258
+ this.#koniState.initialSyncMantaPay(address).then(() => {
3259
+ console.debug('Finished initial sync for MantaPay');
3260
+ this.#skipAutoLock = false;
3261
+ unsubSyncProgress();
3262
+ // make sure the sync state is set, just in case it gets unsubscribed
3263
+ this.#koniState.chainService.mantaPay.setSyncState({
3264
+ progress: 100,
3265
+ isSyncing: false
3266
+ });
3267
+ }).catch(e => {
3268
+ console.error('Error syncing MantaPay', e);
3269
+ this.#skipAutoLock = false;
3270
+ unsubSyncProgress();
3271
+ this.#koniState.chainService.mantaPay.setSyncState({
3272
+ progress: 0,
3273
+ isSyncing: false
3274
+ });
3275
+ });
3276
+ }
3277
+ async disableMantaPay(address) {
3278
+ return this.#koniState.disableMantaPay(address);
3279
+ }
3280
+ subscribeMantaPayConfig(id, port) {
3281
+ const cb = createSubscription(id, port);
3282
+ const mantaPayConfigSubscription = this.#koniState.subscribeMantaPayConfig().subscribe({
3283
+ next: rs => {
3284
+ cb(rs);
3285
+ }
3286
+ });
3287
+ this.createUnsubscriptionHandle(id, mantaPayConfigSubscription.unsubscribe);
3288
+ port.onDisconnect.addListener(() => {
3289
+ this.cancelSubscription(id);
3290
+ });
3291
+ return this.#koniState.getMantaPayConfig('calamari');
3292
+ }
3293
+ subscribeMantaPaySyncState(id, port) {
3294
+ const cb = createSubscription(id, port);
3295
+ const syncingStateSubscription = this.#koniState.subscribeMantaPaySyncState().subscribe({
3296
+ next: rs => {
3297
+ cb(rs);
3298
+ }
3299
+ });
3300
+ this.createUnsubscriptionHandle(id, syncingStateSubscription.unsubscribe);
3301
+ port.onDisconnect.addListener(() => {
3302
+ this.cancelSubscription(id);
3303
+ });
3304
+ return this.#koniState.chainService.mantaPay.getSyncState();
3305
+ }
3306
+
3015
3307
  // --------------------------------------------------------------
3016
3308
  // eslint-disable-next-line @typescript-eslint/require-await
3017
3309
  async handle(id, type, request, port) {
3018
3310
  clearTimeout(this.#lockTimeOut);
3019
3311
  this.#lockTimeOut = setTimeout(() => {
3020
- this.keyringLock();
3312
+ if (!this.#skipAutoLock) {
3313
+ this.keyringLock();
3314
+ }
3021
3315
  }, this.#timeAutoLock * 60 * 1000);
3022
3316
  switch (type) {
3023
3317
  /// Clone from PolkadotJs
@@ -3385,6 +3679,29 @@ export default class KoniExtension {
3385
3679
  case 'pri(settings.getLogoMaps)':
3386
3680
  return await this.getLogoMap();
3387
3681
 
3682
+ /// Wallet Connect
3683
+ case 'pri(walletConnect.connect)':
3684
+ return this.connectWalletConnect(request);
3685
+ case 'pri(walletConnect.requests.subscribe)':
3686
+ return this.connectWCSubscribe(id, port);
3687
+ case 'pri(walletConnect.session.approve)':
3688
+ return this.approveWalletConnectSession(request);
3689
+ case 'pri(walletConnect.session.reject)':
3690
+ return this.rejectWalletConnectSession(request);
3691
+ case 'pri(walletConnect.session.subscribe)':
3692
+ return this.subscribeWalletConnectSessions(id, port);
3693
+ case 'pri(walletConnect.session.disconnect)':
3694
+ return this.disconnectWalletConnectSession(request);
3695
+ case 'pri(mantaPay.enable)':
3696
+ return await this.enableMantaPay(request);
3697
+ case 'pri(mantaPay.initSyncMantaPay)':
3698
+ return await this.initSyncMantaPay(request);
3699
+ case 'pri(mantaPay.subscribeConfig)':
3700
+ return await this.subscribeMantaPayConfig(id, port);
3701
+ case 'pri(mantaPay.disable)':
3702
+ return await this.disableMantaPay(request);
3703
+ case 'pri(mantaPay.subscribeSyncingState)':
3704
+ return this.subscribeMantaPaySyncState(id, port);
3388
3705
  // Default
3389
3706
  default:
3390
3707
  throw new Error(`Unable to handle message of type ${type}`);
@@ -1,10 +1,10 @@
1
1
  /// <reference types="chrome" />
2
2
  import { _AssetRef, _AssetType, _ChainAsset, _ChainInfo, _MultiChainAsset } from '@subwallet/chain-list/types';
3
- import { AddTokenRequestExternal, ApiMap, AuthRequestV2, BalanceItem, BalanceJson, BrowserConfirmationType, ChainStakingMetadata, ConfirmationsQueue, CrowdloanItem, CrowdloanJson, CurrentAccountInfo, EvmSendTransactionParams, ExternalRequestPromise, NftCollection, NftItem, NftJson, NominatorMetadata, RequestAccountExportPrivateKey, RequestCheckPublicAndSecretKey, RequestConfirmationComplete, RequestSettingsType, ResponseAccountExportPrivateKey, ResponseCheckPublicAndSecretKey, ServiceInfo, SingleModeJson, StakingItem, StakingJson, StakingRewardItem, StakingRewardJson, StakingType, ThemeNames, UiSettings } from '@subwallet/extension-base/background/KoniTypes';
3
+ import { AddTokenRequestExternal, AmountData, ApiMap, AuthRequestV2, BalanceItem, BalanceJson, BrowserConfirmationType, ChainStakingMetadata, ConfirmationsQueue, CrowdloanItem, CrowdloanJson, CurrentAccountInfo, EvmSendTransactionParams, ExternalRequestPromise, MantaPayConfig, NftCollection, NftItem, NftJson, NominatorMetadata, RequestAccountExportPrivateKey, RequestCheckPublicAndSecretKey, RequestConfirmationComplete, RequestSettingsType, ResponseAccountExportPrivateKey, ResponseCheckPublicAndSecretKey, ServiceInfo, SingleModeJson, StakingItem, StakingJson, StakingRewardItem, StakingRewardJson, StakingType, ThemeNames, UiSettings } from '@subwallet/extension-base/background/KoniTypes';
4
4
  import { AccountJson, RequestAuthorizeTab, RequestRpcSend, RequestRpcSubscribe, RequestRpcUnsubscribe, RequestSign, ResponseRpcListProviders, ResponseSigning } from '@subwallet/extension-base/background/types';
5
5
  import { BalanceService } from '@subwallet/extension-base/services/balance-service';
6
6
  import { ChainService } from '@subwallet/extension-base/services/chain-service';
7
- import { _ChainConnectionStatus, _ChainState, _NetworkUpsertParams, _ValidateCustomAssetRequest } from '@subwallet/extension-base/services/chain-service/types';
7
+ import { _ChainState, _NetworkUpsertParams, _ValidateCustomAssetRequest } from '@subwallet/extension-base/services/chain-service/types';
8
8
  import { EventService } from '@subwallet/extension-base/services/event-service';
9
9
  import { HistoryService } from '@subwallet/extension-base/services/history-service';
10
10
  import { KeyringService } from '@subwallet/extension-base/services/keyring-service';
@@ -17,6 +17,7 @@ import SettingService from '@subwallet/extension-base/services/setting-service/S
17
17
  import DatabaseService from '@subwallet/extension-base/services/storage-service/DatabaseService';
18
18
  import { SubscanService } from '@subwallet/extension-base/services/subscan-service';
19
19
  import TransactionService from '@subwallet/extension-base/services/transaction-service';
20
+ import WalletConnectService from '@subwallet/extension-base/services/wallet-connect-service';
20
21
  import { MetadataDef, ProviderMeta } from '@subwallet/extension-inject/types';
21
22
  import SimpleKeyring from 'eth-simple-keyring';
22
23
  import { BehaviorSubject, Subject } from 'rxjs';
@@ -36,6 +37,8 @@ export default class KoniState {
36
37
  private crowdloanMap;
37
38
  private crowdloanSubject;
38
39
  private nftSubject;
40
+ private mantaPayConfigSubject;
41
+ isMantaPayEnabled: boolean;
39
42
  private stakingSubject;
40
43
  private chainStakingMetadataSubject;
41
44
  private stakingNominatorMetadataSubject;
@@ -58,6 +61,7 @@ export default class KoniState {
58
61
  readonly balanceService: BalanceService;
59
62
  readonly migrationService: MigrationService;
60
63
  readonly subscanService: SubscanService;
64
+ readonly walletConnectService: WalletConnectService;
61
65
  private generalStatus;
62
66
  private waitSleeping;
63
67
  private waitStarting;
@@ -77,6 +81,7 @@ export default class KoniState {
77
81
  get authSubjectV2(): BehaviorSubject<import("@subwallet/extension-base/background/types").AuthorizeRequest[]>;
78
82
  generateDefaultBalanceMap(): Record<string, BalanceItem>;
79
83
  init(): Promise<void>;
84
+ initMantaPay(password: string): Promise<void>;
80
85
  private startSubscription;
81
86
  onReady(): void;
82
87
  updateKeyringState(isReady?: boolean, callback?: () => void): void;
@@ -94,9 +99,11 @@ export default class KoniState {
94
99
  getChainStakingMetadata(): Promise<ChainStakingMetadata[]>;
95
100
  getStakingMetadataByChain(chain: string, type: StakingType): Promise<ChainStakingMetadata | undefined>;
96
101
  getNominatorMetadata(): Promise<NominatorMetadata[]>;
102
+ getMantaPayConfig(chain: string): Promise<MantaPayConfig[]>;
97
103
  getStaking(): Promise<StakingJson>;
98
104
  getStakingOwnersByChains(chains: string[]): Promise<string[]>;
99
105
  getPooledStakingRecordsByAddress(addresses: string[]): Promise<StakingItem[]>;
106
+ subscribeMantaPayConfig(): Subject<MantaPayConfig[]>;
100
107
  subscribeStaking(): Subject<StakingJson>;
101
108
  subscribeChainStakingMetadata(): Subject<ChainStakingMetadata[]>;
102
109
  subscribeNominatorMetadata(): Subject<NominatorMetadata[]>;
@@ -219,7 +226,6 @@ export default class KoniState {
219
226
  wakeup(): Promise<void>;
220
227
  cancelSubscription(id: string): boolean;
221
228
  createUnsubscriptionHandle(id: string, unsubscribe: () => void): void;
222
- updateChainConnectionStatus(chain: string, status: _ChainConnectionStatus): void;
223
229
  autoEnableChains(addresses: string[]): Promise<void>;
224
230
  onAccountAdd(): void;
225
231
  onAccountRemove(): void;
@@ -227,5 +233,13 @@ export default class KoniState {
227
233
  reloadStaking(): Promise<boolean>;
228
234
  approvePassPhishingPage(_url: string): Promise<boolean>;
229
235
  resetWallet(resetAll: boolean): Promise<void>;
236
+ enableMantaPay(updateStore: boolean, address: string, password: string, seedPhrase?: string): Promise<string | undefined>;
237
+ disableMantaPay(address: string): Promise<boolean>;
238
+ initialSyncMantaPay(address: string): Promise<boolean | undefined>;
239
+ getMantaZkBalance(): void;
240
+ subscribeMantaPayBalance(): () => void;
241
+ syncMantaPay(): Promise<void>;
242
+ getMantaPayZkBalance(address: string, tokenInfo: _ChainAsset): Promise<AmountData>;
243
+ subscribeMantaPaySyncState(): Subject<import("@subwallet/extension-base/background/KoniTypes").MantaPaySyncState>;
230
244
  }
231
245
  export {};