@subwallet/extension-base 1.3.41-0 → 1.3.43-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 (219) hide show
  1. package/background/KoniTypes.d.ts +134 -5
  2. package/background/KoniTypes.js +18 -0
  3. package/background/errors/BitcoinProviderError.d.ts +6 -0
  4. package/background/errors/BitcoinProviderError.js +47 -0
  5. package/background/types.d.ts +1 -1
  6. package/cjs/background/KoniTypes.js +20 -1
  7. package/cjs/background/errors/BitcoinProviderError.js +54 -0
  8. package/cjs/constants/bitcoin.js +22 -0
  9. package/cjs/constants/index.js +16 -1
  10. package/cjs/core/logic-validation/recipientAddress.js +9 -0
  11. package/cjs/core/logic-validation/request.js +316 -3
  12. package/cjs/core/logic-validation/transfer.js +25 -5
  13. package/cjs/core/types.js +1 -0
  14. package/cjs/core/utils.js +15 -1
  15. package/cjs/koni/background/handlers/Extension.js +477 -93
  16. package/cjs/koni/background/handlers/State.js +249 -16
  17. package/cjs/koni/background/handlers/Tabs.js +119 -6
  18. package/cjs/packageInfo.js +1 -1
  19. package/cjs/page/bitcoin/index.js +67 -0
  20. package/cjs/page/index.js +5 -0
  21. package/cjs/services/balance-service/helpers/subscribe/bitcoin.js +94 -0
  22. package/cjs/services/balance-service/helpers/subscribe/index.js +19 -7
  23. package/cjs/services/balance-service/index.js +32 -4
  24. package/cjs/services/balance-service/transfer/bitcoin-transfer.js +119 -0
  25. package/cjs/services/balance-service/transfer/token.js +2 -0
  26. package/cjs/services/base/types.js +2 -0
  27. package/cjs/services/buy-service/index.js +17 -2
  28. package/cjs/services/chain-service/constants.js +14 -3
  29. package/cjs/services/chain-service/handler/bitcoin/BitcoinApi.js +105 -0
  30. package/cjs/services/chain-service/handler/bitcoin/BitcoinChainHandler.js +78 -0
  31. package/cjs/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/blockstream-testnet-strategy.js +371 -0
  32. package/cjs/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/index.js +19 -0
  33. package/cjs/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/mempool-testnet-strategy.js +368 -0
  34. package/cjs/services/chain-service/handler/bitcoin/strategy/SubWalletMainnet/index.js +302 -0
  35. package/cjs/services/chain-service/handler/bitcoin/strategy/types.js +1 -0
  36. package/cjs/services/chain-service/index.js +27 -3
  37. package/cjs/services/chain-service/utils/index.js +57 -4
  38. package/cjs/services/chain-service/utils/patch.js +1 -1
  39. package/cjs/services/earning-service/handlers/native-staking/para-chain.js +27 -5
  40. package/cjs/services/event-service/index.js +4 -0
  41. package/cjs/services/fee-service/service.js +8 -3
  42. package/cjs/services/hiro-service/index.js +96 -0
  43. package/cjs/services/hiro-service/utils/index.js +85 -0
  44. package/cjs/services/history-service/bitcoin-history.js +58 -0
  45. package/cjs/services/history-service/helpers/recoverHistoryStatus.js +96 -4
  46. package/cjs/services/history-service/index.js +41 -3
  47. package/cjs/services/keyring-service/context/handlers/Derive.js +1 -1
  48. package/cjs/services/keyring-service/context/handlers/Migration.js +2 -2
  49. package/cjs/services/keyring-service/context/handlers/Mnemonic.js +4 -3
  50. package/cjs/services/migration-service/scripts/MigrateNewUnifiedAccount.js +29 -0
  51. package/cjs/services/migration-service/scripts/index.js +3 -1
  52. package/cjs/services/request-service/handler/AuthRequestHandler.js +18 -0
  53. package/cjs/services/request-service/handler/BitcoinRequestHandler.js +427 -0
  54. package/cjs/services/request-service/index.js +29 -3
  55. package/cjs/services/rune-service/index.js +105 -0
  56. package/cjs/services/transaction-service/helpers/index.js +7 -1
  57. package/cjs/services/transaction-service/index.js +206 -16
  58. package/cjs/services/transaction-service/utils.js +6 -3
  59. package/cjs/strategy/api-request-strategy/context/base.js +31 -0
  60. package/cjs/strategy/api-request-strategy/index.js +90 -0
  61. package/cjs/strategy/api-request-strategy/types.js +1 -0
  62. package/cjs/strategy/api-request-strategy/utils/index.js +33 -0
  63. package/cjs/types/account/info/keyring.js +1 -1
  64. package/cjs/types/bitcoin.js +24 -0
  65. package/cjs/types/fee/bitcoin.js +1 -0
  66. package/cjs/types/fee/index.js +11 -0
  67. package/cjs/types/index.js +11 -0
  68. package/cjs/utils/account/analyze.js +3 -3
  69. package/cjs/utils/account/common.js +16 -6
  70. package/cjs/utils/account/derive/info/solo.js +68 -19
  71. package/cjs/utils/account/derive/info/unified.js +2 -0
  72. package/cjs/utils/account/derive/validate.js +70 -2
  73. package/cjs/utils/account/transform.js +11 -5
  74. package/cjs/utils/auth.js +2 -1
  75. package/cjs/utils/bitcoin/common.js +98 -0
  76. package/cjs/utils/bitcoin/fee.js +21 -0
  77. package/cjs/utils/bitcoin/index.js +38 -0
  78. package/cjs/utils/bitcoin/utxo-management.js +281 -0
  79. package/cjs/utils/fee/transfer.js +48 -0
  80. package/cjs/utils/index.js +15 -1
  81. package/constants/bitcoin.d.ts +3 -0
  82. package/constants/bitcoin.js +13 -0
  83. package/constants/index.d.ts +2 -0
  84. package/constants/index.js +3 -1
  85. package/core/logic-validation/recipientAddress.js +10 -1
  86. package/core/logic-validation/request.d.ts +6 -2
  87. package/core/logic-validation/request.js +309 -3
  88. package/core/logic-validation/transfer.d.ts +2 -2
  89. package/core/logic-validation/transfer.js +27 -7
  90. package/core/types.d.ts +1 -0
  91. package/core/types.js +1 -0
  92. package/core/utils.d.ts +1 -0
  93. package/core/utils.js +15 -2
  94. package/koni/background/handlers/Extension.d.ts +5 -0
  95. package/koni/background/handlers/Extension.js +387 -9
  96. package/koni/background/handlers/State.d.ts +10 -3
  97. package/koni/background/handlers/State.js +240 -15
  98. package/koni/background/handlers/Tabs.d.ts +7 -2
  99. package/koni/background/handlers/Tabs.js +119 -9
  100. package/package.json +149 -8
  101. package/packageInfo.js +1 -1
  102. package/page/bitcoin/index.d.ts +17 -0
  103. package/page/bitcoin/index.js +60 -0
  104. package/page/index.d.ts +2 -1
  105. package/page/index.js +4 -0
  106. package/services/balance-service/helpers/subscribe/bitcoin.d.ts +2 -0
  107. package/services/balance-service/helpers/subscribe/bitcoin.js +87 -0
  108. package/services/balance-service/helpers/subscribe/index.d.ts +2 -2
  109. package/services/balance-service/helpers/subscribe/index.js +20 -8
  110. package/services/balance-service/index.d.ts +2 -0
  111. package/services/balance-service/index.js +32 -4
  112. package/services/balance-service/transfer/bitcoin-transfer.d.ts +14 -0
  113. package/services/balance-service/transfer/bitcoin-transfer.js +112 -0
  114. package/services/balance-service/transfer/cardano-transfer.d.ts +2 -0
  115. package/services/balance-service/transfer/token.js +2 -0
  116. package/services/base/types.d.ts +2 -0
  117. package/services/base/types.js +2 -0
  118. package/services/buy-service/index.js +17 -2
  119. package/services/chain-service/constants.d.ts +6 -0
  120. package/services/chain-service/constants.js +8 -2
  121. package/services/chain-service/handler/bitcoin/BitcoinApi.d.ts +31 -0
  122. package/services/chain-service/handler/bitcoin/BitcoinApi.js +98 -0
  123. package/services/chain-service/handler/bitcoin/BitcoinChainHandler.d.ts +16 -0
  124. package/services/chain-service/handler/bitcoin/BitcoinChainHandler.js +70 -0
  125. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/blockstream-testnet-strategy.d.ts +28 -0
  126. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/blockstream-testnet-strategy.js +362 -0
  127. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/index.d.ts +2 -0
  128. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/index.js +5 -0
  129. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/mempool-testnet-strategy.d.ts +28 -0
  130. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/mempool-testnet-strategy.js +359 -0
  131. package/services/chain-service/handler/bitcoin/strategy/SubWalletMainnet/index.d.ts +28 -0
  132. package/services/chain-service/handler/bitcoin/strategy/SubWalletMainnet/index.js +293 -0
  133. package/services/chain-service/handler/bitcoin/strategy/types.d.ts +291 -0
  134. package/services/chain-service/handler/bitcoin/strategy/types.js +1 -0
  135. package/services/chain-service/index.d.ts +3 -0
  136. package/services/chain-service/index.js +31 -5
  137. package/services/chain-service/types.d.ts +20 -0
  138. package/services/chain-service/utils/index.d.ts +4 -0
  139. package/services/chain-service/utils/index.js +50 -4
  140. package/services/chain-service/utils/patch.js +1 -1
  141. package/services/earning-service/handlers/native-staking/para-chain.js +27 -5
  142. package/services/event-service/index.d.ts +3 -0
  143. package/services/event-service/index.js +4 -0
  144. package/services/event-service/types.d.ts +3 -0
  145. package/services/fee-service/service.js +8 -3
  146. package/services/hiro-service/index.d.ts +17 -0
  147. package/services/hiro-service/index.js +88 -0
  148. package/services/hiro-service/utils/index.d.ts +6 -0
  149. package/services/hiro-service/utils/index.js +72 -0
  150. package/services/history-service/bitcoin-history.d.ts +4 -0
  151. package/services/history-service/bitcoin-history.js +52 -0
  152. package/services/history-service/helpers/recoverHistoryStatus.d.ts +3 -1
  153. package/services/history-service/helpers/recoverHistoryStatus.js +96 -4
  154. package/services/history-service/index.d.ts +1 -0
  155. package/services/history-service/index.js +42 -4
  156. package/services/keyring-service/context/handlers/Derive.js +2 -2
  157. package/services/keyring-service/context/handlers/Migration.js +2 -2
  158. package/services/keyring-service/context/handlers/Mnemonic.js +4 -3
  159. package/services/migration-service/scripts/MigrateNewUnifiedAccount.d.ts +4 -0
  160. package/services/migration-service/scripts/MigrateNewUnifiedAccount.js +21 -0
  161. package/services/migration-service/scripts/index.js +3 -1
  162. package/services/request-service/handler/AuthRequestHandler.js +19 -1
  163. package/services/request-service/handler/BitcoinRequestHandler.d.ts +22 -0
  164. package/services/request-service/handler/BitcoinRequestHandler.js +414 -0
  165. package/services/request-service/index.d.ts +8 -2
  166. package/services/request-service/index.js +25 -3
  167. package/services/rune-service/index.d.ts +17 -0
  168. package/services/rune-service/index.js +97 -0
  169. package/services/transaction-service/helpers/index.d.ts +3 -1
  170. package/services/transaction-service/helpers/index.js +5 -0
  171. package/services/transaction-service/index.d.ts +4 -5
  172. package/services/transaction-service/index.js +205 -17
  173. package/services/transaction-service/types.d.ts +13 -2
  174. package/services/transaction-service/utils.js +7 -4
  175. package/strategy/api-request-strategy/context/base.d.ts +15 -0
  176. package/strategy/api-request-strategy/context/base.js +24 -0
  177. package/strategy/api-request-strategy/index.d.ts +15 -0
  178. package/strategy/api-request-strategy/index.js +83 -0
  179. package/strategy/api-request-strategy/types.d.ts +22 -0
  180. package/strategy/api-request-strategy/types.js +1 -0
  181. package/strategy/api-request-strategy/utils/index.d.ts +2 -0
  182. package/strategy/api-request-strategy/utils/index.js +23 -0
  183. package/types/account/info/keyring.d.ts +1 -1
  184. package/types/account/info/keyring.js +1 -1
  185. package/types/balance/index.d.ts +4 -1
  186. package/types/balance/transfer.d.ts +19 -0
  187. package/types/bitcoin.d.ts +93 -0
  188. package/types/bitcoin.js +17 -0
  189. package/types/buy.d.ts +1 -1
  190. package/types/fee/base.d.ts +4 -1
  191. package/types/fee/bitcoin.d.ts +18 -0
  192. package/types/fee/bitcoin.js +1 -0
  193. package/types/fee/index.d.ts +1 -0
  194. package/types/fee/index.js +2 -1
  195. package/types/fee/subscription.d.ts +4 -3
  196. package/types/index.d.ts +1 -0
  197. package/types/index.js +1 -0
  198. package/utils/account/analyze.js +4 -4
  199. package/utils/account/common.d.ts +7 -8
  200. package/utils/account/common.js +16 -6
  201. package/utils/account/derive/info/solo.js +70 -21
  202. package/utils/account/derive/info/unified.js +2 -0
  203. package/utils/account/derive/validate.d.ts +1 -0
  204. package/utils/account/derive/validate.js +68 -1
  205. package/utils/account/transform.d.ts +1 -1
  206. package/utils/account/transform.js +11 -5
  207. package/utils/auth.js +3 -2
  208. package/utils/bitcoin/common.d.ts +22 -0
  209. package/utils/bitcoin/common.js +88 -0
  210. package/utils/bitcoin/fee.d.ts +2 -0
  211. package/utils/bitcoin/fee.js +14 -0
  212. package/utils/bitcoin/index.d.ts +3 -0
  213. package/utils/bitcoin/index.js +6 -0
  214. package/utils/bitcoin/utxo-management.d.ts +33 -0
  215. package/utils/bitcoin/utxo-management.js +266 -0
  216. package/utils/fee/transfer.d.ts +3 -1
  217. package/utils/fee/transfer.js +47 -1
  218. package/utils/index.d.ts +1 -0
  219. package/utils/index.js +6 -3
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", {
6
6
  });
7
7
  exports.default = void 0;
8
8
  var CardanoWasm = _interopRequireWildcard(require("@emurgo/cardano-serialization-lib-nodejs"));
9
+ var _BitcoinProviderError = require("@subwallet/extension-base/background/errors/BitcoinProviderError");
9
10
  var _CardanoProviderError = require("@subwallet/extension-base/background/errors/CardanoProviderError");
10
11
  var _EvmProviderError = require("@subwallet/extension-base/background/errors/EvmProviderError");
11
12
  var _helpers = require("@subwallet/extension-base/background/handlers/helpers");
@@ -49,6 +50,8 @@ var _cardano = require("@subwallet/extension-base/utils/cardano");
49
50
  var _promise = require("@subwallet/extension-base/utils/promise");
50
51
  var _subwalletApiSdk = _interopRequireDefault(require("@subwallet/subwallet-api-sdk"));
51
52
  var _uiKeyring = require("@subwallet/ui-keyring");
53
+ var _bignumber = _interopRequireDefault(require("bignumber.js"));
54
+ var bitcoin = _interopRequireWildcard(require("bitcoinjs-lib"));
52
55
  var _bn = _interopRequireDefault(require("bn.js"));
53
56
  var _i18next = require("i18next");
54
57
  var _rxjs = require("rxjs");
@@ -95,6 +98,7 @@ class KoniState {
95
98
  generalStatus = _types.ServiceStatus.INITIALIZING;
96
99
  waitSleeping = null;
97
100
  waitStarting = null;
101
+ waitStartingFull = null;
98
102
  constructor() {
99
103
  let providers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
100
104
  // Init subwallet api sdk
@@ -106,11 +110,13 @@ class KoniState {
106
110
  this.eventService = new _eventService.EventService();
107
111
  this.dbService = new _DatabaseService.default(this.eventService);
108
112
  this.keyringService = new _keyringService.KeyringService(this);
113
+ this.feeService = new _service2.default(this);
114
+ this.transactionService = new _transactionService.default(this);
109
115
  this.notificationService = new _NotificationService.default();
110
116
  this.chainService = new _chainService.ChainService(this.dbService, this.eventService);
111
117
  this.subscanService = _subscanService.SubscanService.getInstance();
112
118
  this.settingService = new _SettingService.default();
113
- this.requestService = new _requestService.default(this.chainService, this.settingService, this.keyringService);
119
+ this.requestService = new _requestService.default(this.chainService, this.settingService, this.keyringService, this.transactionService);
114
120
  this.priceService = new _priceService.PriceService(this.dbService, this.eventService, this.chainService);
115
121
  this.balanceService = new _balanceService.BalanceService(this);
116
122
  this.historyService = new _historyService.HistoryService(this.dbService, this.chainService, this.eventService, this.keyringService, this.subscanService);
@@ -120,9 +126,7 @@ class KoniState {
120
126
  this.campaignService = new _campaignService.default(this);
121
127
  this.mktCampaignService = new _mktCampaignService.default(this);
122
128
  this.buyService = new _buyService.default(this);
123
- this.transactionService = new _transactionService.default(this);
124
129
  this.earningService = new _service.default(this);
125
- this.feeService = new _service2.default(this);
126
130
  this.swapService = new _swapService.SwapService(this);
127
131
  this.inappNotificationService = new _inappNotificationService.InappNotificationService(this.dbService, this.keyringService, this.eventService, this.chainService);
128
132
  this.chainOnlineService = new _chainOnlineService.ChainOnlineService(this.chainService, this.settingService, this.eventService, this.dbService);
@@ -132,7 +136,9 @@ class KoniState {
132
136
 
133
137
  // Init state
134
138
  if (_utils3.targetIsWeb) {
135
- this.init().catch(console.error);
139
+ this.init().then(() => {
140
+ this.wakeup(true).catch(console.error);
141
+ }).catch(console.error);
136
142
  }
137
143
  }
138
144
 
@@ -228,7 +234,8 @@ class KoniState {
228
234
  await this.earningService.init();
229
235
  await this.swapService.init();
230
236
  await this.inappNotificationService.init();
231
- this.onReady();
237
+
238
+ // this.onReady();
232
239
  this.onAccountAdd();
233
240
  this.onAccountRemove();
234
241
 
@@ -240,6 +247,9 @@ class KoniState {
240
247
  this.chainService.subscribeChainInfoMap().subscribe(() => {
241
248
  this.afterChainServiceInit();
242
249
  });
250
+
251
+ // Mark app is ready
252
+ this.eventService.emit('general.init', true);
243
253
  }
244
254
  async initMantaPay(password) {
245
255
  var _this$chainService, _this$chainService$ma;
@@ -263,11 +273,6 @@ class KoniState {
263
273
  this.mantaPayConfigSubject.next(data);
264
274
  });
265
275
  }
266
- onReady() {
267
- // Todo: Need optimize in the future to, only run important services onetime to save resources
268
- // Todo: If optimize must check activity of web-runner of mobile
269
- this._start().catch(console.error);
270
- }
271
276
  updateKeyringState() {
272
277
  let isReady = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
273
278
  let callback = arguments.length > 1 ? arguments[1] : undefined;
@@ -756,6 +761,9 @@ class KoniState {
756
761
  getCardanoApi(networkKey) {
757
762
  return this.chainService.getCardanoApi(networkKey);
758
763
  }
764
+ getBitcoinApi(networkKey) {
765
+ return this.chainService.getBitcoinApi(networkKey);
766
+ }
759
767
  getApiMap() {
760
768
  return {
761
769
  substrate: this.chainService.getSubstrateApiMap(),
@@ -1038,6 +1046,8 @@ class KoniState {
1038
1046
  });
1039
1047
  });
1040
1048
  }
1049
+
1050
+ // Cardano
1041
1051
  async cardanoGetBalance(id, url, address) {
1042
1052
  const authInfoMap = await this.getAuthList();
1043
1053
  const authInfo = authInfoMap[(0, _utils3.stripUrl)(url)];
@@ -1260,6 +1270,193 @@ class KoniState {
1260
1270
  const cardanoApi = this.chainService.getCardanoApi(networkKey);
1261
1271
  return await cardanoApi.sendCardanoTxReturnHash(txHex);
1262
1272
  }
1273
+
1274
+ // Bitcoin
1275
+ async bitcoinSign(id, url, method, params) {
1276
+ const {
1277
+ address,
1278
+ message
1279
+ } = params;
1280
+ const payloadValidation = {
1281
+ address,
1282
+ type: 'bitcoin',
1283
+ payloadAfterValidated: message,
1284
+ errors: [],
1285
+ networkKey: ''
1286
+ };
1287
+ const validationSteps = [_logicValidation.validationAuthMiddleware, _logicValidation.validationBitcoinSignMessageMiddleware];
1288
+ const result = await (0, _logicValidation.generateValidationProcess)(this, url, payloadValidation, validationSteps);
1289
+ const errorsFormated = (0, _logicValidation.convertErrorFormat)(result.errors);
1290
+ const payloadAfterValidated = {
1291
+ ...result.payloadAfterValidated,
1292
+ errors: errorsFormated,
1293
+ id
1294
+ };
1295
+ return this.requestService.addConfirmationBitcoin(id, url, 'bitcoinSignatureRequest', payloadAfterValidated, {}).then(_ref9 => {
1296
+ let {
1297
+ isApproved,
1298
+ payload
1299
+ } = _ref9;
1300
+ if (isApproved) {
1301
+ if (payload) {
1302
+ return payload;
1303
+ } else {
1304
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INVALID_PARAMS, (0, _i18next.t)('Not found signature'));
1305
+ }
1306
+ } else {
1307
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.USER_REJECTED_REQUEST);
1308
+ }
1309
+ });
1310
+ }
1311
+ async bitcoinSignPspt(id, url, params) {
1312
+ const {
1313
+ address,
1314
+ network,
1315
+ psbt
1316
+ } = params;
1317
+ const payloadValidation = {
1318
+ address,
1319
+ type: 'bitcoin',
1320
+ payloadAfterValidated: params,
1321
+ errors: [],
1322
+ networkKey: network === 'mainnet' ? 'bitcoin' : 'bitcoinTestnet'
1323
+ };
1324
+ const validationSteps = [_logicValidation.validationAuthMiddleware, _logicValidation.validationBitcoinConnectMiddleware, _logicValidation.validationBitcoinSignPsbtMiddleware];
1325
+ const result = await (0, _logicValidation.generateValidationProcess)(this, url, payloadValidation, validationSteps);
1326
+ const errorsFormated = (0, _logicValidation.convertErrorFormat)(result.errors);
1327
+ const payloadAfterValidated = {
1328
+ ...result.payloadAfterValidated,
1329
+ errors: errorsFormated
1330
+ };
1331
+ const network_ = network === 'mainnet' ? bitcoin.networks.bitcoin : bitcoin.networks.testnet;
1332
+ const psbtGenerate = bitcoin.Psbt.fromHex(psbt, {
1333
+ network: network_
1334
+ });
1335
+ const isExistedInput = (inputs, address) => inputs.findIndex(_ref10 => {
1336
+ let {
1337
+ address: address_
1338
+ } = _ref10;
1339
+ return (0, _utils3.isSameAddress)(address, address_ || '');
1340
+ });
1341
+ let to = '';
1342
+ const tokenInfo = this.getNativeTokenInfo(result.networkKey);
1343
+ let value = new _bignumber.default(0);
1344
+ const totalBalance = await this.balanceService.getTotalBalance(address, result.networkKey, tokenInfo.slug);
1345
+ let inputAmount = new _bignumber.default(0);
1346
+ const psbtInputData = psbtGenerate.data.inputs.reduce((inputs, _ref11, inputIndex) => {
1347
+ let {
1348
+ nonWitnessUtxo,
1349
+ witnessUtxo
1350
+ } = _ref11;
1351
+ let inputData = null;
1352
+ if (witnessUtxo) {
1353
+ inputData = {
1354
+ address: bitcoin.address.fromOutputScript(witnessUtxo === null || witnessUtxo === void 0 ? void 0 : witnessUtxo.script, network_),
1355
+ amount: witnessUtxo.value.toString()
1356
+ };
1357
+ } else if (nonWitnessUtxo) {
1358
+ const txin = psbtGenerate.txInputs[inputIndex];
1359
+ const txout = bitcoin.Transaction.fromBuffer(nonWitnessUtxo).outs[txin.index];
1360
+ inputData = {
1361
+ address: bitcoin.address.fromOutputScript(txout.script, network_),
1362
+ amount: txout.value.toString()
1363
+ };
1364
+ }
1365
+ if (inputData) {
1366
+ inputs.push(inputData);
1367
+ if ((0, _utils3.isSameAddress)(address, inputData.address || '')) {
1368
+ inputAmount = inputAmount.plus(new _bignumber.default(inputData.amount || '0'));
1369
+ }
1370
+ }
1371
+ return inputs;
1372
+ }, []);
1373
+ if (new _bignumber.default(totalBalance.value).lt(inputAmount)) {
1374
+ payloadAfterValidated.errors = [{
1375
+ message: (0, _i18next.t)('Insufficient balance'),
1376
+ name: (0, _i18next.t)('Unable to sign transaction')
1377
+ }];
1378
+ }
1379
+ const psbtOutputData = psbtGenerate.txOutputs.map(output => {
1380
+ let address = '';
1381
+ try {
1382
+ address = output.address || bitcoin.address.fromOutputScript(output.script, network_);
1383
+ } catch (e) {
1384
+ if (output.script.includes(bitcoin.opcodes.OP_RETURN)) {
1385
+ address = 'OP_RETURN';
1386
+ } else {
1387
+ address = 'Unknown';
1388
+ }
1389
+ }
1390
+ if (isExistedInput(psbtInputData, address) === -1) {
1391
+ to = address;
1392
+ value = value.plus(new _bignumber.default(output.value));
1393
+ }
1394
+ return {
1395
+ address,
1396
+ amount: output.value.toString()
1397
+ };
1398
+ });
1399
+ payloadAfterValidated.payload = {
1400
+ ...payloadAfterValidated.payload,
1401
+ psbt,
1402
+ tokenSlug: tokenInfo.slug,
1403
+ value: value.toString(),
1404
+ to,
1405
+ txInput: psbtInputData,
1406
+ txOutput: psbtOutputData
1407
+ };
1408
+ return this.requestService.addConfirmationBitcoin(id, url, 'bitcoinSignPsbtRequest', payloadAfterValidated, {}).then(_ref12 => {
1409
+ let {
1410
+ isApproved,
1411
+ payload
1412
+ } = _ref12;
1413
+ if (isApproved) {
1414
+ if (payload) {
1415
+ return payload;
1416
+ } else {
1417
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INVALID_PARAMS, (0, _i18next.t)('Not found signature'));
1418
+ }
1419
+ } else {
1420
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.USER_REJECTED_REQUEST);
1421
+ }
1422
+ });
1423
+ }
1424
+ async bitcoinSendTransaction(id, url, transactionParams) {
1425
+ const payloadValidation = {
1426
+ address: transactionParams.account,
1427
+ type: 'bitcoin',
1428
+ payloadAfterValidated: transactionParams,
1429
+ errors: [],
1430
+ networkKey: transactionParams.network === 'mainnet' ? 'bitcoin' : 'bitcoinTestnet'
1431
+ };
1432
+ const validationSteps = [_logicValidation.validationAuthMiddleware, _logicValidation.validationBitcoinConnectMiddleware, _logicValidation.validationBitcoinSendTransactionMiddleware];
1433
+ const result = await (0, _logicValidation.generateValidationProcess)(this, url, payloadValidation, validationSteps);
1434
+ const errorsFormated = (0, _logicValidation.convertErrorFormat)(result.errors);
1435
+ const requestPayload = {
1436
+ ...result.payloadAfterValidated,
1437
+ hashPayload: JSON.stringify(result.payloadAfterValidated),
1438
+ from: transactionParams.account,
1439
+ id,
1440
+ errors: errorsFormated
1441
+ };
1442
+
1443
+ // Custom handle this instead of general handler transaction
1444
+ return this.requestService.addConfirmationBitcoin(id, url, 'bitcoinSendTransactionRequestAfterConfirmation', requestPayload, {}).then(_ref13 => {
1445
+ let {
1446
+ isApproved,
1447
+ payload
1448
+ } = _ref13;
1449
+ if (isApproved) {
1450
+ if (payload) {
1451
+ return payload;
1452
+ } else {
1453
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INVALID_PARAMS, (0, _i18next.t)('Not found signature'));
1454
+ }
1455
+ } else {
1456
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.USER_REJECTED_REQUEST);
1457
+ }
1458
+ });
1459
+ }
1263
1460
  getConfirmationsQueueSubject() {
1264
1461
  return this.requestService.confirmationsQueueSubject;
1265
1462
  }
@@ -1269,6 +1466,9 @@ class KoniState {
1269
1466
  getConfirmationsQueueSubjectCardano() {
1270
1467
  return this.requestService.confirmationsQueueSubjectCardano;
1271
1468
  }
1469
+ getConfirmationsQueueSubjectBitcoin() {
1470
+ return this.requestService.confirmationsQueueSubjectBitcoin;
1471
+ }
1272
1472
  async completeConfirmation(request) {
1273
1473
  return await this.requestService.completeConfirmation(request);
1274
1474
  }
@@ -1278,6 +1478,9 @@ class KoniState {
1278
1478
  async completeConfirmationCardano(request) {
1279
1479
  return await this.requestService.completeConfirmationCardano(request);
1280
1480
  }
1481
+ async completeConfirmationBitcoin(request) {
1482
+ return await this.requestService.completeConfirmationBitcoin(request);
1483
+ }
1281
1484
  async onMV3Update() {
1282
1485
  const migrationStatus = await _storage.SWStorage.instance.getItem('mv3_migration');
1283
1486
  if (!migrationStatus || migrationStatus !== 'done') {
@@ -1348,11 +1551,11 @@ class KoniState {
1348
1551
  const subscription = this.keyringService.context.observable.currentAccount.subscribe(handleRemind);
1349
1552
  }
1350
1553
  }
1351
- async setStorageFromWS(_ref9) {
1554
+ async setStorageFromWS(_ref14) {
1352
1555
  let {
1353
1556
  key,
1354
1557
  value
1355
- } = _ref9;
1558
+ } = _ref14;
1356
1559
  try {
1357
1560
  const jsonData = JSON.stringify(value);
1358
1561
  await _storage.SWStorage.instance.setItem(key, jsonData);
@@ -1429,8 +1632,12 @@ class KoniState {
1429
1632
  });
1430
1633
  }
1431
1634
  async sleep() {
1635
+ // Wait for app initialized before sleep
1636
+ await this.eventService.waitAppInitialized;
1637
+
1432
1638
  // Wait starting finish before sleep to avoid conflict
1433
1639
  this.generalStatus === _types.ServiceStatus.STARTING && this.waitStarting && (await this.waitStarting);
1640
+ this.generalStatus === _types.ServiceStatus.STARTING_FULL && this.waitStartingFull && (await this.waitStartingFull);
1434
1641
  this.eventService.emit('general.sleep', true);
1435
1642
 
1436
1643
  // Avoid sleep multiple times
@@ -1459,6 +1666,9 @@ class KoniState {
1459
1666
  this.waitSleeping = null;
1460
1667
  }
1461
1668
  async _start() {
1669
+ // Wait for app initialized before start
1670
+ await this.eventService.waitAppInitialized;
1671
+
1462
1672
  // Wait sleep finish before start to avoid conflict
1463
1673
  this.generalStatus === _types.ServiceStatus.STOPPING && this.waitSleeping && (await this.waitSleeping);
1464
1674
 
@@ -1484,15 +1694,38 @@ class KoniState {
1484
1694
  }
1485
1695
 
1486
1696
  // Start services
1487
- await Promise.all([this.cron.start(), this.subscription.start(), this.historyService.start(), this.priceService.start(), this.balanceService.start(), this.earningService.start(), this.swapService.start(), this.inappNotificationService.start()]);
1697
+ this.eventService.emit('general.start', true);
1488
1698
 
1489
1699
  // Complete starting
1490
- starting.resolve();
1491
1700
  this.waitStarting = null;
1492
1701
  this.generalStatus = _types.ServiceStatus.STARTED;
1702
+ starting.resolve();
1703
+ }
1704
+ async _startFull() {
1705
+ // Continue wait existed starting process
1706
+ if (this.generalStatus === _types.ServiceStatus.STARTING) {
1707
+ await this.waitStarting;
1708
+ }
1709
+
1710
+ // Always start full from start state
1711
+ if (this.generalStatus !== _types.ServiceStatus.STARTED) {
1712
+ return;
1713
+ }
1714
+ this.generalStatus = _types.ServiceStatus.STARTING_FULL;
1715
+ const startingFull = (0, _promise.createPromiseHandler)();
1716
+ this.waitStartingFull = startingFull.promise;
1717
+ await Promise.all([this.cron.start(), this.subscription.start(), this.historyService.start(), this.priceService.start(), this.balanceService.start(), this.earningService.start(), this.swapService.start(), this.inappNotificationService.start()]);
1718
+ this.eventService.emit('general.start_full', true);
1719
+ this.waitStartingFull = null;
1720
+ this.generalStatus = _types.ServiceStatus.STARTED_FULL;
1721
+ startingFull.resolve();
1493
1722
  }
1494
1723
  async wakeup() {
1724
+ let fullWakeup = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
1495
1725
  await this._start();
1726
+ if (fullWakeup) {
1727
+ await this._startFull();
1728
+ }
1496
1729
  }
1497
1730
  cancelSubscription(id) {
1498
1731
  if ((0, _subscriptions.isSubscriptionRunning)(id)) {
@@ -1780,12 +2013,12 @@ class KoniState {
1780
2013
 
1781
2014
  /* Metadata */
1782
2015
 
1783
- getCrowdloanContributions(_ref10) {
2016
+ getCrowdloanContributions(_ref15) {
1784
2017
  let {
1785
2018
  address,
1786
2019
  page,
1787
2020
  relayChain
1788
- } = _ref10;
2021
+ } = _ref15;
1789
2022
  return this.subscanService.getCrowdloanContributions(relayChain, address, page);
1790
2023
  }
1791
2024
  }
@@ -7,6 +7,7 @@ Object.defineProperty(exports, "__esModule", {
7
7
  exports.default = exports.chainPatrolCheckUrl = void 0;
8
8
  var CardanoWasm = _interopRequireWildcard(require("@emurgo/cardano-serialization-lib-nodejs"));
9
9
  var _types = require("@subwallet/chain-list/types");
10
+ var _BitcoinProviderError = require("@subwallet/extension-base/background/errors/BitcoinProviderError");
10
11
  var _CardanoProviderError = require("@subwallet/extension-base/background/errors/CardanoProviderError");
11
12
  var _EvmProviderError = require("@subwallet/extension-base/background/errors/EvmProviderError");
12
13
  var _helpers = require("@subwallet/extension-base/background/handlers/helpers");
@@ -23,6 +24,7 @@ var _helper = require("@subwallet/extension-base/services/request-service/helper
23
24
  var _constants2 = require("@subwallet/extension-base/services/setting-service/constants");
24
25
  var _utils2 = require("@subwallet/extension-base/utils");
25
26
  var _types3 = require("@subwallet/keyring/types");
27
+ var _utils3 = require("@subwallet/keyring/utils");
26
28
  var _uiKeyring = require("@subwallet/ui-keyring");
27
29
  var _web = _interopRequireDefault(require("web3"));
28
30
  var _phishing = require("@polkadot/phishing");
@@ -51,7 +53,8 @@ function transformAccountsV2(accounts) {
51
53
  evm: _types3.EthereumKeypairTypes,
52
54
  substrate: _types3.SubstrateKeypairTypes,
53
55
  ton: _types3.TonKeypairTypes,
54
- cardano: _types3.CardanoKeypairTypes
56
+ cardano: _types3.CardanoKeypairTypes,
57
+ bitcoin: _types3.BitcoinKeypairTypes
55
58
  };
56
59
  const isValidTypes = accountAuthTypes.some(authType => {
57
60
  var _validTypes$authType;
@@ -952,10 +955,6 @@ class KoniTabs {
952
955
  });
953
956
  });
954
957
  }
955
- async canUseAccount(address, url) {
956
- const allowedAccounts = await this.getCurrentAccount(url, 'evm');
957
- return !!allowedAccounts.find(acc => acc.toLowerCase() === address.toLowerCase());
958
- }
959
958
  async evmSign(id, url, _ref19) {
960
959
  let {
961
960
  method,
@@ -1320,6 +1319,116 @@ class KoniTabs {
1320
1319
  throw new _CardanoProviderError.CardanoProviderError(_KoniTypes.CardanoProviderErrorType.INTERNAL_ERROR, 'Failed to submit transaction');
1321
1320
  }
1322
1321
  }
1322
+
1323
+ /// Bitcoin
1324
+
1325
+ isBitcoinPublicRequest(type, request) {
1326
+ return type === 'bitcoin(request)' && ['getAddresses'].includes(request === null || request === void 0 ? void 0 : request.method);
1327
+ }
1328
+ async bitcoinGetAddresses(url) {
1329
+ try {
1330
+ const isCompleted = await this.#koniState.authorizeUrlV2(url, {
1331
+ origin: url,
1332
+ accountAuthTypes: ['bitcoin']
1333
+ });
1334
+ const result = [];
1335
+ if (!isCompleted) {
1336
+ return result;
1337
+ }
1338
+ const authInfo = await this.getAuthInfo(url);
1339
+ if (!authInfo || !authInfo.isAllowedMap || !authInfo.isAllowed) {
1340
+ return result;
1341
+ }
1342
+ const addressesAllowed = await this.getCurrentAccount(url, 'bitcoin');
1343
+ const addressResults = [];
1344
+ addressesAllowed.forEach(address => {
1345
+ const pair = _uiKeyring.keyring.getPair(address);
1346
+ if (pair.meta.noPublicKey) {
1347
+ return;
1348
+ }
1349
+ const addressInfo = (0, _utils3.getBitcoinAddressInfo)(address);
1350
+ const item = {
1351
+ address,
1352
+ type: addressInfo.type,
1353
+ isTestnet: addressInfo.network === 'testnet'
1354
+ };
1355
+ item.derivationPath = pair.meta.derivationPath;
1356
+ item.publicKey = (0, _util.hexStripPrefix)((0, _util.u8aToHex)(pair.publicKey));
1357
+ if (pair.publicKey.length !== 32) {
1358
+ item.tweakedPublicKey = (0, _util.hexStripPrefix)((0, _util.u8aToHex)(pair.publicKey.slice(1, 33)));
1359
+ }
1360
+ addressResults.push(item);
1361
+ });
1362
+ return addressResults;
1363
+ } catch (e) {
1364
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.USER_REJECTED_REQUEST);
1365
+ }
1366
+ }
1367
+ async bitcoinSign(id, url, _ref22) {
1368
+ let {
1369
+ method,
1370
+ params
1371
+ } = _ref22;
1372
+ const signResult = await this.#koniState.bitcoinSign(id, url, method, params);
1373
+ if (signResult) {
1374
+ return signResult;
1375
+ } else {
1376
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INVALID_PARAMS, 'Failed to sign message');
1377
+ }
1378
+ }
1379
+ async bitcoinSignPspt(id, url, _ref23) {
1380
+ let {
1381
+ method,
1382
+ params
1383
+ } = _ref23;
1384
+ const psbtParams = params;
1385
+ const signResult = await this.#koniState.bitcoinSignPspt(id, url, psbtParams);
1386
+ if (signResult) {
1387
+ return signResult;
1388
+ } else {
1389
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INVALID_PARAMS, 'Failed to sign message');
1390
+ }
1391
+ }
1392
+ async bitcoinSendTransfer(id, url, _ref24) {
1393
+ let {
1394
+ params
1395
+ } = _ref24;
1396
+ const transactionParams = params;
1397
+ const transactionHash = await this.#koniState.bitcoinSendTransaction(id, url, transactionParams);
1398
+ if (!transactionHash) {
1399
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.USER_REJECTED_REQUEST);
1400
+ }
1401
+ return {
1402
+ txid: transactionHash
1403
+ };
1404
+ }
1405
+ async handleBitcoinRequest(id, url, request, port) {
1406
+ const {
1407
+ method
1408
+ } = request;
1409
+ try {
1410
+ switch (method) {
1411
+ case 'getAddresses':
1412
+ return await this.bitcoinGetAddresses(url);
1413
+ case 'signMessage':
1414
+ return await this.bitcoinSign(id, url, request);
1415
+ case 'signPsbt':
1416
+ return await this.bitcoinSignPspt(id, url, request);
1417
+ case 'sendTransfer':
1418
+ return await this.bitcoinSendTransfer(id, url, request);
1419
+ default:
1420
+ throw new Error(`Method ${method} is not supported by SubWalletBitcoin provider`);
1421
+ }
1422
+ } catch (e) {
1423
+ // @ts-ignore
1424
+ if (e.code) {
1425
+ throw e;
1426
+ } else {
1427
+ console.error(e);
1428
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INTERNAL_ERROR, e === null || e === void 0 ? void 0 : e.toString());
1429
+ }
1430
+ }
1431
+ }
1323
1432
  async handle(id, type, request, url, port) {
1324
1433
  if (type === 'pub(phishing.redirectIfDenied)') {
1325
1434
  return this.redirectIfPhishing(url);
@@ -1330,7 +1439,7 @@ class KoniTabs {
1330
1439
 
1331
1440
  // Wait for account ready and chain ready
1332
1441
  await Promise.all([this.#koniState.eventService.waitAccountReady, this.#koniState.eventService.waitChainReady]);
1333
- if (!['pub(authorize.tabV2)', 'pub(accounts.subscribeV2)'].includes(type) && !this.isEvmPublicRequest(type, request)) {
1442
+ if (!['pub(authorize.tabV2)', 'pub(accounts.subscribeV2)'].includes(type) && !this.isEvmPublicRequest(type, request) && !this.isBitcoinPublicRequest(type, request)) {
1334
1443
  await this.#koniState.ensureUrlAuthorizedV2(url).catch(e => {
1335
1444
  if (type.startsWith('evm')) {
1336
1445
  throw new _EvmProviderError.EvmProviderError(_KoniTypes.EvmProviderErrorType.INTERNAL_ERROR, e.message);
@@ -1401,6 +1510,10 @@ class KoniTabs {
1401
1510
  return await this.cardanoSignTransaction(id, url, request);
1402
1511
  case 'cardano(transaction.submit)':
1403
1512
  return await this.cardanoSubmitTransaction(id, url, request);
1513
+
1514
+ // Bitcoin
1515
+ case 'bitcoin(request)':
1516
+ return await this.handleBitcoinRequest(id, url, request, port);
1404
1517
  default:
1405
1518
  throw new Error(`Unable to handle message of type ${type}`);
1406
1519
  }
@@ -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.41-0'
16
+ version: '1.3.43-0'
17
17
  };
18
18
  exports.packageInfo = packageInfo;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ // Copyright 2019-2022 @subwallet/extension authors & contributors
8
+ // SPDX-License-Identifier: Apache-2.0
9
+
10
+ const WALLET_NAME = 'SubWallet';
11
+ const WALLET_VERSION = process.env.PKG_VERSION;
12
+ class SubWalletBitcoinProvider {
13
+ name = WALLET_NAME;
14
+ version = WALLET_VERSION;
15
+ isSubWallet = true;
16
+ constructor(sendMessage) {
17
+ this.sendMessage = sendMessage;
18
+ }
19
+ async requestAccounts() {
20
+ return await this.request('getAccounts');
21
+ }
22
+ async getAccounts() {
23
+ return await this.request('getAccounts');
24
+ }
25
+ async signMessage(params) {
26
+ return await this.request('signMessage', params);
27
+ }
28
+ async signPsbt(params) {
29
+ return await this.request('signPsbt', params);
30
+ }
31
+ async sendTransfer(params) {
32
+ return await this.request('sendTransfer', params);
33
+ }
34
+ request(method, params) {
35
+ // Implement this method
36
+ return new Promise((resolve, reject) => {
37
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
38
+ this.sendMessage('bitcoin(request)', {
39
+ method,
40
+ params
41
+ }).then(result => {
42
+ resolve(result);
43
+ }).catch(e => {
44
+ reject(e);
45
+ });
46
+ });
47
+ }
48
+ getProductInfo() {
49
+ return {
50
+ name: this.name,
51
+ version: this.version
52
+ };
53
+ }
54
+ get apis() {
55
+ return {
56
+ isSubWallet: this.isSubWallet,
57
+ request: (method, params) => this.request(method, params),
58
+ getAccounts: () => this.getAccounts(),
59
+ signMessage: params => this.signMessage(params),
60
+ signPsbt: params => this.signPsbt(params),
61
+ sendTransfer: params => this.sendTransfer(params),
62
+ requestAccounts: () => this.requestAccounts(),
63
+ getProductInfo: () => this.getProductInfo()
64
+ };
65
+ }
66
+ }
67
+ exports.default = SubWalletBitcoinProvider;
package/cjs/page/index.js CHANGED
@@ -6,11 +6,13 @@ Object.defineProperty(exports, "__esModule", {
6
6
  });
7
7
  exports.enable = enable;
8
8
  exports.handleResponse = handleResponse;
9
+ exports.initBitcoinProvider = initBitcoinProvider;
9
10
  exports.initCardanoProvider = initCardanoProvider;
10
11
  exports.initEvmProvider = initEvmProvider;
11
12
  exports.sendMessage = sendMessage;
12
13
  var _ProviderError = require("@subwallet/extension-base/background/errors/ProviderError");
13
14
  var _KoniTypes = require("@subwallet/extension-base/background/KoniTypes");
15
+ var _bitcoin = _interopRequireDefault(require("@subwallet/extension-base/page/bitcoin"));
14
16
  var _cardano = _interopRequireDefault(require("@subwallet/extension-base/page/cardano"));
15
17
  var _evm = _interopRequireDefault(require("@subwallet/extension-base/page/evm"));
16
18
  var _substrate = _interopRequireDefault(require("@subwallet/extension-base/page/substrate"));
@@ -76,4 +78,7 @@ function initEvmProvider(version) {
76
78
  }
77
79
  function initCardanoProvider() {
78
80
  return new _cardano.default(sendMessage);
81
+ }
82
+ function initBitcoinProvider() {
83
+ return new _bitcoin.default(sendMessage).apis;
79
84
  }