@subwallet/extension-base 1.3.40-0 → 1.3.42-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 (232) hide show
  1. package/background/KoniTypes.d.ts +121 -4
  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/cjs/background/KoniTypes.js +20 -1
  6. package/cjs/background/errors/BitcoinProviderError.js +54 -0
  7. package/cjs/constants/bitcoin.js +22 -0
  8. package/cjs/constants/environment.js +4 -2
  9. package/cjs/constants/index.js +16 -1
  10. package/cjs/core/logic-validation/recipientAddress.js +9 -0
  11. package/cjs/core/logic-validation/transfer.js +25 -5
  12. package/cjs/core/types.js +1 -0
  13. package/cjs/core/utils.js +15 -1
  14. package/cjs/koni/background/handlers/Extension.js +96 -41
  15. package/cjs/koni/background/handlers/State.js +52 -11
  16. package/cjs/packageInfo.js +1 -1
  17. package/cjs/services/balance-service/helpers/subscribe/bitcoin.js +94 -0
  18. package/cjs/services/balance-service/helpers/subscribe/evm.js +6 -1
  19. package/cjs/services/balance-service/helpers/subscribe/index.js +19 -7
  20. package/cjs/services/balance-service/index.js +32 -4
  21. package/cjs/services/balance-service/transfer/bitcoin-transfer.js +119 -0
  22. package/cjs/services/balance-service/transfer/token.js +2 -0
  23. package/cjs/services/balance-service/transfer/xcm/index.js +15 -9
  24. package/cjs/services/balance-service/transfer/xcm/utils.js +12 -14
  25. package/cjs/services/base/types.js +2 -0
  26. package/cjs/services/chain-service/constants.js +18 -6
  27. package/cjs/services/chain-service/handler/CardanoApi.js +25 -35
  28. package/cjs/services/chain-service/handler/bitcoin/BitcoinApi.js +105 -0
  29. package/cjs/services/chain-service/handler/bitcoin/BitcoinChainHandler.js +78 -0
  30. package/cjs/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/blockstream-testnet-strategy.js +371 -0
  31. package/cjs/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/index.js +19 -0
  32. package/cjs/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/mempool-testnet-strategy.js +368 -0
  33. package/cjs/services/chain-service/handler/bitcoin/strategy/SubWalletMainnet/index.js +302 -0
  34. package/cjs/services/chain-service/handler/bitcoin/strategy/types.js +1 -0
  35. package/cjs/services/chain-service/index.js +27 -3
  36. package/cjs/services/chain-service/utils/index.js +57 -4
  37. package/cjs/services/chain-service/utils/patch.js +1 -1
  38. package/cjs/services/earning-service/handlers/native-staking/tao.js +4 -38
  39. package/cjs/services/event-service/index.js +4 -0
  40. package/cjs/services/fee-service/service.js +8 -3
  41. package/cjs/services/hiro-service/index.js +96 -0
  42. package/cjs/services/hiro-service/utils/index.js +85 -0
  43. package/cjs/services/history-service/bitcoin-history.js +58 -0
  44. package/cjs/services/history-service/helpers/recoverHistoryStatus.js +96 -4
  45. package/cjs/services/history-service/index.js +41 -3
  46. package/cjs/services/keyring-service/context/handlers/Derive.js +1 -1
  47. package/cjs/services/keyring-service/context/handlers/Migration.js +2 -2
  48. package/cjs/services/keyring-service/context/handlers/Mnemonic.js +4 -3
  49. package/cjs/services/migration-service/scripts/MigrateNewUnifiedAccount.js +29 -0
  50. package/cjs/services/migration-service/scripts/index.js +3 -1
  51. package/cjs/services/request-service/handler/BitcoinRequestHandler.js +440 -0
  52. package/cjs/services/request-service/index.js +29 -3
  53. package/cjs/services/rune-service/index.js +105 -0
  54. package/cjs/services/swap-service/handler/chainflip-handler.js +29 -18
  55. package/cjs/services/swap-service/handler/kyber-handler.js +5 -9
  56. package/cjs/services/swap-service/handler/simpleswap-handler.js +4 -7
  57. package/cjs/services/swap-service/handler/uniswap-handler.js +5 -12
  58. package/cjs/services/swap-service/utils.js +46 -37
  59. package/cjs/services/transaction-service/helpers/index.js +7 -1
  60. package/cjs/services/transaction-service/index.js +136 -15
  61. package/cjs/services/transaction-service/utils.js +6 -3
  62. package/cjs/strategy/api-request-strategy/context/base.js +31 -0
  63. package/cjs/strategy/api-request-strategy/index.js +90 -0
  64. package/cjs/strategy/api-request-strategy/types.js +1 -0
  65. package/cjs/strategy/api-request-strategy/utils/index.js +33 -0
  66. package/cjs/types/account/info/keyring.js +1 -1
  67. package/cjs/types/bitcoin.js +24 -0
  68. package/cjs/types/environment.js +19 -0
  69. package/cjs/types/fee/bitcoin.js +1 -0
  70. package/cjs/types/fee/index.js +11 -0
  71. package/cjs/types/index.js +11 -0
  72. package/cjs/utils/account/analyze.js +3 -3
  73. package/cjs/utils/account/common.js +16 -6
  74. package/cjs/utils/account/derive/info/solo.js +68 -19
  75. package/cjs/utils/account/derive/info/unified.js +2 -0
  76. package/cjs/utils/account/derive/validate.js +70 -2
  77. package/cjs/utils/account/transform.js +11 -5
  78. package/cjs/utils/bitcoin/common.js +98 -0
  79. package/cjs/utils/bitcoin/fee.js +21 -0
  80. package/cjs/utils/bitcoin/index.js +38 -0
  81. package/cjs/utils/bitcoin/utxo-management.js +281 -0
  82. package/cjs/utils/environment.js +30 -2
  83. package/cjs/utils/fee/transfer.js +48 -0
  84. package/cjs/utils/index.js +15 -1
  85. package/constants/bitcoin.d.ts +3 -0
  86. package/constants/bitcoin.js +13 -0
  87. package/constants/environment.d.ts +1 -0
  88. package/constants/environment.js +2 -1
  89. package/constants/index.d.ts +2 -0
  90. package/constants/index.js +3 -1
  91. package/core/logic-validation/recipientAddress.js +10 -1
  92. package/core/logic-validation/transfer.d.ts +2 -2
  93. package/core/logic-validation/transfer.js +27 -7
  94. package/core/types.d.ts +1 -0
  95. package/core/types.js +1 -0
  96. package/core/utils.d.ts +1 -0
  97. package/core/utils.js +15 -2
  98. package/koni/background/handlers/Extension.d.ts +2 -0
  99. package/koni/background/handlers/Extension.js +95 -42
  100. package/koni/background/handlers/State.d.ts +7 -3
  101. package/koni/background/handlers/State.js +52 -12
  102. package/package.json +149 -8
  103. package/packageInfo.js +1 -1
  104. package/services/balance-service/helpers/subscribe/bitcoin.d.ts +2 -0
  105. package/services/balance-service/helpers/subscribe/bitcoin.js +87 -0
  106. package/services/balance-service/helpers/subscribe/evm.js +6 -1
  107. package/services/balance-service/helpers/subscribe/index.d.ts +2 -2
  108. package/services/balance-service/helpers/subscribe/index.js +20 -8
  109. package/services/balance-service/index.d.ts +2 -0
  110. package/services/balance-service/index.js +32 -4
  111. package/services/balance-service/transfer/bitcoin-transfer.d.ts +14 -0
  112. package/services/balance-service/transfer/bitcoin-transfer.js +112 -0
  113. package/services/balance-service/transfer/token.js +2 -0
  114. package/services/balance-service/transfer/xcm/index.js +15 -9
  115. package/services/balance-service/transfer/xcm/utils.d.ts +2 -0
  116. package/services/balance-service/transfer/xcm/utils.js +12 -14
  117. package/services/base/types.d.ts +2 -0
  118. package/services/base/types.js +2 -0
  119. package/services/chain-service/constants.d.ts +7 -0
  120. package/services/chain-service/constants.js +12 -5
  121. package/services/chain-service/handler/CardanoApi.d.ts +1 -5
  122. package/services/chain-service/handler/CardanoApi.js +26 -34
  123. package/services/chain-service/handler/bitcoin/BitcoinApi.d.ts +31 -0
  124. package/services/chain-service/handler/bitcoin/BitcoinApi.js +98 -0
  125. package/services/chain-service/handler/bitcoin/BitcoinChainHandler.d.ts +16 -0
  126. package/services/chain-service/handler/bitcoin/BitcoinChainHandler.js +70 -0
  127. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/blockstream-testnet-strategy.d.ts +28 -0
  128. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/blockstream-testnet-strategy.js +362 -0
  129. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/index.d.ts +2 -0
  130. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/index.js +5 -0
  131. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/mempool-testnet-strategy.d.ts +28 -0
  132. package/services/chain-service/handler/bitcoin/strategy/BlockStreamTestnet/mempool-testnet-strategy.js +359 -0
  133. package/services/chain-service/handler/bitcoin/strategy/SubWalletMainnet/index.d.ts +28 -0
  134. package/services/chain-service/handler/bitcoin/strategy/SubWalletMainnet/index.js +293 -0
  135. package/services/chain-service/handler/bitcoin/strategy/types.d.ts +291 -0
  136. package/services/chain-service/handler/bitcoin/strategy/types.js +1 -0
  137. package/services/chain-service/index.d.ts +3 -0
  138. package/services/chain-service/index.js +31 -5
  139. package/services/chain-service/types.d.ts +20 -0
  140. package/services/chain-service/utils/index.d.ts +4 -0
  141. package/services/chain-service/utils/index.js +50 -4
  142. package/services/chain-service/utils/patch.js +1 -1
  143. package/services/earning-service/handlers/native-staking/tao.d.ts +0 -11
  144. package/services/earning-service/handlers/native-staking/tao.js +4 -24
  145. package/services/event-service/index.d.ts +3 -0
  146. package/services/event-service/index.js +4 -0
  147. package/services/event-service/types.d.ts +3 -0
  148. package/services/fee-service/service.js +8 -3
  149. package/services/hiro-service/index.d.ts +17 -0
  150. package/services/hiro-service/index.js +88 -0
  151. package/services/hiro-service/utils/index.d.ts +6 -0
  152. package/services/hiro-service/utils/index.js +72 -0
  153. package/services/history-service/bitcoin-history.d.ts +4 -0
  154. package/services/history-service/bitcoin-history.js +52 -0
  155. package/services/history-service/helpers/recoverHistoryStatus.d.ts +3 -1
  156. package/services/history-service/helpers/recoverHistoryStatus.js +96 -4
  157. package/services/history-service/index.d.ts +1 -0
  158. package/services/history-service/index.js +42 -4
  159. package/services/keyring-service/context/handlers/Derive.js +2 -2
  160. package/services/keyring-service/context/handlers/Migration.js +2 -2
  161. package/services/keyring-service/context/handlers/Mnemonic.js +4 -3
  162. package/services/migration-service/scripts/MigrateNewUnifiedAccount.d.ts +4 -0
  163. package/services/migration-service/scripts/MigrateNewUnifiedAccount.js +21 -0
  164. package/services/migration-service/scripts/index.js +3 -1
  165. package/services/request-service/handler/BitcoinRequestHandler.d.ts +23 -0
  166. package/services/request-service/handler/BitcoinRequestHandler.js +427 -0
  167. package/services/request-service/index.d.ts +9 -2
  168. package/services/request-service/index.js +25 -3
  169. package/services/rune-service/index.d.ts +17 -0
  170. package/services/rune-service/index.js +97 -0
  171. package/services/swap-service/handler/chainflip-handler.d.ts +0 -2
  172. package/services/swap-service/handler/chainflip-handler.js +25 -13
  173. package/services/swap-service/handler/kyber-handler.d.ts +0 -1
  174. package/services/swap-service/handler/kyber-handler.js +5 -8
  175. package/services/swap-service/handler/simpleswap-handler.d.ts +0 -1
  176. package/services/swap-service/handler/simpleswap-handler.js +4 -6
  177. package/services/swap-service/handler/uniswap-handler.js +6 -13
  178. package/services/swap-service/utils.d.ts +0 -13
  179. package/services/swap-service/utils.js +46 -34
  180. package/services/transaction-service/helpers/index.d.ts +3 -1
  181. package/services/transaction-service/helpers/index.js +5 -0
  182. package/services/transaction-service/index.d.ts +3 -5
  183. package/services/transaction-service/index.js +135 -16
  184. package/services/transaction-service/types.d.ts +12 -2
  185. package/services/transaction-service/utils.js +7 -4
  186. package/strategy/api-request-strategy/context/base.d.ts +15 -0
  187. package/strategy/api-request-strategy/context/base.js +24 -0
  188. package/strategy/api-request-strategy/index.d.ts +15 -0
  189. package/strategy/api-request-strategy/index.js +83 -0
  190. package/strategy/api-request-strategy/types.d.ts +22 -0
  191. package/strategy/api-request-strategy/types.js +1 -0
  192. package/strategy/api-request-strategy/utils/index.d.ts +2 -0
  193. package/strategy/api-request-strategy/utils/index.js +23 -0
  194. package/types/account/info/keyring.d.ts +1 -1
  195. package/types/account/info/keyring.js +1 -1
  196. package/types/balance/index.d.ts +4 -1
  197. package/types/balance/transfer.d.ts +17 -0
  198. package/types/bitcoin.d.ts +93 -0
  199. package/types/bitcoin.js +17 -0
  200. package/types/environment.d.ts +9 -0
  201. package/types/environment.js +13 -0
  202. package/types/fee/base.d.ts +4 -1
  203. package/types/fee/bitcoin.d.ts +18 -0
  204. package/types/fee/bitcoin.js +1 -0
  205. package/types/fee/index.d.ts +1 -0
  206. package/types/fee/index.js +2 -1
  207. package/types/fee/subscription.d.ts +4 -3
  208. package/types/index.d.ts +1 -0
  209. package/types/index.js +1 -0
  210. package/utils/account/analyze.js +4 -4
  211. package/utils/account/common.d.ts +7 -8
  212. package/utils/account/common.js +16 -6
  213. package/utils/account/derive/info/solo.js +70 -21
  214. package/utils/account/derive/info/unified.js +2 -0
  215. package/utils/account/derive/validate.d.ts +1 -0
  216. package/utils/account/derive/validate.js +68 -1
  217. package/utils/account/transform.d.ts +1 -1
  218. package/utils/account/transform.js +11 -5
  219. package/utils/bitcoin/common.d.ts +22 -0
  220. package/utils/bitcoin/common.js +88 -0
  221. package/utils/bitcoin/fee.d.ts +2 -0
  222. package/utils/bitcoin/fee.js +14 -0
  223. package/utils/bitcoin/index.d.ts +3 -0
  224. package/utils/bitcoin/index.js +6 -0
  225. package/utils/bitcoin/utxo-management.d.ts +33 -0
  226. package/utils/bitcoin/utxo-management.js +266 -0
  227. package/utils/environment.d.ts +2 -0
  228. package/utils/environment.js +27 -1
  229. package/utils/fee/transfer.d.ts +3 -1
  230. package/utils/fee/transfer.js +47 -1
  231. package/utils/index.d.ts +1 -0
  232. package/utils/index.js +6 -3
@@ -0,0 +1,440 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = void 0;
8
+ var _BitcoinProviderError = require("@subwallet/extension-base/background/errors/BitcoinProviderError");
9
+ var _TransactionError = require("@subwallet/extension-base/background/errors/TransactionError");
10
+ var _KoniTypes = require("@subwallet/extension-base/background/KoniTypes");
11
+ var _bitcoinTransfer = require("@subwallet/extension-base/services/balance-service/transfer/bitcoin-transfer");
12
+ var _types = require("@subwallet/extension-base/types");
13
+ var _utils = require("@subwallet/extension-base/utils");
14
+ var _getId = require("@subwallet/extension-base/utils/getId");
15
+ var _request = require("@subwallet/extension-base/utils/request");
16
+ var _uiKeyring = _interopRequireDefault(require("@subwallet/ui-keyring"));
17
+ var bitcoin = _interopRequireWildcard(require("bitcoinjs-lib"));
18
+ var _i18next = require("i18next");
19
+ var _rxjs = require("rxjs");
20
+ var _util = require("@polkadot/util");
21
+ 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); }
22
+ 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; }
23
+ // Copyright 2019-2022 @subwallet/extension-base authors & contributors
24
+ // SPDX-License-Identifier: Apache-2.0
25
+
26
+ class BitcoinRequestHandler {
27
+ #requestService;
28
+ #chainService;
29
+ #transactionService;
30
+ #feeService;
31
+ #logger;
32
+ confirmationsQueueSubjectBitcoin = new _rxjs.BehaviorSubject({
33
+ bitcoinSignatureRequest: {},
34
+ bitcoinSendTransactionRequest: {},
35
+ bitcoinWatchTransactionRequest: {},
36
+ bitcoinSendTransactionRequestAfterConfirmation: {},
37
+ bitcoinSignPsbtRequest: {}
38
+ });
39
+ confirmationsPromiseMap = {};
40
+ constructor(requestService, chainService, feeService, transactionService) {
41
+ this.#requestService = requestService;
42
+ this.#chainService = chainService;
43
+ this.#feeService = feeService;
44
+ this.#transactionService = transactionService;
45
+ this.#logger = (0, _util.logger)('BitcoinRequestHandler');
46
+ }
47
+ get numBitcoinRequests() {
48
+ let count = 0;
49
+ Object.values(this.confirmationsQueueSubjectBitcoin.getValue()).forEach(x => {
50
+ count += Object.keys(x).length;
51
+ });
52
+ return count;
53
+ }
54
+ getConfirmationsQueueSubjectBitcoin() {
55
+ return this.confirmationsQueueSubjectBitcoin;
56
+ }
57
+ async addConfirmationBitcoin(id, url, type, payload) {
58
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
59
+ let validator = arguments.length > 5 ? arguments[5] : undefined;
60
+ const confirmations = this.confirmationsQueueSubjectBitcoin.getValue();
61
+ const confirmationType = confirmations[type];
62
+ const payloadJson = JSON.stringify(payload);
63
+ const isInternal = (0, _request.isInternalRequest)(url);
64
+ if (['bitcoinSignatureRequest', 'bitcoinSendTransactionRequest', 'bitcoinSendTransactionRequestAfterConfirmation'].includes(type)) {
65
+ const isAlwaysRequired = await this.#requestService.settingService.isAlwaysRequired;
66
+ if (isAlwaysRequired) {
67
+ this.#requestService.keyringService.lock();
68
+ }
69
+ }
70
+
71
+ // Check duplicate request
72
+ const duplicated = Object.values(confirmationType).find(c => c.url === url && c.payloadJson === payloadJson);
73
+ if (duplicated) {
74
+ throw new Error('Duplicate request');
75
+ }
76
+ confirmationType[id] = {
77
+ id,
78
+ url,
79
+ isInternal,
80
+ payload,
81
+ payloadJson,
82
+ ...options
83
+ };
84
+ const promise = new Promise((resolve, reject) => {
85
+ this.confirmationsPromiseMap[id] = {
86
+ validator: validator,
87
+ resolver: {
88
+ resolve: resolve,
89
+ reject: reject
90
+ }
91
+ };
92
+ });
93
+ this.confirmationsQueueSubjectBitcoin.next(confirmations);
94
+ if (!isInternal) {
95
+ this.#requestService.popupOpen();
96
+ }
97
+ this.#requestService.updateIconV2();
98
+ return promise;
99
+ }
100
+ updateConfirmationBitcoin(id, type, payload) {
101
+ let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
102
+ let validator = arguments.length > 4 ? arguments[4] : undefined;
103
+ const confirmations = this.confirmationsQueueSubjectBitcoin.getValue();
104
+ const confirmationType = confirmations[type];
105
+
106
+ // Check duplicate request
107
+ const exists = confirmationType[id];
108
+ if (!exists) {
109
+ throw new Error('Request does not exist');
110
+ }
111
+ const payloadJson = JSON.stringify(payload);
112
+ confirmationType[id] = {
113
+ ...exists,
114
+ payload,
115
+ payloadJson,
116
+ ...options
117
+ };
118
+ if (validator) {
119
+ this.confirmationsPromiseMap[id].validator = validator;
120
+ }
121
+ this.confirmationsQueueSubjectBitcoin.next(confirmations);
122
+ }
123
+ signMessageBitcoin(confirmation) {
124
+ const {
125
+ account,
126
+ payload
127
+ } = confirmation.payload;
128
+ const address = account.address;
129
+ const pair = _uiKeyring.default.getPair(address);
130
+ if (pair.isLocked) {
131
+ _uiKeyring.default.unlockPair(pair.address);
132
+ }
133
+
134
+ // Check if payload is a string
135
+ if (typeof payload === 'string') {
136
+ // Assume BitcoinSigner is an instance that implements the BitcoinSigner interface
137
+ return {
138
+ signature: pair.bitcoin.signMessage(payload),
139
+ message: payload,
140
+ address
141
+ }; // Assuming compressed = false
142
+ } else if (payload instanceof Uint8Array) {
143
+ // Check if payload is a byte array (Uint8Array)
144
+ // Convert Uint8Array to string
145
+ const payloadString = Buffer.from(payload).toString('hex');
146
+
147
+ // Assume BitcoinSigner is an instance that implements the BitcoinSigner interface
148
+ return {
149
+ signature: pair.bitcoin.signMessage(payloadString),
150
+ message: payload.toString(),
151
+ address
152
+ }; // Assuming compressed = false
153
+ } else {
154
+ // Handle the case where payload is invalid
155
+ throw new Error('Invalid payload type');
156
+ }
157
+ }
158
+ signTransactionBitcoin(request) {
159
+ // Extract necessary information from the BitcoinSendTransactionRequest
160
+ const {
161
+ account,
162
+ hashPayload
163
+ } = request.payload;
164
+ const address = account.address;
165
+ const pair = _uiKeyring.default.getPair(address);
166
+
167
+ // Unlock the pair if it is locked
168
+ if (pair.isLocked) {
169
+ _uiKeyring.default.unlockPair(pair.address);
170
+ }
171
+ const psbt = bitcoin.Psbt.fromHex(hashPayload);
172
+
173
+ // Finalize all inputs in the Psbt
174
+ // Sign the Psbt using the pair's bitcoin object
175
+ const signedTransaction = pair.bitcoin.signTransaction(psbt, psbt.txInputs.map((v, i) => i));
176
+ signedTransaction.finalizeAllInputs();
177
+ return signedTransaction.extractTransaction().toHex();
178
+ }
179
+ async signTransactionBitcoinWithPayload(request) {
180
+ const transaction = this.#transactionService.getTransaction(request.id);
181
+ const {
182
+ chain,
183
+ emitterTransaction,
184
+ feeCustom,
185
+ feeOption,
186
+ id
187
+ } = transaction;
188
+ const {
189
+ from,
190
+ to,
191
+ value
192
+ } = transaction.data;
193
+ if (!emitterTransaction) {
194
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INTERNAL_ERROR);
195
+ }
196
+ const chainInfo = this.#chainService.getChainInfoByKey(chain);
197
+ const bitcoinApi = this.#chainService.getBitcoinApi(chain);
198
+ const eventData = {
199
+ id,
200
+ errors: [],
201
+ warnings: [],
202
+ extrinsicHash: id
203
+ };
204
+ const network = chainInfo.isTestnet ? bitcoin.networks.testnet : bitcoin.networks.bitcoin;
205
+ const feeInfo = await this.#feeService.subscribeChainFee((0, _getId.getId)(), chain, 'bitcoin');
206
+ const [psbt] = await (0, _bitcoinTransfer.createBitcoinTransaction)({
207
+ bitcoinApi,
208
+ chain,
209
+ from,
210
+ feeCustom,
211
+ feeOption,
212
+ feeInfo,
213
+ to,
214
+ transferAll: false,
215
+ value: value || '0',
216
+ network
217
+ });
218
+ const pair = _uiKeyring.default.getPair(from);
219
+
220
+ // Unlock the pair if it is locked
221
+ if (pair.isLocked) {
222
+ _uiKeyring.default.unlockPair(pair.address);
223
+ }
224
+
225
+ // Finalize all inputs in the Psbt
226
+
227
+ // Sign the Psbt using the pair's bitcoin object
228
+ const signedTransaction = pair.bitcoin.signTransaction(psbt, psbt.txInputs.map((v, i) => i));
229
+ signedTransaction.finalizeAllInputs();
230
+ const signature = signedTransaction.extractTransaction().toHex();
231
+ this.#transactionService.emitterEventTransaction(emitterTransaction, eventData, chainInfo.slug, signature);
232
+ const {
233
+ promise,
234
+ reject,
235
+ resolve
236
+ } = (0, _utils.createPromiseHandler)();
237
+ emitterTransaction.on('extrinsicHash', data => {
238
+ if (!data.extrinsicHash) {
239
+ reject(_KoniTypes.BitcoinProviderErrorType.INTERNAL_ERROR);
240
+ } else {
241
+ resolve(data.extrinsicHash);
242
+ }
243
+ });
244
+ emitterTransaction.on('error', error => {
245
+ reject(error);
246
+ });
247
+ return promise;
248
+ }
249
+ async signPsbt(request) {
250
+ // Extract necessary information from the BitcoinSendTransactionRequest
251
+ const {
252
+ account,
253
+ payload
254
+ } = request.payload;
255
+ const {
256
+ allowedSighash,
257
+ broadcast,
258
+ psbt,
259
+ signAtIndex
260
+ } = payload;
261
+ const transaction = this.#transactionService.getTransaction(request.id);
262
+ let eventData = {
263
+ id: request.id,
264
+ errors: [],
265
+ warnings: [],
266
+ extrinsicHash: request.id
267
+ };
268
+
269
+ // todo: validate type of the account
270
+
271
+ if (Object.keys(account).length === 0) {
272
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INVALID_PARAMS, 'Please connect to Wallet to try this request');
273
+ }
274
+ const pair = _uiKeyring.default.getPair(account.address);
275
+
276
+ // Unlock the pair if it is locked
277
+ if (pair.isLocked) {
278
+ _uiKeyring.default.unlockPair(pair.address);
279
+ }
280
+ const signAtIndexGenerate = signAtIndex ? (0, _util.isArray)(signAtIndex) ? signAtIndex : [signAtIndex] : [...Array(psbt.inputCount)].map((_, i) => i);
281
+ let psptSignedTransaction = null;
282
+
283
+ // Sign the Psbt using the pair's bitcoin object
284
+ try {
285
+ psptSignedTransaction = pair.bitcoin.signTransaction(psbt, signAtIndexGenerate, allowedSighash);
286
+ } catch (e) {
287
+ if (transaction) {
288
+ var _transaction$emitterT;
289
+ (_transaction$emitterT = transaction.emitterTransaction) === null || _transaction$emitterT === void 0 ? void 0 : _transaction$emitterT.emit('error', {
290
+ ...eventData,
291
+ errors: [new _TransactionError.TransactionError(_types.BasicTxErrorType.INVALID_PARAMS, e.message)],
292
+ id: transaction.id,
293
+ extrinsicHash: transaction.id
294
+ });
295
+ }
296
+ throw new Error(e.message);
297
+ }
298
+ if (!psptSignedTransaction) {
299
+ throw new Error('Unable to sign');
300
+ }
301
+ if (!broadcast) {
302
+ for (const index of signAtIndexGenerate) {
303
+ psptSignedTransaction.finalizeInput(index);
304
+ }
305
+ return {
306
+ psbt: psptSignedTransaction.toHex()
307
+ };
308
+ }
309
+ if (!transaction) {
310
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INTERNAL_ERROR);
311
+ }
312
+ const {
313
+ chain,
314
+ emitterTransaction,
315
+ id
316
+ } = transaction;
317
+ eventData = {
318
+ id,
319
+ errors: [],
320
+ warnings: [],
321
+ extrinsicHash: id
322
+ };
323
+ if (!emitterTransaction) {
324
+ throw new _BitcoinProviderError.BitcoinProviderError(_KoniTypes.BitcoinProviderErrorType.INTERNAL_ERROR);
325
+ }
326
+ const chainInfo = this.#chainService.getChainInfoByKey(chain);
327
+ try {
328
+ psptSignedTransaction.finalizeAllInputs();
329
+ } catch (e) {
330
+ emitterTransaction.emit('error', {
331
+ ...eventData,
332
+ errors: [new _TransactionError.TransactionError(_types.BasicTxErrorType.INVALID_PARAMS, e.message)]
333
+ });
334
+ throw new Error(e.message);
335
+ }
336
+ const hexTransaction = psptSignedTransaction.extractTransaction().toHex();
337
+ this.#transactionService.emitterEventTransaction(emitterTransaction, eventData, chainInfo.slug, hexTransaction);
338
+ const {
339
+ promise,
340
+ reject,
341
+ resolve
342
+ } = (0, _utils.createPromiseHandler)();
343
+ emitterTransaction.on('extrinsicHash', data => {
344
+ if (!data.extrinsicHash || !psptSignedTransaction) {
345
+ reject(_KoniTypes.BitcoinProviderErrorType.INTERNAL_ERROR);
346
+ } else {
347
+ var _psptSignedTransactio;
348
+ resolve({
349
+ psbt: (_psptSignedTransactio = psptSignedTransaction) === null || _psptSignedTransactio === void 0 ? void 0 : _psptSignedTransactio.toHex(),
350
+ txid: data.extrinsicHash
351
+ });
352
+ }
353
+ });
354
+ emitterTransaction.on('error', error => {
355
+ reject(error);
356
+ });
357
+ return promise;
358
+ }
359
+ async decorateResultBitcoin(t, request, result) {
360
+ if (t === 'bitcoinSignatureRequest') {
361
+ result.payload = this.signMessageBitcoin(request);
362
+ } else if (t === 'bitcoinSendTransactionRequest') {
363
+ result.payload = this.signTransactionBitcoin(request);
364
+ } else if (t === 'bitcoinSignPsbtRequest') {
365
+ result.payload = await this.signPsbt(request);
366
+ } else if (t === 'bitcoinSendTransactionRequestAfterConfirmation') {
367
+ result.payload = await this.signTransactionBitcoinWithPayload(request);
368
+ }
369
+ if (t === 'bitcoinSignatureRequest' || t === 'bitcoinSendTransactionRequest' || t === 'bitcoinSignPsbtRequest' || t === 'bitcoinSendTransactionRequestAfterConfirmation') {
370
+ const isAlwaysRequired = await this.#requestService.settingService.isAlwaysRequired;
371
+ if (isAlwaysRequired) {
372
+ this.#requestService.keyringService.lock();
373
+ }
374
+ }
375
+ }
376
+ async completeConfirmationBitcoin(request) {
377
+ const confirmations = this.confirmationsQueueSubjectBitcoin.getValue();
378
+ for (const ct in request) {
379
+ const type = ct;
380
+ const result = request[type];
381
+ const {
382
+ id,
383
+ isApproved
384
+ } = result;
385
+ const {
386
+ resolver,
387
+ validator
388
+ } = this.confirmationsPromiseMap[id];
389
+ const confirmation = confirmations[type][id];
390
+ if (!resolver || !confirmation) {
391
+ this.#logger.error((0, _i18next.t)('Unable to proceed. Please try again'), type, id);
392
+ throw new Error('Unable to proceed. Please try again');
393
+ }
394
+ if (isApproved) {
395
+ try {
396
+ // Fill signature for some special type
397
+ await this.decorateResultBitcoin(type, confirmation, result);
398
+ const error = validator && validator(result);
399
+ if (error) {
400
+ resolver.reject(error);
401
+ }
402
+ } catch (e) {
403
+ resolver.reject(e);
404
+ }
405
+ }
406
+
407
+ // Delete confirmations from queue
408
+ delete this.confirmationsPromiseMap[id];
409
+ delete confirmations[type][id];
410
+ this.confirmationsQueueSubjectBitcoin.next(confirmations);
411
+
412
+ // Update icon, and close queue
413
+ this.#requestService.updateIconV2(this.#requestService.numAllRequests === 0);
414
+ resolver.resolve(result);
415
+ }
416
+ return true;
417
+ }
418
+ resetWallet() {
419
+ const confirmations = this.confirmationsQueueSubjectBitcoin.getValue();
420
+ for (const [type, requests] of Object.entries(confirmations)) {
421
+ for (const confirmation of Object.values(requests)) {
422
+ const {
423
+ id
424
+ } = confirmation;
425
+ const {
426
+ resolver
427
+ } = this.confirmationsPromiseMap[id];
428
+ if (!resolver || !confirmation) {
429
+ console.error('Not found confirmation', type, id);
430
+ } else {
431
+ resolver.reject(new Error('Reset wallet'));
432
+ }
433
+ delete this.confirmationsPromiseMap[id];
434
+ delete confirmations[type][id];
435
+ }
436
+ }
437
+ this.confirmationsQueueSubjectBitcoin.next(confirmations);
438
+ }
439
+ }
440
+ exports.default = BitcoinRequestHandler;
@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
7
  exports.default = void 0;
8
+ var _BitcoinRequestHandler = _interopRequireDefault(require("@subwallet/extension-base/services/request-service/handler/BitcoinRequestHandler"));
8
9
  var _CardanoRequestHandler = _interopRequireDefault(require("@subwallet/extension-base/services/request-service/handler/CardanoRequestHandler"));
9
10
  var _TonRequestHandler = _interopRequireDefault(require("./handler/TonRequestHandler"));
10
11
  var _handler = require("./handler");
@@ -19,13 +20,14 @@ class RequestService {
19
20
  #authRequestHandler;
20
21
  #substrateRequestHandler;
21
22
  #evmRequestHandler;
23
+ #bitcoinRequestHandler;
22
24
  #tonRequestHandler;
23
25
  #cardanoRequestHandler;
24
26
  #connectWCRequestHandler;
25
27
  #notSupportWCRequestHandler;
26
28
 
27
29
  // Common
28
- constructor(chainService, settingService, keyringService) {
30
+ constructor(chainService, settingService, keyringService, feeService, transactionService) {
29
31
  this.#chainService = chainService;
30
32
  this.settingService = settingService;
31
33
  this.keyringService = keyringService;
@@ -36,6 +38,7 @@ class RequestService {
36
38
  this.#evmRequestHandler = new _handler.EvmRequestHandler(this);
37
39
  this.#tonRequestHandler = new _TonRequestHandler.default(this);
38
40
  this.#cardanoRequestHandler = new _CardanoRequestHandler.default(this);
41
+ this.#bitcoinRequestHandler = new _BitcoinRequestHandler.default(this, this.#chainService, feeService, transactionService);
39
42
  this.#connectWCRequestHandler = new _handler.ConnectWCRequestHandler(this);
40
43
  this.#notSupportWCRequestHandler = new _handler.NotSupportWCRequestHandler(this);
41
44
 
@@ -43,7 +46,7 @@ class RequestService {
43
46
  this.updateIconV2();
44
47
  }
45
48
  get numAllRequests() {
46
- return this.allSubstrateRequests.length + this.numEvmRequests + this.numTonRequests + this.numCardanoRequests;
49
+ return this.allSubstrateRequests.length + this.numEvmRequests + this.numTonRequests + this.numCardanoRequests + this.numBitcoinRequests;
47
50
  }
48
51
  updateIconV2(shouldClose) {
49
52
  this.#popupHandler.updateIconV2(shouldClose);
@@ -156,6 +159,9 @@ class RequestService {
156
159
  get numCardanoRequests() {
157
160
  return this.#cardanoRequestHandler.numCardanoRequests;
158
161
  }
162
+ get numBitcoinRequests() {
163
+ return this.#bitcoinRequestHandler.numBitcoinRequests;
164
+ }
159
165
  get confirmationsQueueSubject() {
160
166
  return this.#evmRequestHandler.getConfirmationsQueueSubject();
161
167
  }
@@ -201,6 +207,25 @@ class RequestService {
201
207
  return this.#evmRequestHandler.updateConfirmation(id, type, payload, options, validator);
202
208
  }
203
209
 
210
+ // Bitcoin requests
211
+
212
+ get confirmationsQueueSubjectBitcoin() {
213
+ return this.#bitcoinRequestHandler.getConfirmationsQueueSubjectBitcoin();
214
+ }
215
+ addConfirmationBitcoin(id, url, type, payload) {
216
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
217
+ let validator = arguments.length > 5 ? arguments[5] : undefined;
218
+ return this.#bitcoinRequestHandler.addConfirmationBitcoin(id, url, type, payload, options, validator);
219
+ }
220
+ async completeConfirmationBitcoin(request) {
221
+ return await this.#bitcoinRequestHandler.completeConfirmationBitcoin(request);
222
+ }
223
+ updateConfirmationBitcoin(id, type, payload) {
224
+ let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
225
+ let validator = arguments.length > 4 ? arguments[4] : undefined;
226
+ return this.#bitcoinRequestHandler.updateConfirmationBitcoin(id, type, payload, options, validator);
227
+ }
228
+
204
229
  // WalletConnect Connect requests
205
230
  getConnectWCRequest(id) {
206
231
  return this.#connectWCRequestHandler.getConnectWCRequest(id);
@@ -237,7 +262,7 @@ class RequestService {
237
262
 
238
263
  // General methods
239
264
  get numRequests() {
240
- return this.numMetaRequests + this.numAuthRequests + this.numSubstrateRequests + this.numEvmRequests + this.numConnectWCRequests + this.numNotSupportWCRequests + this.numTonRequests + this.numCardanoRequests;
265
+ return this.numMetaRequests + this.numAuthRequests + this.numSubstrateRequests + this.numEvmRequests + this.numConnectWCRequests + this.numNotSupportWCRequests + this.numTonRequests + this.numCardanoRequests + this.numBitcoinRequests;
241
266
  }
242
267
  resetWallet() {
243
268
  this.#authRequestHandler.resetWallet();
@@ -245,6 +270,7 @@ class RequestService {
245
270
  this.#evmRequestHandler.resetWallet();
246
271
  this.#tonRequestHandler.resetWallet();
247
272
  this.#cardanoRequestHandler.resetWallet();
273
+ this.#bitcoinRequestHandler.resetWallet();
248
274
  this.#metadataRequestHandler.resetWallet();
249
275
  this.#connectWCRequestHandler.resetWallet();
250
276
  this.#notSupportWCRequestHandler.resetWallet();
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.RunesService = void 0;
7
+ var _SWError = require("@subwallet/extension-base/background/errors/SWError");
8
+ var _constants = require("@subwallet/extension-base/services/chain-service/constants");
9
+ var _apiRequestStrategy = require("@subwallet/extension-base/strategy/api-request-strategy");
10
+ var _base = require("@subwallet/extension-base/strategy/api-request-strategy/context/base");
11
+ var _utils = require("@subwallet/extension-base/strategy/api-request-strategy/utils");
12
+ // Copyright 2019-2022 @subwallet/extension-base authors & contributors
13
+ // SPDX-License-Identifier: Apache-2.0
14
+
15
+ const BITCOIN_API_URL = 'https://btc-api.koni.studio';
16
+ const BITCOIN_API_URL_TEST = 'https://api-testnet.openbit.app';
17
+ class RunesService extends _apiRequestStrategy.BaseApiRequestStrategy {
18
+ constructor(url) {
19
+ const context = new _base.BaseApiRequestContext();
20
+ super(context);
21
+ this.baseUrl = url;
22
+ }
23
+ headers = {
24
+ 'Content-Type': 'application/json',
25
+ Authorization: `Bearer ${_constants._BTC_SERVICE_TOKEN}`
26
+ };
27
+ isRateLimited() {
28
+ return false;
29
+ }
30
+ getUrl(path) {
31
+ return `${this.baseUrl}/${path}`;
32
+ }
33
+ getAddressRunesInfo(address, params) {
34
+ return this.addRequest(async () => {
35
+ const _rs = await (0, _utils.getRequest)(this.getUrl(`rune/address/${address}`), params, this.headers);
36
+ const rs = await _rs.json();
37
+ if (rs.status_code !== 200) {
38
+ throw new _SWError.SWError('RuneScanService.getAddressRunesInfo', rs.message);
39
+ }
40
+ return rs.result;
41
+ }, 1);
42
+ }
43
+
44
+ // * Deprecated
45
+ getRuneCollectionsByBatch(params) {
46
+ return this.addRequest(async () => {
47
+ const url = this.getUrl('rune');
48
+ const rs = await (0, _utils.getRequest)(url, params);
49
+ if (rs.status !== 200) {
50
+ throw new _SWError.SWError('RuneScanService.getRuneCollectionsByBatch', await rs.text());
51
+ }
52
+ return await rs.json();
53
+ }, 1);
54
+ }
55
+
56
+ // * Deprecated
57
+ getAddressRuneTxs(address, params) {
58
+ return this.addRequest(async () => {
59
+ const url = this.getUrl(`address/${address}/txs`);
60
+ const rs = await (0, _utils.getRequest)(url, params);
61
+ if (rs.status !== 200) {
62
+ throw new _SWError.SWError('RuneScanService.getAddressRuneTxs', await rs.text());
63
+ }
64
+ return await rs.json();
65
+ }, 0);
66
+ }
67
+ getRuneMetadata(runeid) {
68
+ return this.addRequest(async () => {
69
+ const _rs = await (0, _utils.getRequest)(this.getUrl(`rune/metadata/${runeid}`), undefined, this.headers);
70
+ const rs = await _rs.json();
71
+ if (rs.status_code !== 200) {
72
+ throw new _SWError.SWError('RuneScanService.getRuneMetadata', rs.message);
73
+ }
74
+ return rs.result;
75
+ }, 0);
76
+ }
77
+ getAddressRuneUtxos(address) {
78
+ return this.addRequest(async () => {
79
+ const _rs = await (0, _utils.getRequest)(this.getUrl(`rune/address/${address}/rune/utxo`), undefined, this.headers);
80
+ const rs = await _rs.json();
81
+ if (rs.status_code !== 200) {
82
+ throw new _SWError.SWError('RuneScanService.getAddressRuneUtxos', rs.message);
83
+ }
84
+ return rs.result;
85
+ }, 0);
86
+ }
87
+
88
+ // Singleton
89
+
90
+ static getInstance() {
91
+ let isTestnet = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
92
+ if (isTestnet) {
93
+ if (!RunesService.testnet) {
94
+ RunesService.testnet = new RunesService(BITCOIN_API_URL_TEST);
95
+ }
96
+ return RunesService.testnet;
97
+ } else {
98
+ if (!RunesService.mainnet) {
99
+ RunesService.mainnet = new RunesService(BITCOIN_API_URL);
100
+ }
101
+ return RunesService.mainnet;
102
+ }
103
+ }
104
+ }
105
+ exports.RunesService = RunesService;