@subwallet/extension-base 1.3.22-0 → 1.3.23-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 (193) hide show
  1. package/background/KoniTypes.d.ts +75 -2
  2. package/background/KoniTypes.js +2 -0
  3. package/cjs/background/KoniTypes.js +2 -0
  4. package/cjs/constants/environment.js +4 -2
  5. package/cjs/constants/signing.js +6 -2
  6. package/cjs/core/logic-validation/recipientAddress.js +9 -1
  7. package/cjs/core/logic-validation/transfer.js +35 -29
  8. package/cjs/core/types.js +1 -0
  9. package/cjs/core/utils.js +12 -1
  10. package/cjs/defaults.js +1 -1
  11. package/cjs/koni/api/dotsama/crowdloan.js +1 -1
  12. package/cjs/koni/api/nft/index.js +9 -16
  13. package/cjs/koni/api/staking/index.js +3 -4
  14. package/cjs/koni/background/handlers/Extension.js +234 -96
  15. package/cjs/koni/background/handlers/State.js +15 -0
  16. package/cjs/packageInfo.js +1 -1
  17. package/cjs/services/balance-service/helpers/subscribe/cardano/consts.js +11 -0
  18. package/cjs/services/balance-service/helpers/subscribe/cardano/index.js +63 -0
  19. package/cjs/services/balance-service/helpers/subscribe/cardano/types.js +1 -0
  20. package/cjs/services/balance-service/helpers/subscribe/cardano/utils.js +74 -0
  21. package/cjs/services/balance-service/helpers/subscribe/index.js +21 -7
  22. package/cjs/services/balance-service/helpers/subscribe/ton/utils.js +2 -2
  23. package/cjs/services/balance-service/index.js +4 -2
  24. package/cjs/services/balance-service/transfer/cardano-transfer.js +122 -0
  25. package/cjs/services/balance-service/transfer/token.js +4 -4
  26. package/cjs/services/chain-service/handler/CardanoApi.js +176 -0
  27. package/cjs/services/chain-service/handler/CardanoChainHandler.js +83 -0
  28. package/cjs/services/chain-service/handler/TonApi.js +2 -5
  29. package/cjs/services/chain-service/index.js +29 -7
  30. package/cjs/services/chain-service/utils/index.js +40 -11
  31. package/cjs/services/chain-service/utils/patch.js +1 -1
  32. package/cjs/services/earning-service/handlers/liquid-staking/bifrost-manta.js +1 -1
  33. package/cjs/services/earning-service/handlers/liquid-staking/bifrost.js +1 -1
  34. package/cjs/services/earning-service/service.js +6 -12
  35. package/cjs/services/fee-service/service.js +19 -8
  36. package/cjs/services/history-service/index.js +4 -6
  37. package/cjs/services/inapp-notification-service/index.js +12 -4
  38. package/cjs/services/keyring-service/context/account-context.js +17 -2
  39. package/cjs/services/keyring-service/context/handlers/Derive.js +10 -7
  40. package/cjs/services/keyring-service/context/handlers/Migration.js +268 -0
  41. package/cjs/services/keyring-service/context/handlers/Mnemonic.js +2 -2
  42. package/cjs/services/keyring-service/context/handlers/Secret.js +1 -1
  43. package/cjs/services/keyring-service/utils.js +18 -0
  44. package/cjs/services/request-service/handler/CardanoRequestHandler.js +172 -0
  45. package/cjs/services/request-service/handler/EvmRequestHandler.js +1 -1
  46. package/cjs/services/request-service/index.js +20 -2
  47. package/cjs/services/setting-service/constants.js +10 -1
  48. package/cjs/services/storage-service/DatabaseService.js +3 -0
  49. package/cjs/services/storage-service/db-stores/InappNotification.js +6 -0
  50. package/cjs/services/swap-service/handler/asset-hub/handler.js +0 -59
  51. package/cjs/services/swap-service/handler/chainflip-handler.js +33 -281
  52. package/cjs/services/swap-service/handler/hydradx-handler.js +23 -190
  53. package/cjs/services/swap-service/handler/simpleswap-handler.js +1 -222
  54. package/cjs/services/swap-service/handler/uniswap-handler.js +331 -0
  55. package/cjs/services/swap-service/index.js +31 -22
  56. package/cjs/services/swap-service/utils.js +21 -38
  57. package/cjs/services/transaction-service/helpers/index.js +6 -1
  58. package/cjs/services/transaction-service/index.js +278 -21
  59. package/cjs/services/transaction-service/utils.js +5 -1
  60. package/cjs/types/account/info/keyring.js +12 -1
  61. package/cjs/types/fee/cardano.js +1 -0
  62. package/cjs/types/swap/index.js +7 -2
  63. package/cjs/utils/account/analyze.js +2 -1
  64. package/cjs/utils/account/common.js +29 -20
  65. package/cjs/utils/account/derive/info/solo.js +9 -4
  66. package/cjs/utils/account/derive/validate.js +36 -2
  67. package/cjs/utils/account/transform.js +38 -13
  68. package/cjs/utils/fee/transfer.js +40 -7
  69. package/cjs/utils/index.js +2 -2
  70. package/cjs/utils/staticData/index.js +7 -2
  71. package/constants/environment.d.ts +1 -0
  72. package/constants/environment.js +2 -1
  73. package/constants/signing.js +6 -2
  74. package/core/logic-validation/recipientAddress.js +11 -3
  75. package/core/logic-validation/transfer.js +9 -3
  76. package/core/substrate/xcm-parser.d.ts +1 -1
  77. package/core/types.d.ts +1 -0
  78. package/core/types.js +1 -0
  79. package/core/utils.d.ts +1 -0
  80. package/core/utils.js +13 -3
  81. package/defaults.d.ts +1 -1
  82. package/defaults.js +1 -1
  83. package/koni/api/dotsama/crowdloan.js +3 -3
  84. package/koni/api/nft/index.js +10 -16
  85. package/koni/api/nft/story_odyssey_nft/index.d.ts +1 -1
  86. package/koni/api/staking/index.js +4 -5
  87. package/koni/background/handlers/Extension.d.ts +9 -0
  88. package/koni/background/handlers/Extension.js +144 -8
  89. package/koni/background/handlers/State.d.ts +5 -1
  90. package/koni/background/handlers/State.js +16 -1
  91. package/package.json +71 -9
  92. package/packageInfo.js +1 -1
  93. package/services/balance-service/helpers/subscribe/cardano/consts.d.ts +1 -0
  94. package/services/balance-service/helpers/subscribe/cardano/consts.js +4 -0
  95. package/services/balance-service/helpers/subscribe/cardano/index.d.ts +2 -0
  96. package/services/balance-service/helpers/subscribe/cardano/index.js +57 -0
  97. package/services/balance-service/helpers/subscribe/cardano/types.d.ts +34 -0
  98. package/services/balance-service/helpers/subscribe/cardano/types.js +1 -0
  99. package/services/balance-service/helpers/subscribe/cardano/utils.d.ts +15 -0
  100. package/services/balance-service/helpers/subscribe/cardano/utils.js +62 -0
  101. package/services/balance-service/helpers/subscribe/index.d.ts +2 -2
  102. package/services/balance-service/helpers/subscribe/index.js +23 -9
  103. package/services/balance-service/helpers/subscribe/ton/utils.d.ts +1 -1
  104. package/services/balance-service/helpers/subscribe/ton/utils.js +1 -1
  105. package/services/balance-service/index.js +4 -2
  106. package/services/balance-service/transfer/cardano-transfer.d.ts +24 -0
  107. package/services/balance-service/transfer/cardano-transfer.js +114 -0
  108. package/services/balance-service/transfer/token.d.ts +1 -1
  109. package/services/balance-service/transfer/token.js +2 -2
  110. package/services/chain-service/handler/CardanoApi.d.ts +38 -0
  111. package/services/chain-service/handler/CardanoApi.js +167 -0
  112. package/services/chain-service/handler/CardanoChainHandler.d.ts +17 -0
  113. package/services/chain-service/handler/CardanoChainHandler.js +75 -0
  114. package/services/chain-service/handler/TonApi.js +3 -6
  115. package/services/chain-service/handler/types.d.ts +1 -0
  116. package/services/chain-service/index.d.ts +3 -1
  117. package/services/chain-service/index.js +29 -7
  118. package/services/chain-service/types.d.ts +9 -1
  119. package/services/chain-service/utils/index.d.ts +4 -0
  120. package/services/chain-service/utils/index.js +32 -11
  121. package/services/chain-service/utils/patch.js +1 -1
  122. package/services/earning-service/handlers/liquid-staking/bifrost-manta.js +1 -1
  123. package/services/earning-service/handlers/liquid-staking/bifrost.js +1 -1
  124. package/services/earning-service/service.js +8 -14
  125. package/services/fee-service/service.js +19 -8
  126. package/services/history-service/index.js +6 -8
  127. package/services/inapp-notification-service/index.d.ts +3 -4
  128. package/services/inapp-notification-service/index.js +14 -6
  129. package/services/keyring-service/context/account-context.d.ts +6 -2
  130. package/services/keyring-service/context/account-context.js +17 -2
  131. package/services/keyring-service/context/handlers/Derive.d.ts +1 -1
  132. package/services/keyring-service/context/handlers/Derive.js +10 -8
  133. package/services/keyring-service/context/handlers/Migration.d.ts +17 -0
  134. package/services/keyring-service/context/handlers/Migration.js +258 -0
  135. package/services/keyring-service/context/handlers/Mnemonic.js +2 -2
  136. package/services/keyring-service/context/handlers/Secret.js +2 -2
  137. package/services/keyring-service/utils.d.ts +2 -0
  138. package/services/keyring-service/utils.js +11 -0
  139. package/services/request-service/handler/CardanoRequestHandler.d.ts +16 -0
  140. package/services/request-service/handler/CardanoRequestHandler.js +163 -0
  141. package/services/request-service/handler/EvmRequestHandler.js +1 -1
  142. package/services/request-service/index.d.ts +6 -3
  143. package/services/request-service/index.js +19 -5
  144. package/services/setting-service/constants.d.ts +3 -0
  145. package/services/setting-service/constants.js +6 -0
  146. package/services/storage-service/DatabaseService.d.ts +1 -0
  147. package/services/storage-service/DatabaseService.js +3 -0
  148. package/services/storage-service/db-stores/InappNotification.d.ts +1 -0
  149. package/services/storage-service/db-stores/InappNotification.js +6 -0
  150. package/services/swap-service/handler/asset-hub/handler.d.ts +1 -4
  151. package/services/swap-service/handler/asset-hub/handler.js +2 -61
  152. package/services/swap-service/handler/base-handler.d.ts +1 -4
  153. package/services/swap-service/handler/chainflip-handler.d.ts +2 -9
  154. package/services/swap-service/handler/chainflip-handler.js +31 -280
  155. package/services/swap-service/handler/hydradx-handler.d.ts +1 -6
  156. package/services/swap-service/handler/hydradx-handler.js +13 -180
  157. package/services/swap-service/handler/simpleswap-handler.d.ts +1 -4
  158. package/services/swap-service/handler/simpleswap-handler.js +5 -226
  159. package/services/swap-service/handler/uniswap-handler.d.ts +41 -0
  160. package/services/swap-service/handler/uniswap-handler.js +323 -0
  161. package/services/swap-service/index.js +30 -22
  162. package/services/swap-service/utils.d.ts +1 -5
  163. package/services/swap-service/utils.js +7 -21
  164. package/services/transaction-service/helpers/index.d.ts +2 -0
  165. package/services/transaction-service/helpers/index.js +4 -0
  166. package/services/transaction-service/index.d.ts +8 -2
  167. package/services/transaction-service/index.js +263 -10
  168. package/services/transaction-service/types.d.ts +7 -0
  169. package/services/transaction-service/utils.js +7 -2
  170. package/types/account/info/keyring.d.ts +4 -1
  171. package/types/account/info/keyring.js +9 -0
  172. package/types/account/info/proxy.d.ts +2 -0
  173. package/types/balance/index.d.ts +4 -1
  174. package/types/fee/base.d.ts +1 -1
  175. package/types/fee/cardano.d.ts +18 -0
  176. package/types/fee/cardano.js +1 -0
  177. package/types/fee/subscription.d.ts +4 -3
  178. package/types/swap/index.d.ts +11 -3
  179. package/types/swap/index.js +7 -2
  180. package/utils/account/analyze.js +2 -1
  181. package/utils/account/common.d.ts +11 -6
  182. package/utils/account/common.js +28 -19
  183. package/utils/account/derive/info/solo.js +10 -5
  184. package/utils/account/derive/validate.d.ts +1 -0
  185. package/utils/account/derive/validate.js +34 -1
  186. package/utils/account/transform.d.ts +2 -1
  187. package/utils/account/transform.js +37 -13
  188. package/utils/fee/transfer.d.ts +2 -1
  189. package/utils/fee/transfer.js +44 -11
  190. package/utils/index.js +4 -4
  191. package/utils/staticData/index.d.ts +4 -1
  192. package/utils/staticData/index.js +5 -1
  193. package/utils/staticData/oldChainPrefix.json +1 -0
@@ -43,6 +43,7 @@ var _storage = require("@subwallet/extension-base/storage");
43
43
  var _types2 = require("@subwallet/extension-base/types");
44
44
  var _utils3 = require("@subwallet/extension-base/utils");
45
45
  var _promise = require("@subwallet/extension-base/utils/promise");
46
+ var _subwalletApiSdk = _interopRequireDefault(require("@subwallet/subwallet-api-sdk"));
46
47
  var _uiKeyring = require("@subwallet/ui-keyring");
47
48
  var _bn = _interopRequireDefault(require("bn.js"));
48
49
  var _i18next = require("i18next");
@@ -90,6 +91,8 @@ class KoniState {
90
91
  waitStarting = null;
91
92
  constructor() {
92
93
  let providers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
94
+ // Init subwallet api sdk
95
+ _subwalletApiSdk.default.init(_constants.BACKEND_API_URL);
93
96
  this.providers = providers;
94
97
  this.eventService = new _eventService.EventService();
95
98
  this.dbService = new _DatabaseService.default(this.eventService);
@@ -731,6 +734,12 @@ class KoniState {
731
734
  getTonApi(networkKey) {
732
735
  return this.chainService.getTonApi(networkKey);
733
736
  }
737
+ getCardanoApiMap() {
738
+ return this.chainService.getCardanoApiMap();
739
+ }
740
+ getCardanoApi(networkKey) {
741
+ return this.chainService.getCardanoApi(networkKey);
742
+ }
734
743
  getApiMap() {
735
744
  return {
736
745
  substrate: this.chainService.getSubstrateApiMap(),
@@ -1017,12 +1026,18 @@ class KoniState {
1017
1026
  getConfirmationsQueueSubjectTon() {
1018
1027
  return this.requestService.confirmationsQueueSubjectTon;
1019
1028
  }
1029
+ getConfirmationsQueueSubjectCardano() {
1030
+ return this.requestService.confirmationsQueueSubjectCardano;
1031
+ }
1020
1032
  async completeConfirmation(request) {
1021
1033
  return await this.requestService.completeConfirmation(request);
1022
1034
  }
1023
1035
  async completeConfirmationTon(request) {
1024
1036
  return await this.requestService.completeConfirmationTon(request);
1025
1037
  }
1038
+ async completeConfirmationCardano(request) {
1039
+ return await this.requestService.completeConfirmationCardano(request);
1040
+ }
1026
1041
  async onMV3Update() {
1027
1042
  const migrationStatus = await _storage.SWStorage.instance.getItem('mv3_migration');
1028
1043
  if (!migrationStatus || migrationStatus !== 'done') {
@@ -13,6 +13,6 @@ const packageInfo = {
13
13
  name: '@subwallet/extension-base',
14
14
  path: typeof __dirname === 'string' ? __dirname : 'auto',
15
15
  type: 'cjs',
16
- version: '1.3.22-0'
16
+ version: '1.3.23-0'
17
17
  };
18
18
  exports.packageInfo = packageInfo;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.DEFAULT_CARDANO_TTL_OFFSET = void 0;
7
+ // Copyright 2019-2022 @subwallet/extension-base
8
+ // SPDX-License-Identifier: Apache-2.0
9
+
10
+ const DEFAULT_CARDANO_TTL_OFFSET = 2 * 60 * 60 * 1000; // 2 hours
11
+ exports.DEFAULT_CARDANO_TTL_OFFSET = DEFAULT_CARDANO_TTL_OFFSET;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.subscribeCardanoBalance = subscribeCardanoBalance;
7
+ var _types = require("@subwallet/chain-list/types");
8
+ var _KoniTypes = require("@subwallet/extension-base/background/KoniTypes");
9
+ var _constants = require("@subwallet/extension-base/constants");
10
+ var _utils = require("@subwallet/extension-base/services/balance-service/helpers/subscribe/cardano/utils");
11
+ var _utils2 = require("@subwallet/extension-base/utils");
12
+ // Copyright 2019-2022 @subwallet/extension-base
13
+ // SPDX-License-Identifier: Apache-2.0
14
+
15
+ async function getBalanceMap(addresses, cardanoApi, isTestnet) {
16
+ const addressBalanceMap = {};
17
+ for (const address of addresses) {
18
+ addressBalanceMap[address] = await cardanoApi.getBalanceMap(isTestnet ? (0, _utils2.reformatAddress)(address, 0) : address);
19
+ }
20
+ return addressBalanceMap;
21
+ }
22
+ function subscribeCardanoBalance(params) {
23
+ const {
24
+ addresses,
25
+ assetMap,
26
+ callback,
27
+ cardanoApi,
28
+ chainInfo
29
+ } = params;
30
+ const chain = chainInfo.slug;
31
+ const isTestnet = chainInfo.isTestnet;
32
+ const tokens = (0, _utils2.filterAssetsByChainAndType)(assetMap, chain, [_types._AssetType.NATIVE, _types._AssetType.CIP26]);
33
+ function getBalance() {
34
+ getBalanceMap(addresses, cardanoApi, isTestnet).then(addressBalanceMap => {
35
+ Object.values(tokens).forEach(tokenInfo => {
36
+ const id = (0, _utils.getCardanoAssetId)(tokenInfo);
37
+ const balances = addresses.map(address => {
38
+ var _addressBalanceMap$ad;
39
+ if (!addressBalanceMap[address]) {
40
+ return '0';
41
+ }
42
+ return ((_addressBalanceMap$ad = addressBalanceMap[address].find(asset => asset.unit === id)) === null || _addressBalanceMap$ad === void 0 ? void 0 : _addressBalanceMap$ad.quantity) || '0';
43
+ });
44
+ const items = balances.map((balance, index) => {
45
+ return {
46
+ address: addresses[index],
47
+ tokenSlug: tokenInfo.slug,
48
+ free: balance,
49
+ locked: '0',
50
+ // todo: research cardano lock balance
51
+ state: _KoniTypes.APIItemState.READY
52
+ };
53
+ });
54
+ callback(items);
55
+ });
56
+ }).catch(e => console.error('Error while fetching cardano balance', e));
57
+ }
58
+ const interval = setInterval(getBalance, _constants.ASTAR_REFRESH_BALANCE_INTERVAL);
59
+ getBalance();
60
+ return () => {
61
+ clearInterval(interval);
62
+ };
63
+ }
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.cborToBytes = void 0;
7
+ exports.getAdaBelongUtxo = getAdaBelongUtxo;
8
+ exports.getCardanoAssetId = getCardanoAssetId;
9
+ exports.getCardanoTxFee = getCardanoTxFee;
10
+ exports.retryCardanoTxStatus = retryCardanoTxStatus;
11
+ exports.splitCardanoId = splitCardanoId;
12
+ var _cardanoSerializationLibNodejs = require("@emurgo/cardano-serialization-lib-nodejs");
13
+ // Copyright 2019-2022 @subwallet/extension-base
14
+ // SPDX-License-Identifier: Apache-2.0
15
+
16
+ function getCardanoAssetId(chainAsset) {
17
+ var _chainAsset$metadata;
18
+ return (_chainAsset$metadata = chainAsset.metadata) === null || _chainAsset$metadata === void 0 ? void 0 : _chainAsset$metadata.cardanoId;
19
+ }
20
+ function getCardanoTxFee(payload) {
21
+ return BigInt(_cardanoSerializationLibNodejs.Transaction.from_hex(payload).body().fee().to_str());
22
+ }
23
+ function getAdaBelongUtxo(payload, receiverAddress) {
24
+ const txOutputsRaw = _cardanoSerializationLibNodejs.Transaction.from_hex(payload).body().outputs().to_json();
25
+ const txOutputs = JSON.parse(txOutputsRaw);
26
+ const receiverUtxo = txOutputs.find(utxo => utxo.address === receiverAddress); // must has utxo to receiver
27
+
28
+ // @ts-ignore
29
+ return BigInt(receiverUtxo.amount.coin);
30
+ }
31
+ const cborToBytes = hex => {
32
+ if (hex.length % 2 === 0 && /^[0-9A-F]*$/i.test(hex)) {
33
+ return Buffer.from(hex, 'hex');
34
+ }
35
+ return Buffer.from(hex, 'utf-8');
36
+ };
37
+ exports.cborToBytes = cborToBytes;
38
+ async function retryCardanoTxStatus(fn, options) {
39
+ let lastError;
40
+ for (let i = 0; i < options.retries; i++) {
41
+ try {
42
+ return await fn();
43
+ } catch (e) {
44
+ if (e instanceof Error) {
45
+ lastError = e;
46
+ }
47
+
48
+ // todo: improve the timeout tx
49
+ await new Promise(resolve => setTimeout(resolve, options.delay)); // wait for delay period, then recall the fn()
50
+ }
51
+ }
52
+
53
+ console.error('Cardano transaction timeout', lastError); // throw only last error, in case no successful result from fn()
54
+
55
+ return false;
56
+ }
57
+ function splitCardanoId(id) {
58
+ if (id === 'lovelace') {
59
+ return {
60
+ cardanoId: id,
61
+ policyId: '',
62
+ nameHex: ''
63
+ };
64
+ }
65
+ if (!id || id.length < 56) {
66
+ throw new Error('The cardano native asset policy id must has 28 bytes in length.');
67
+ } else {
68
+ return {
69
+ cardanoId: id,
70
+ policyId: id.slice(0, 56),
71
+ nameHex: id.slice(56)
72
+ };
73
+ }
74
+ }
@@ -8,6 +8,7 @@ exports.getAccountJsonByAddress = void 0;
8
8
  exports.subscribeBalance = subscribeBalance;
9
9
  var _types = require("@subwallet/chain-list/types");
10
10
  var _KoniTypes = require("@subwallet/extension-base/background/KoniTypes");
11
+ var _cardano = require("@subwallet/extension-base/services/balance-service/helpers/subscribe/cardano");
11
12
  var _utils = require("@subwallet/extension-base/services/chain-service/utils");
12
13
  var _utils2 = require("@subwallet/extension-base/utils");
13
14
  var _uiKeyring = _interopRequireDefault(require("@subwallet/ui-keyring"));
@@ -45,16 +46,19 @@ exports.getAccountJsonByAddress = getAccountJsonByAddress;
45
46
  const filterAddress = (addresses, chainInfo) => {
46
47
  const {
47
48
  bitcoin,
49
+ cardano,
48
50
  evm,
49
51
  substrate,
50
52
  ton
51
- } = (0, _utils2.categoryAddresses)(addresses);
53
+ } = (0, _utils2.getAddressesByChainTypeMap)(addresses);
52
54
  if ((0, _utils._isChainEvmCompatible)(chainInfo)) {
53
- return [evm, [...bitcoin, ...substrate, ...ton]];
55
+ return [evm, [...bitcoin, ...substrate, ...ton, ...cardano]];
54
56
  } else if ((0, _utils._isChainBitcoinCompatible)(chainInfo)) {
55
- return [bitcoin, [...evm, ...substrate, ...ton]];
57
+ return [bitcoin, [...evm, ...substrate, ...ton, ...cardano]];
56
58
  } else if ((0, _utils._isChainTonCompatible)(chainInfo)) {
57
- return [ton, [...bitcoin, ...evm, ...substrate]];
59
+ return [ton, [...bitcoin, ...evm, ...substrate, ...cardano]];
60
+ } else if ((0, _utils._isChainCardanoCompatible)(chainInfo)) {
61
+ return [cardano, [...bitcoin, ...evm, ...substrate, ...ton]];
58
62
  } else {
59
63
  const fetchList = [];
60
64
  const unfetchList = [];
@@ -80,11 +84,11 @@ const filterAddress = (addresses, chainInfo) => {
80
84
  fetchList.push(address);
81
85
  }
82
86
  });
83
- return [fetchList, [...unfetchList, ...bitcoin, ...evm, ...ton]];
87
+ return [fetchList, [...unfetchList, ...bitcoin, ...evm, ...ton, ...cardano]];
84
88
  }
85
89
  };
86
90
  const handleUnsupportedOrPendingAddresses = (addresses, chainSlug, chainAssetMap, state, callback) => {
87
- const tokens = (0, _utils2.filterAssetsByChainAndType)(chainAssetMap, chainSlug, [_types._AssetType.NATIVE, _types._AssetType.ERC20, _types._AssetType.PSP22, _types._AssetType.LOCAL, _types._AssetType.GRC20, _types._AssetType.VFT]);
91
+ const tokens = (0, _utils2.filterAssetsByChainAndType)(chainAssetMap, chainSlug, [_types._AssetType.NATIVE, _types._AssetType.ERC20, _types._AssetType.PSP22, _types._AssetType.LOCAL, _types._AssetType.GRC20, _types._AssetType.VFT, _types._AssetType.TEP74, _types._AssetType.CIP26]);
88
92
  const now = new Date().getTime();
89
93
  Object.values(tokens).forEach(token => {
90
94
  const items = addresses.map(address => ({
@@ -100,7 +104,7 @@ const handleUnsupportedOrPendingAddresses = (addresses, chainSlug, chainAssetMap
100
104
  };
101
105
 
102
106
  // main subscription, use for multiple chains, multiple addresses and multiple tokens
103
- function subscribeBalance(addresses, chains, tokens, _chainAssetMap, _chainInfoMap, substrateApiMap, evmApiMap, tonApiMap, callback, extrinsicType) {
107
+ function subscribeBalance(addresses, chains, tokens, _chainAssetMap, _chainInfoMap, substrateApiMap, evmApiMap, tonApiMap, cardanoApiMap, callback, extrinsicType) {
104
108
  // Filter chain and token
105
109
  const chainAssetMap = Object.fromEntries(Object.entries(_chainAssetMap).filter(_ref => {
106
110
  let [token] = _ref;
@@ -138,6 +142,16 @@ function subscribeBalance(addresses, chains, tokens, _chainAssetMap, _chainInfoM
138
142
  tonApi
139
143
  });
140
144
  }
145
+ const cardanoApi = cardanoApiMap[chainSlug];
146
+ if ((0, _utils._isPureCardanoChain)(chainInfo)) {
147
+ return (0, _cardano.subscribeCardanoBalance)({
148
+ addresses: useAddresses,
149
+ assetMap: chainAssetMap,
150
+ callback,
151
+ chainInfo,
152
+ cardanoApi
153
+ });
154
+ }
141
155
 
142
156
  // If the chain is not ready, return pending state
143
157
  if (!substrateApiMap[chainSlug].isApiReady) {
@@ -18,7 +18,7 @@ exports.getTransferCellPromise = getTransferCellPromise;
18
18
  exports.getWalletQueryId = getWalletQueryId;
19
19
  exports.isBounceableAddress = isBounceableAddress;
20
20
  exports.messageRelaxedToCell = messageRelaxedToCell;
21
- exports.retry = retry;
21
+ exports.retryTonTxStatus = retryTonTxStatus;
22
22
  exports.tonAddressInfo = tonAddressInfo;
23
23
  var _consts = require("@subwallet/extension-base/services/balance-service/helpers/subscribe/ton/consts");
24
24
  var _core = require("@ton/core");
@@ -45,7 +45,7 @@ function externalMessage(contract, seqno, body) {
45
45
  body: body
46
46
  }))).endCell();
47
47
  }
48
- async function retry(fn, options) {
48
+ async function retryTonTxStatus(fn, options) {
49
49
  let lastError;
50
50
  for (let i = 0; i < options.retries; i++) {
51
51
  try {
@@ -200,8 +200,9 @@ class BalanceService {
200
200
  const evmApiMap = this.state.chainService.getEvmApiMap();
201
201
  const substrateApiMap = this.state.chainService.getSubstrateApiMap();
202
202
  const tonApiMap = this.state.chainService.getTonApiMap();
203
+ const cardanoApiMap = this.state.chainService.getCardanoApiMap();
203
204
  let unsub = _util.noop;
204
- unsub = (0, _helpers.subscribeBalance)([address], [chain], [tSlug], assetMap, chainInfoMap, substrateApiMap, evmApiMap, tonApiMap, result => {
205
+ unsub = (0, _helpers.subscribeBalance)([address], [chain], [tSlug], assetMap, chainInfoMap, substrateApiMap, evmApiMap, tonApiMap, cardanoApiMap, result => {
205
206
  const rs = result[0];
206
207
  let value;
207
208
  switch (balanceType) {
@@ -371,13 +372,14 @@ class BalanceService {
371
372
  const evmApiMap = this.state.chainService.getEvmApiMap();
372
373
  const substrateApiMap = this.state.chainService.getSubstrateApiMap();
373
374
  const tonApiMap = this.state.chainService.getTonApiMap();
375
+ const cardanoApiMap = this.state.chainService.getCardanoApiMap();
374
376
  const activeChainSlugs = Object.keys(this.state.getActiveChainInfoMap());
375
377
  const assetState = this.state.chainService.subscribeAssetSettings().value;
376
378
  const assets = Object.values(assetMap).filter(asset => {
377
379
  var _assetState$asset$slu;
378
380
  return activeChainSlugs.includes(asset.originChain) && ((_assetState$asset$slu = assetState[asset.slug]) === null || _assetState$asset$slu === void 0 ? void 0 : _assetState$asset$slu.visible);
379
381
  }).map(asset => asset.slug);
380
- const unsub = (0, _helpers.subscribeBalance)(addresses, activeChainSlugs, assets, assetMap, chainInfoMap, substrateApiMap, evmApiMap, tonApiMap, result => {
382
+ const unsub = (0, _helpers.subscribeBalance)(addresses, activeChainSlugs, assets, assetMap, chainInfoMap, substrateApiMap, evmApiMap, tonApiMap, cardanoApiMap, result => {
381
383
  !cancel && this.setBalanceItem(result);
382
384
  }, _KoniTypes.ExtrinsicType.TRANSFER_BALANCE);
383
385
  const unsub2 = this.state.subscribeMantaPayBalance();
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createCardanoTransaction = createCardanoTransaction;
7
+ var csl = _interopRequireWildcard(require("@emurgo/cardano-serialization-lib-nodejs"));
8
+ var _types = require("@subwallet/chain-list/types");
9
+ var _utils = require("@subwallet/extension-base/services/balance-service/helpers/subscribe/cardano/utils");
10
+ var _subwalletApiSdk = require("@subwallet/subwallet-api-sdk");
11
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
12
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
13
+ // Copyright 2019-2022 @subwallet/extension-base
14
+ // SPDX-License-Identifier: Apache-2.0
15
+
16
+ async function createCardanoTransaction(params) {
17
+ var _tokenInfo$metadata;
18
+ const {
19
+ cardanoTtlOffset,
20
+ from,
21
+ networkKey,
22
+ to,
23
+ tokenInfo,
24
+ transferAll,
25
+ value
26
+ } = params;
27
+ const cardanoId = (_tokenInfo$metadata = tokenInfo.metadata) === null || _tokenInfo$metadata === void 0 ? void 0 : _tokenInfo$metadata.cardanoId;
28
+ const isNativeTransfer = tokenInfo.assetType === _types._AssetType.NATIVE;
29
+ const isSelfTransfer = from === to;
30
+ if (!cardanoId) {
31
+ throw new Error('Missing token policy id metadata');
32
+ }
33
+ const payload = await _subwalletApiSdk.subwalletApiSdk.fetchUnsignedPayload({
34
+ tokenDecimals: params.tokenInfo.decimals || 0,
35
+ nativeTokenSymbol: params.nativeTokenInfo.symbol,
36
+ cardanoId,
37
+ from: params.from,
38
+ to: params.to,
39
+ value: params.value,
40
+ cardanoTtlOffset: params.cardanoTtlOffset
41
+ });
42
+ console.log('Build cardano payload successfully!', payload);
43
+ validatePayload(payload, params);
44
+ const fee = (0, _utils.getCardanoTxFee)(payload);
45
+ const adaBelongToCnaUtxo = isNativeTransfer || isSelfTransfer ? BigInt(0) : (0, _utils.getAdaBelongUtxo)(payload, to);
46
+ const tx = {
47
+ from,
48
+ to,
49
+ networkKey,
50
+ value,
51
+ transferAll,
52
+ cardanoTtlOffset,
53
+ estimateCardanoFee: (fee + adaBelongToCnaUtxo).toString(),
54
+ cardanoPayload: payload
55
+ };
56
+ return [tx, value];
57
+ }
58
+ function validatePayload(payload, params) {
59
+ var _params$tokenInfo$met;
60
+ const txInfo = JSON.parse(csl.Transaction.from_hex(payload).to_json());
61
+ const outputs = txInfo.body.outputs;
62
+ const cardanoId = (_params$tokenInfo$met = params.tokenInfo.metadata) === null || _params$tokenInfo$met === void 0 ? void 0 : _params$tokenInfo$met.cardanoId;
63
+ const assetType = params.tokenInfo.assetType;
64
+ const isSendSameAddress = params.from === params.to;
65
+ if (!cardanoId) {
66
+ throw new Error('Missing cardano id metadata');
67
+ }
68
+ const cardanoAssetMetadata = (0, _utils.splitCardanoId)(cardanoId);
69
+ if (isSendSameAddress) {
70
+ validateAllOutputsBelongToAddress(params.from, outputs);
71
+ validateExistOutputWithAmountSend(params.value, outputs, assetType, cardanoAssetMetadata);
72
+ } else {
73
+ const [outputsBelongToReceiver, outputsNotBelongToReceiver] = [outputs.filter(output => output.address === params.to), outputs.filter(output => output.address !== params.to)];
74
+ validateReceiverOutputsWithAmountSend(params.value, outputsBelongToReceiver, assetType, cardanoAssetMetadata);
75
+ validateAllOutputsBelongToAddress(params.from, outputsNotBelongToReceiver);
76
+ }
77
+ }
78
+ function validateAllOutputsBelongToAddress(address, outputs) {
79
+ const found = outputs.find(output => output.address !== address);
80
+ if (found) {
81
+ throw new Error('Transaction has invalid address information');
82
+ }
83
+ }
84
+ function validateExistOutputWithAmountSend(amount, outputs, assetType, cardanoAssetMetadata) {
85
+ if (assetType === _types._AssetType.NATIVE) {
86
+ const found = outputs.find(output => output.amount.coin === amount);
87
+ if (found) {
88
+ return;
89
+ }
90
+ throw new Error('Transaction has invalid transfer amount information');
91
+ }
92
+ if (assetType === _types._AssetType.CIP26) {
93
+ const found = outputs.find(output => {
94
+ var _output$amount$multia;
95
+ return amount === ((_output$amount$multia = output.amount.multiasset[cardanoAssetMetadata.policyId]) === null || _output$amount$multia === void 0 ? void 0 : _output$amount$multia[cardanoAssetMetadata.nameHex]);
96
+ });
97
+ if (found) {
98
+ return;
99
+ }
100
+ throw new Error('Transaction has invalid transfer amount information');
101
+ }
102
+ throw new Error('Invalid asset type!');
103
+ }
104
+ function validateReceiverOutputsWithAmountSend(amount, outputs, assetType, cardanoAssetMetadata) {
105
+ if (outputs.length !== 1) {
106
+ throw new Error('Transaction has invalid transfer amount information');
107
+ }
108
+ const receiverOutput = outputs[0];
109
+ if (assetType === _types._AssetType.NATIVE) {
110
+ if (receiverOutput.amount.coin === amount) {
111
+ return;
112
+ }
113
+ throw new Error('Transaction has invalid transfer amount information');
114
+ }
115
+ if (assetType === _types._AssetType.CIP26) {
116
+ if (receiverOutput.amount.multiasset[cardanoAssetMetadata.policyId][cardanoAssetMetadata.nameHex] === amount) {
117
+ return;
118
+ }
119
+ throw new Error('Transaction has invalid transfer amount information');
120
+ }
121
+ throw new Error('Invalid asset type!');
122
+ }
@@ -4,7 +4,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.getTransferMockTxFee = exports.createTransferExtrinsic = void 0;
7
+ exports.getTransferMockTxFee = exports.createSubstrateExtrinsic = void 0;
8
8
  var _api = require("@gear-js/api");
9
9
  var _types = require("@subwallet/chain-list/types");
10
10
  var _wasm = require("@subwallet/extension-base/koni/api/contract-handler/wasm");
@@ -23,7 +23,7 @@ var _utilCrypto = require("@polkadot/util-crypto");
23
23
  // Copyright 2019-2022 @subwallet/extension-base
24
24
  // SPDX-License-Identifier: Apache-2.0
25
25
 
26
- const createTransferExtrinsic = async _ref => {
26
+ const createSubstrateExtrinsic = async _ref => {
27
27
  var _tokenInfo$metadata;
28
28
  let {
29
29
  from,
@@ -119,7 +119,7 @@ const createTransferExtrinsic = async _ref => {
119
119
  }
120
120
  return [transfer, transferAmount || value];
121
121
  };
122
- exports.createTransferExtrinsic = createTransferExtrinsic;
122
+ exports.createSubstrateExtrinsic = createSubstrateExtrinsic;
123
123
  const getTransferMockTxFee = async (address, chainInfo, tokenInfo, api) => {
124
124
  try {
125
125
  let estimatedFee;
@@ -157,7 +157,7 @@ const getTransferMockTxFee = async (address, chainInfo, tokenInfo, api) => {
157
157
  var _paymentInfo$partialF;
158
158
  const substrateApi = api;
159
159
  const chainApi = await substrateApi.isReady;
160
- const [mockTx] = await createTransferExtrinsic({
160
+ const [mockTx] = await createSubstrateExtrinsic({
161
161
  from: address,
162
162
  networkKey: chainInfo.slug,
163
163
  substrateApi: chainApi,
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.CardanoApi = exports.API_KEY = void 0;
7
+ var _utils = require("@subwallet/extension-base/services/balance-service/helpers/subscribe/cardano/utils");
8
+ var _types = require("@subwallet/extension-base/services/chain-service/types");
9
+ var _utils2 = require("@subwallet/extension-base/utils");
10
+ var _rxjs = require("rxjs");
11
+ var _util = require("@polkadot/util");
12
+ // Copyright 2019-2022 @subwallet/extension-base authors & contributors
13
+ // SPDX-License-Identifier: Apache-2.0
14
+
15
+ const API_KEY = {
16
+ mainnet: process.env.BLOCKFROST_API_KEY_MAIN || '',
17
+ testnet: process.env.BLOCKFROST_API_KEY_PREP || ''
18
+ };
19
+ exports.API_KEY = API_KEY;
20
+ class CardanoApi {
21
+ // private api: BlockFrostAPI;
22
+
23
+ apiRetry = 0;
24
+ isApiConnectedSubject = new _rxjs.BehaviorSubject(false);
25
+ connectionStatusSubject = new _rxjs.BehaviorSubject(_types._ChainConnectionStatus.DISCONNECTED);
26
+ isApiReady = false;
27
+ isApiReadyOnce = false;
28
+ constructor(chainSlug, apiUrl, _ref) {
29
+ let {
30
+ isTestnet,
31
+ providerName
32
+ } = _ref;
33
+ this.chainSlug = chainSlug;
34
+ this.apiUrl = apiUrl;
35
+ this.isTestnet = isTestnet !== null && isTestnet !== void 0 ? isTestnet : true;
36
+ this.projectId = isTestnet ? API_KEY.testnet : API_KEY.mainnet;
37
+ this.providerName = providerName || 'unknown';
38
+ // this.api = this.createProvider(isTestnet);
39
+ this.isReadyHandler = (0, _utils2.createPromiseHandler)();
40
+ this.connect();
41
+ }
42
+ get isApiConnected() {
43
+ return this.isApiConnectedSubject.getValue();
44
+ }
45
+ get connectionStatus() {
46
+ return this.connectionStatusSubject.getValue();
47
+ }
48
+ updateConnectionStatus(status) {
49
+ const isConnected = status === _types._ChainConnectionStatus.CONNECTED;
50
+ if (isConnected !== this.isApiConnectedSubject.value) {
51
+ this.isApiConnectedSubject.next(isConnected);
52
+ }
53
+ if (status !== this.connectionStatusSubject.value) {
54
+ this.connectionStatusSubject.next(status);
55
+ }
56
+ }
57
+ get isReady() {
58
+ return this.isReadyHandler.promise;
59
+ }
60
+ async updateApiUrl(apiUrl) {
61
+ if (this.apiUrl === apiUrl) {
62
+ return;
63
+ }
64
+ await this.disconnect();
65
+ this.apiUrl = apiUrl;
66
+ // this.api = this.createProvider();
67
+ }
68
+
69
+ async recoverConnect() {
70
+ await this.disconnect();
71
+ this.connect();
72
+ await this.isReadyHandler.promise;
73
+ }
74
+
75
+ // private createProvider (isTestnet = true): BlockFrostAPI {
76
+ // const projectId = isTestnet ? API_KEY.testnet : API_KEY.mainnet;
77
+ //
78
+ // return new BlockFrostAPI({
79
+ // projectId
80
+ // });
81
+ // }
82
+
83
+ connect() {
84
+ this.updateConnectionStatus(_types._ChainConnectionStatus.CONNECTING);
85
+ // There isn't a persistent network connection underlying TonClient. Cant check connection status.
86
+ // this.isApiReadyOnce = true;
87
+ this.onConnect();
88
+ }
89
+ async disconnect() {
90
+ this.onDisconnect();
91
+ this.updateConnectionStatus(_types._ChainConnectionStatus.DISCONNECTED);
92
+ return Promise.resolve();
93
+ }
94
+ destroy() {
95
+ // Todo: implement this in the future
96
+ return this.disconnect();
97
+ }
98
+ onConnect() {
99
+ if (!this.isApiConnected) {
100
+ console.log(`Connected to ${this.chainSlug} at ${this.apiUrl}`);
101
+ this.isApiReady = true;
102
+ if (this.isApiReadyOnce) {
103
+ this.isReadyHandler.resolve(this);
104
+ }
105
+ }
106
+ this.updateConnectionStatus(_types._ChainConnectionStatus.CONNECTED);
107
+ }
108
+ onDisconnect() {
109
+ this.updateConnectionStatus(_types._ChainConnectionStatus.DISCONNECTED);
110
+ if (this.isApiConnected) {
111
+ console.warn(`Disconnected from ${this.chainSlug} of ${this.apiUrl}`);
112
+ this.isApiReady = false;
113
+ this.isReadyHandler = (0, _utils2.createPromiseHandler)();
114
+ }
115
+ }
116
+ async getBalanceMap(address) {
117
+ try {
118
+ const url = this.isTestnet ? `https://cardano-preprod.blockfrost.io/api/v0/addresses/${address}` : `https://cardano-mainnet.blockfrost.io/api/v0/addresses/${address}`;
119
+ const response = await fetch(url, {
120
+ method: 'GET',
121
+ headers: {
122
+ Project_id: this.projectId
123
+ }
124
+ });
125
+ const addressBalance = await response.json();
126
+ return addressBalance.amount;
127
+ } catch (e) {
128
+ console.error('Error on getting account balance', e);
129
+ return [];
130
+ }
131
+ }
132
+ async sendCardanoTxReturnHash(tx) {
133
+ try {
134
+ const url = this.isTestnet ? 'https://cardano-preprod.blockfrost.io/api/v0/tx/submit' : 'https://cardano-mainnet.blockfrost.io/api/v0/tx/submit';
135
+ const response = await fetch(url, {
136
+ method: 'POST',
137
+ headers: {
138
+ Project_id: this.projectId,
139
+ 'Content-Type': 'application/cbor'
140
+ },
141
+ body: (0, _utils.cborToBytes)(tx)
142
+ });
143
+ const hash = (await response.text()).replace(/^"|"$/g, '');
144
+ if ((0, _util.isHex)((0, _util.hexAddPrefix)(hash))) {
145
+ return hash;
146
+ } else {
147
+ console.error('Error on submitting cardano tx');
148
+ return '';
149
+ }
150
+ } catch (e) {
151
+ console.error('Error on submitting cardano tx', e);
152
+ return '';
153
+ }
154
+ }
155
+ async getStatusByTxHash(txHash, ttl) {
156
+ const cronTime = 30000;
157
+ return (0, _utils.retryCardanoTxStatus)(async () => {
158
+ const url = this.isTestnet ? `https://cardano-preprod.blockfrost.io/api/v0/txs/${txHash}` : `https://cardano-mainnet.blockfrost.io/api/v0/txs/${txHash}`;
159
+ const response = await fetch(url, {
160
+ method: 'GET',
161
+ headers: {
162
+ Project_id: this.projectId
163
+ }
164
+ });
165
+ const txInfo = await response.json();
166
+ if (txInfo.block && txInfo.hash && txInfo.index >= 0) {
167
+ return true;
168
+ }
169
+ throw new Error('Transaction not found');
170
+ }, {
171
+ retries: ttl / cronTime,
172
+ delay: cronTime
173
+ });
174
+ }
175
+ }
176
+ exports.CardanoApi = CardanoApi;