@metamask-previews/bridge-status-controller 12.0.1-preview-fa52096c → 13.1.0-preview-3d7a30d

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 (60) hide show
  1. package/CHANGELOG.md +35 -2
  2. package/dist/bridge-status-controller.cjs +257 -7
  3. package/dist/bridge-status-controller.cjs.map +1 -1
  4. package/dist/bridge-status-controller.d.cts +23 -3
  5. package/dist/bridge-status-controller.d.cts.map +1 -1
  6. package/dist/bridge-status-controller.d.mts +23 -3
  7. package/dist/bridge-status-controller.d.mts.map +1 -1
  8. package/dist/bridge-status-controller.mjs +259 -9
  9. package/dist/bridge-status-controller.mjs.map +1 -1
  10. package/dist/constants.cjs +3 -1
  11. package/dist/constants.cjs.map +1 -1
  12. package/dist/constants.d.cts +2 -0
  13. package/dist/constants.d.cts.map +1 -1
  14. package/dist/constants.d.mts +2 -0
  15. package/dist/constants.d.mts.map +1 -1
  16. package/dist/constants.mjs +2 -0
  17. package/dist/constants.mjs.map +1 -1
  18. package/dist/index.cjs +4 -1
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +2 -1
  21. package/dist/index.d.cts.map +1 -1
  22. package/dist/index.d.mts +2 -1
  23. package/dist/index.d.mts.map +1 -1
  24. package/dist/index.mjs +2 -1
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/types.cjs +10 -1
  27. package/dist/types.cjs.map +1 -1
  28. package/dist/types.d.cts +28 -7
  29. package/dist/types.d.cts.map +1 -1
  30. package/dist/types.d.mts +28 -7
  31. package/dist/types.d.mts.map +1 -1
  32. package/dist/types.mjs +9 -0
  33. package/dist/types.mjs.map +1 -1
  34. package/dist/utils/bridge-status.cjs +6 -5
  35. package/dist/utils/bridge-status.cjs.map +1 -1
  36. package/dist/utils/bridge-status.d.cts.map +1 -1
  37. package/dist/utils/bridge-status.d.mts.map +1 -1
  38. package/dist/utils/bridge-status.mjs +6 -5
  39. package/dist/utils/bridge-status.mjs.map +1 -1
  40. package/dist/utils/gas.cjs +31 -0
  41. package/dist/utils/gas.cjs.map +1 -0
  42. package/dist/utils/gas.d.cts +20 -0
  43. package/dist/utils/gas.d.cts.map +1 -0
  44. package/dist/utils/gas.d.mts +20 -0
  45. package/dist/utils/gas.d.mts.map +1 -0
  46. package/dist/utils/gas.mjs +27 -0
  47. package/dist/utils/gas.mjs.map +1 -0
  48. package/dist/utils/transaction.cjs +115 -0
  49. package/dist/utils/transaction.cjs.map +1 -0
  50. package/dist/utils/transaction.d.cts +45 -0
  51. package/dist/utils/transaction.d.cts.map +1 -0
  52. package/dist/utils/transaction.d.mts +45 -0
  53. package/dist/utils/transaction.d.mts.map +1 -0
  54. package/dist/utils/transaction.mjs +106 -0
  55. package/dist/utils/transaction.mjs.map +1 -0
  56. package/dist/utils/validators.cjs +1 -1
  57. package/dist/utils/validators.cjs.map +1 -1
  58. package/dist/utils/validators.mjs +2 -2
  59. package/dist/utils/validators.mjs.map +1 -1
  60. package/package.json +14 -3
package/CHANGELOG.md CHANGED
@@ -7,9 +7,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [13.1.0]
11
+
12
+ ### Fixed
13
+
14
+ - Add optional `approvalTxId` to `BridgeHistoryItem` to prevent transaction metadata corruption ([#5670](https://github.com/MetaMask/core/pull/5670))
15
+ - Fixes issue where `updateTransaction` was overwriting transaction metadata when associating approvals
16
+ - Stores approval transaction ID in bridge history instead of modifying transaction metadata
17
+ - Reduces duplicate quote data in state
18
+
19
+ ## [13.0.0]
20
+
21
+ ### Added
22
+
23
+ - **BREAKING:** Add `@metamask/snaps-controllers` peer dependency at `^11.0.0` ([#5634](https://github.com/MetaMask/core/pull/5634), [#5639](https://github.com/MetaMask/core/pull/5639))
24
+ - **BREAKING:** Add `@metamask/gas-fee-controller` peer dependency at `^23.0.0` ([#5643](https://github.com/MetaMask/core/pull/5643))
25
+ - **BREAKING:** Add `@metamask/assets-controllers` peer dependency at `^58.0.0` ([#5643](https://github.com/MetaMask/core/pull/5643), [#5672](https://github.com/MetaMask/core/pull/5672))
26
+ - Add `@metamask/user-operation-controller` dependency at `^33.0.0` ([#5643](https://github.com/MetaMask/core/pull/5643))
27
+ - Add `uuid` dependency at `^8.3.2` ([#5634](https://github.com/MetaMask/core/pull/5634))
28
+ - Add `@metamask/keyring-api` dependency at `^17.4.0` ([#5643](https://github.com/MetaMask/core/pull/5643))
29
+ - Add `bignumber.js` dependency at `^9.1.2` ([#5643](https://github.com/MetaMask/core/pull/5643))
30
+ - Add `submitTx` handler that submits cross-chain swaps transactions and triggers polling for destination transaction status ([#5634](https://github.com/MetaMask/core/pull/5634))
31
+ - Enable submitting EVM transactions using `submitTx` ([#5643](https://github.com/MetaMask/core/pull/5643))
32
+ - Add functionality for importing tokens from transaction after successful confirmation ([#5643](https://github.com/MetaMask/core/pull/5643))
33
+
10
34
  ### Changed
11
35
 
12
- - Bump `@metamask/bridge-controller` dependency to `^14.0.0` ([#5657](https://github.com/MetaMask/core/pull/5657))
36
+ - **BREAKING** Change `@metamask/bridge-controller` from dependency to peer dependency and bump to `^16.0.0` ([#5657](https://github.com/MetaMask/core/pull/5657), [#5665](https://github.com/MetaMask/core/pull/5665), [#5643](https://github.com/MetaMask/core/pull/5643) [#5672](https://github.com/MetaMask/core/pull/5672))
37
+ - Add optional config.customBridgeApiBaseUrl constructor arg to set the bridge-api base URL ([#5634](https://github.com/MetaMask/core/pull/5634))
38
+ - Add required `addTransactionFn` and `estimateGasFeeFn` args to the BridgeStatusController constructor to enable calling TransactionController's methods from `submitTx` ([#5643](https://github.com/MetaMask/core/pull/5643))
39
+ - Add optional `addUserOperationFromTransactionFn` arg to the BridgeStatusController constructor to enable submitting txs from smart accounts using the UserOperationController's addUserOperationFromTransaction method ([#5643](https://github.com/MetaMask/core/pull/5643))
40
+
41
+ ### Fixed
42
+
43
+ - Update validators to accept any `bridge` string in the StatusResponse ([#5634](https://github.com/MetaMask/core/pull/5634))
13
44
 
14
45
  ## [12.0.1]
15
46
 
@@ -107,7 +138,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
107
138
 
108
139
  - Initial release ([#5317](https://github.com/MetaMask/core/pull/5317))
109
140
 
110
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/bridge-status-controller@12.0.1...HEAD
141
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/bridge-status-controller@13.1.0...HEAD
142
+ [13.1.0]: https://github.com/MetaMask/core/compare/@metamask/bridge-status-controller@13.0.0...@metamask/bridge-status-controller@13.1.0
143
+ [13.0.0]: https://github.com/MetaMask/core/compare/@metamask/bridge-status-controller@12.0.1...@metamask/bridge-status-controller@13.0.0
111
144
  [12.0.1]: https://github.com/MetaMask/core/compare/@metamask/bridge-status-controller@12.0.0...@metamask/bridge-status-controller@12.0.1
112
145
  [12.0.0]: https://github.com/MetaMask/core/compare/@metamask/bridge-status-controller@11.0.0...@metamask/bridge-status-controller@12.0.0
113
146
  [11.0.0]: https://github.com/MetaMask/core/compare/@metamask/bridge-status-controller@10.0.0...@metamask/bridge-status-controller@11.0.0
@@ -10,15 +10,22 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _BridgeStatusController_instances, _BridgeStatusController_pollingTokensByTxMetaId, _BridgeStatusController_clientId, _BridgeStatusController_fetchFn, _BridgeStatusController_config, _BridgeStatusController_restartPollingForIncompleteHistoryItems, _BridgeStatusController_getMultichainSelectedAccountAddress, _BridgeStatusController_fetchBridgeTxStatus, _BridgeStatusController_getSrcTxHash, _BridgeStatusController_updateSrcTxHash, _BridgeStatusController_wipeBridgeStatusByChainId;
13
+ var _BridgeStatusController_instances, _BridgeStatusController_pollingTokensByTxMetaId, _BridgeStatusController_clientId, _BridgeStatusController_fetchFn, _BridgeStatusController_config, _BridgeStatusController_addTransactionFn, _BridgeStatusController_estimateGasFeeFn, _BridgeStatusController_addUserOperationFromTransactionFn, _BridgeStatusController_restartPollingForIncompleteHistoryItems, _BridgeStatusController_getMultichainSelectedAccount, _BridgeStatusController_getMultichainSelectedAccountAddress, _BridgeStatusController_fetchBridgeTxStatus, _BridgeStatusController_getSrcTxHash, _BridgeStatusController_updateSrcTxHash, _BridgeStatusController_wipeBridgeStatusByChainId, _BridgeStatusController_handleSolanaTx, _BridgeStatusController_waitForHashAndReturnFinalTxMeta, _BridgeStatusController_handleApprovalTx, _BridgeStatusController_handleEvmSmartTransaction, _BridgeStatusController_handleEvmTransaction, _BridgeStatusController_addTokens, _BridgeStatusController_handleUSDTAllowanceReset, _BridgeStatusController_calculateGasFees;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.BridgeStatusController = void 0;
16
16
  const bridge_controller_1 = require("@metamask/bridge-controller");
17
+ const controller_utils_1 = require("@metamask/controller-utils");
18
+ const keyring_api_1 = require("@metamask/keyring-api");
17
19
  const polling_controller_1 = require("@metamask/polling-controller");
20
+ const transaction_controller_1 = require("@metamask/transaction-controller");
18
21
  const utils_1 = require("@metamask/utils");
22
+ const bignumber_js_1 = require("bignumber.js");
19
23
  const constants_1 = require("./constants.cjs");
20
24
  const types_1 = require("./types.cjs");
21
25
  const bridge_status_1 = require("./utils/bridge-status.cjs");
26
+ const gas_1 = require("./utils/gas.cjs");
27
+ const transaction_1 = require("./utils/transaction.cjs");
28
+ const transaction_2 = require("./utils/transaction.cjs");
22
29
  const metadata = {
23
30
  // We want to persist the bridge status state so that we can show the proper data for the Activity list
24
31
  // basically match the behavior of TransactionController
@@ -28,7 +35,7 @@ const metadata = {
28
35
  },
29
36
  };
30
37
  class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPollingController)() {
31
- constructor({ messenger, state, clientId, fetchFn, config, }) {
38
+ constructor({ messenger, state, clientId, fetchFn, addTransactionFn, addUserOperationFromTransactionFn, estimateGasFeeFn, config, }) {
32
39
  super({
33
40
  name: constants_1.BRIDGE_STATUS_CONTROLLER_NAME,
34
41
  metadata,
@@ -44,6 +51,9 @@ class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPoll
44
51
  _BridgeStatusController_clientId.set(this, void 0);
45
52
  _BridgeStatusController_fetchFn.set(this, void 0);
46
53
  _BridgeStatusController_config.set(this, void 0);
54
+ _BridgeStatusController_addTransactionFn.set(this, void 0);
55
+ _BridgeStatusController_estimateGasFeeFn.set(this, void 0);
56
+ _BridgeStatusController_addUserOperationFromTransactionFn.set(this, void 0);
47
57
  this.resetState = () => {
48
58
  this.update((state) => {
49
59
  state.txHistory = constants_1.DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;
@@ -85,8 +95,13 @@ class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPoll
85
95
  });
86
96
  });
87
97
  });
98
+ /**
99
+ * Starts polling for the bridge tx status
100
+ *
101
+ * @param startPollingForBridgeTxStatusArgs - The args to start polling for the bridge tx status
102
+ */
88
103
  this.startPollingForBridgeTxStatus = (startPollingForBridgeTxStatusArgs) => {
89
- const { bridgeTxMeta, statusRequest, quoteResponse, startTime, slippagePercentage, initialDestAssetBalance, targetContractAddress, } = startPollingForBridgeTxStatusArgs;
104
+ const { bridgeTxMeta, statusRequest, quoteResponse, startTime, slippagePercentage, initialDestAssetBalance, targetContractAddress, approvalTxId, } = startPollingForBridgeTxStatusArgs;
90
105
  const accountAddress = __classPrivateFieldGet(this, _BridgeStatusController_instances, "m", _BridgeStatusController_getMultichainSelectedAccountAddress).call(this);
91
106
  // Write all non-status fields to state so we can reference the quote in Activity list without the Bridge API
92
107
  // We know it's in progress but not the exact status yet
@@ -115,6 +130,7 @@ class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPoll
115
130
  },
116
131
  },
117
132
  hasApprovalTx: Boolean(quoteResponse.approval),
133
+ approvalTxId,
118
134
  };
119
135
  this.update((state) => {
120
136
  // Use the txMeta.id as the key so we can reference the txMeta in TransactionController
@@ -142,7 +158,7 @@ class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPoll
142
158
  }
143
159
  __classPrivateFieldGet(this, _BridgeStatusController_updateSrcTxHash, "f").call(this, bridgeTxMetaId, srcTxHash);
144
160
  const statusRequest = (0, bridge_status_1.getStatusRequestWithSrcTxHash)(historyItem.quote, srcTxHash);
145
- const status = await (0, bridge_status_1.fetchBridgeTxStatus)(statusRequest, __classPrivateFieldGet(this, _BridgeStatusController_clientId, "f"), __classPrivateFieldGet(this, _BridgeStatusController_fetchFn, "f"), __classPrivateFieldGet(this, _BridgeStatusController_config, "f").customBridgeApiBaseUrl ?? bridge_controller_1.BRIDGE_PROD_API_BASE_URL);
161
+ const status = await (0, bridge_status_1.fetchBridgeTxStatus)(statusRequest, __classPrivateFieldGet(this, _BridgeStatusController_clientId, "f"), __classPrivateFieldGet(this, _BridgeStatusController_fetchFn, "f"), __classPrivateFieldGet(this, _BridgeStatusController_config, "f").customBridgeApiBaseUrl);
146
162
  const newBridgeHistoryItem = {
147
163
  ...historyItem,
148
164
  status,
@@ -219,13 +235,245 @@ class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPoll
219
235
  }, state.txHistory);
220
236
  });
221
237
  });
238
+ /**
239
+ * ******************************************************
240
+ * TX SUBMISSION HANDLING
241
+ *******************************************************
242
+ */
243
+ /**
244
+ * Submits the transaction to the snap using the keyring rpc method
245
+ * This adds an approval tx to the ApprovalsController in the background
246
+ * The client needs to handle the approval tx by redirecting to the confirmation page with the approvalTxId in the URL
247
+ *
248
+ * @param quoteResponse - The quote response
249
+ * @param quoteResponse.quote - The quote
250
+ * @returns The transaction meta
251
+ */
252
+ _BridgeStatusController_handleSolanaTx.set(this, async (quoteResponse) => {
253
+ const selectedAccount = __classPrivateFieldGet(this, _BridgeStatusController_instances, "m", _BridgeStatusController_getMultichainSelectedAccount).call(this);
254
+ if (!selectedAccount) {
255
+ throw new Error('Failed to submit cross-chain swap transaction: undefined multichain account');
256
+ }
257
+ if (!selectedAccount.metadata?.snap?.id ||
258
+ !selectedAccount.options?.scope) {
259
+ throw new Error('Failed to submit cross-chain swap transaction: undefined snap id or scope');
260
+ }
261
+ const keyringRequest = (0, transaction_1.getKeyringRequest)(quoteResponse, selectedAccount);
262
+ const keyringResponse = (await this.messagingSystem.call('SnapController:handleRequest', keyringRequest));
263
+ // The extension client actually redirects before it can do anytyhing with this meta
264
+ const txMeta = (0, transaction_1.handleSolanaTxResponse)(keyringResponse, quoteResponse, selectedAccount);
265
+ // TODO remove this eventually, just returning it now to match extension behavior
266
+ // OR if the snap can propagate the snapRequestId or keyringReqId to the ApprovalsController, this can return the approvalTxId instead and clients won't need to subscribe to the ApprovalsController state to redirect
267
+ return txMeta;
268
+ });
269
+ _BridgeStatusController_waitForHashAndReturnFinalTxMeta.set(this, async (hashPromise) => {
270
+ const transactionHash = await hashPromise;
271
+ const finalTransactionMeta = this.messagingSystem
272
+ .call('TransactionController:getState')
273
+ .transactions.find((tx) => tx.hash === transactionHash);
274
+ return finalTransactionMeta;
275
+ });
276
+ _BridgeStatusController_handleApprovalTx.set(this, async (quoteResponse) => {
277
+ if (quoteResponse.approval) {
278
+ await __classPrivateFieldGet(this, _BridgeStatusController_handleUSDTAllowanceReset, "f").call(this, quoteResponse);
279
+ const approvalTxMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, transaction_controller_1.TransactionType.bridgeApproval, quoteResponse.approval, quoteResponse);
280
+ if (!approvalTxMeta) {
281
+ throw new Error('Failed to submit bridge tx: approval txMeta is undefined');
282
+ }
283
+ await (0, transaction_1.handleLineaDelay)(quoteResponse);
284
+ return approvalTxMeta;
285
+ }
286
+ return undefined;
287
+ });
288
+ _BridgeStatusController_handleEvmSmartTransaction.set(this, async (trade, quoteResponse, approvalTxId) => {
289
+ return await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, transaction_controller_1.TransactionType.bridge, trade, quoteResponse, approvalTxId, false);
290
+ });
291
+ /**
292
+ * Submits an EVM transaction to the TransactionController
293
+ *
294
+ * @param transactionType - The type of transaction to submit
295
+ * @param trade - The trade data to confirm
296
+ * @param quoteResponse - The quote response
297
+ * @param quoteResponse.quote - The quote
298
+ * @param approvalTxId - The tx id of the approval tx
299
+ * @param shouldWaitForHash - Whether to wait for the hash of the transaction
300
+ * @returns The transaction meta
301
+ */
302
+ _BridgeStatusController_handleEvmTransaction.set(this, async (transactionType, trade, quoteResponse, approvalTxId, shouldWaitForHash = true) => {
303
+ const actionId = (0, transaction_2.generateActionId)().toString();
304
+ const selectedAccount = this.messagingSystem.call('AccountsController:getAccountByAddress', trade.from);
305
+ if (!selectedAccount) {
306
+ throw new Error('Failed to submit cross-chain swap transaction: unknown account in trade data');
307
+ }
308
+ const hexChainId = (0, bridge_controller_1.formatChainIdToHex)(trade.chainId);
309
+ const networkClientId = this.messagingSystem.call('NetworkController:findNetworkClientIdByChainId', hexChainId);
310
+ const requestOptions = {
311
+ actionId,
312
+ networkClientId,
313
+ requireApproval: false,
314
+ type: transactionType,
315
+ origin: 'metamask',
316
+ };
317
+ const transactionParams = {
318
+ ...trade,
319
+ chainId: hexChainId,
320
+ gasLimit: trade.gasLimit?.toString(),
321
+ gas: trade.gasLimit?.toString(),
322
+ };
323
+ const transactionParamsWithMaxGas = {
324
+ ...transactionParams,
325
+ ...(await __classPrivateFieldGet(this, _BridgeStatusController_calculateGasFees, "f").call(this, transactionParams, networkClientId, hexChainId)),
326
+ };
327
+ let result;
328
+ let transactionMeta;
329
+ const isSmartContractAccount = selectedAccount.type === keyring_api_1.EthAccountType.Erc4337;
330
+ if (isSmartContractAccount && __classPrivateFieldGet(this, _BridgeStatusController_addUserOperationFromTransactionFn, "f")) {
331
+ const smartAccountTxResult = await __classPrivateFieldGet(this, _BridgeStatusController_addUserOperationFromTransactionFn, "f").call(this, transactionParamsWithMaxGas, requestOptions);
332
+ result = smartAccountTxResult.transactionHash;
333
+ transactionMeta = {
334
+ ...requestOptions,
335
+ chainId: hexChainId,
336
+ txParams: transactionParamsWithMaxGas,
337
+ time: Date.now(),
338
+ id: smartAccountTxResult.id,
339
+ status: transaction_controller_1.TransactionStatus.confirmed,
340
+ };
341
+ }
342
+ else {
343
+ const addTransactionResult = await __classPrivateFieldGet(this, _BridgeStatusController_addTransactionFn, "f").call(this, transactionParamsWithMaxGas, requestOptions);
344
+ result = addTransactionResult.result;
345
+ transactionMeta = addTransactionResult.transactionMeta;
346
+ }
347
+ if (shouldWaitForHash) {
348
+ return await __classPrivateFieldGet(this, _BridgeStatusController_waitForHashAndReturnFinalTxMeta, "f").call(this, result);
349
+ }
350
+ // TODO why is this needed?
351
+ // Note that updateTransaction doesn't actually error if you add fields that don't conform the to the txMeta type
352
+ // they will be there at runtime, but you just don't get any type safety checks on them
353
+ // const fieldsToAddToTxMeta = getTxMetaFields(quoteResponse, approvalTxId);
354
+ // dispatch(updateTransaction(completeTxMeta);
355
+ return {
356
+ ...(0, transaction_1.getTxMetaFields)(quoteResponse, approvalTxId),
357
+ ...transactionMeta,
358
+ };
359
+ });
360
+ // Only adds tokens if the source or dest chain is an EVM chain bc non-evm tokens
361
+ // are detected by the multichain asset controllers
362
+ _BridgeStatusController_addTokens.set(this, (asset) => {
363
+ if ((0, bridge_controller_1.isNativeAddress)(asset.address) || (0, bridge_controller_1.isSolanaChainId)(asset.chainId)) {
364
+ return;
365
+ }
366
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
367
+ this.messagingSystem.call('TokensController:addDetectedTokens', [
368
+ {
369
+ address: asset.address,
370
+ decimals: asset.decimals,
371
+ image: asset.iconUrl,
372
+ name: asset.name,
373
+ symbol: asset.symbol,
374
+ },
375
+ ], {
376
+ chainId: (0, bridge_controller_1.formatChainIdToHex)(asset.chainId),
377
+ selectedAddress: __classPrivateFieldGet(this, _BridgeStatusController_instances, "m", _BridgeStatusController_getMultichainSelectedAccountAddress).call(this),
378
+ });
379
+ });
380
+ _BridgeStatusController_handleUSDTAllowanceReset.set(this, async (quoteResponse) => {
381
+ const hexChainId = (0, bridge_controller_1.formatChainIdToHex)(quoteResponse.quote.srcChainId);
382
+ if (quoteResponse.approval &&
383
+ (0, bridge_controller_1.isEthUsdt)(hexChainId, quoteResponse.quote.srcAsset.address)) {
384
+ const allowance = new bignumber_js_1.BigNumber(await this.messagingSystem.call('BridgeController:getBridgeERC20Allowance', quoteResponse.quote.srcAsset.address, hexChainId));
385
+ const shouldResetApproval = allowance.lt(quoteResponse.sentAmount.amount) && allowance.gt(0);
386
+ if (shouldResetApproval) {
387
+ await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, transaction_controller_1.TransactionType.bridgeApproval, { ...quoteResponse.approval, data: (0, bridge_controller_1.getEthUsdtResetData)() }, quoteResponse);
388
+ }
389
+ }
390
+ });
391
+ _BridgeStatusController_calculateGasFees.set(this, async (transactionParams, networkClientId, chainId) => {
392
+ const { gasFeeEstimates } = this.messagingSystem.call('GasFeeController:getState');
393
+ const { estimates: txGasFeeEstimates } = await __classPrivateFieldGet(this, _BridgeStatusController_estimateGasFeeFn, "f").call(this, {
394
+ transactionParams,
395
+ chainId,
396
+ networkClientId,
397
+ });
398
+ const { maxFeePerGas, maxPriorityFeePerGas } = (0, gas_1.getTxGasEstimates)({
399
+ networkGasFeeEstimates: gasFeeEstimates,
400
+ txGasFeeEstimates,
401
+ });
402
+ const maxGasLimit = (0, controller_utils_1.toHex)(transactionParams.gas ?? 0);
403
+ return {
404
+ maxFeePerGas,
405
+ maxPriorityFeePerGas,
406
+ gas: maxGasLimit,
407
+ };
408
+ });
409
+ /**
410
+ * Submits a cross-chain swap transaction
411
+ *
412
+ * @param quoteResponse - The quote response
413
+ * @param isStxEnabledOnClient - Whether smart transactions are enabled on the client, for example the getSmartTransactionsEnabled selector value from the extension
414
+ * @returns The transaction meta
415
+ */
416
+ this.submitTx = async (quoteResponse, isStxEnabledOnClient) => {
417
+ let txMeta;
418
+ // Submit SOLANA tx
419
+ if ((0, bridge_controller_1.isSolanaChainId)(quoteResponse.quote.srcChainId) &&
420
+ typeof quoteResponse.trade === 'string') {
421
+ txMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleSolanaTx, "f").call(this, quoteResponse);
422
+ }
423
+ // Submit EVM tx
424
+ let approvalTime, approvalTxId;
425
+ if (!(0, bridge_controller_1.isSolanaChainId)(quoteResponse.quote.srcChainId) &&
426
+ typeof quoteResponse.trade !== 'string') {
427
+ // Set approval time and id if an approval tx is needed
428
+ const approvalTxMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleApprovalTx, "f").call(this, quoteResponse);
429
+ approvalTime = approvalTxMeta?.time;
430
+ approvalTxId = approvalTxMeta?.id;
431
+ // Handle smart transactions if enabled
432
+ if (isStxEnabledOnClient) {
433
+ txMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmSmartTransaction, "f").call(this, quoteResponse.trade, quoteResponse, approvalTxId);
434
+ }
435
+ else {
436
+ txMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, transaction_controller_1.TransactionType.bridge, quoteResponse.trade, quoteResponse, approvalTxId);
437
+ }
438
+ }
439
+ if (!txMeta) {
440
+ throw new Error('Failed to submit bridge tx: txMeta is undefined');
441
+ }
442
+ try {
443
+ // Start polling for bridge tx status
444
+ this.startPollingForBridgeTxStatus({
445
+ bridgeTxMeta: txMeta,
446
+ statusRequest: {
447
+ ...(0, transaction_1.getStatusRequestParams)(quoteResponse),
448
+ srcTxHash: txMeta.hash,
449
+ },
450
+ quoteResponse,
451
+ slippagePercentage: 0,
452
+ startTime: approvalTime ?? Date.now(),
453
+ approvalTxId,
454
+ });
455
+ // Add tokens to the token list
456
+ __classPrivateFieldGet(this, _BridgeStatusController_addTokens, "f").call(this, quoteResponse.quote.srcAsset);
457
+ __classPrivateFieldGet(this, _BridgeStatusController_addTokens, "f").call(this, quoteResponse.quote.destAsset);
458
+ }
459
+ catch {
460
+ // Ignore errors here, we don't want to crash the app if this fails and tx submission succeeds
461
+ }
462
+ return txMeta;
463
+ };
222
464
  __classPrivateFieldSet(this, _BridgeStatusController_clientId, clientId, "f");
223
465
  __classPrivateFieldSet(this, _BridgeStatusController_fetchFn, fetchFn, "f");
224
- __classPrivateFieldSet(this, _BridgeStatusController_config, config ?? {}, "f");
466
+ __classPrivateFieldSet(this, _BridgeStatusController_addTransactionFn, addTransactionFn, "f");
467
+ __classPrivateFieldSet(this, _BridgeStatusController_addUserOperationFromTransactionFn, addUserOperationFromTransactionFn, "f");
468
+ __classPrivateFieldSet(this, _BridgeStatusController_estimateGasFeeFn, estimateGasFeeFn, "f");
469
+ __classPrivateFieldSet(this, _BridgeStatusController_config, {
470
+ customBridgeApiBaseUrl: config?.customBridgeApiBaseUrl ?? constants_1.BRIDGE_PROD_API_BASE_URL,
471
+ }, "f");
225
472
  // Register action handlers
226
473
  this.messagingSystem.registerActionHandler(`${constants_1.BRIDGE_STATUS_CONTROLLER_NAME}:startPollingForBridgeTxStatus`, this.startPollingForBridgeTxStatus.bind(this));
227
474
  this.messagingSystem.registerActionHandler(`${constants_1.BRIDGE_STATUS_CONTROLLER_NAME}:wipeBridgeStatus`, this.wipeBridgeStatus.bind(this));
228
475
  this.messagingSystem.registerActionHandler(`${constants_1.BRIDGE_STATUS_CONTROLLER_NAME}:resetState`, this.resetState.bind(this));
476
+ this.messagingSystem.registerActionHandler(`${constants_1.BRIDGE_STATUS_CONTROLLER_NAME}:submitTx`, this.submitTx.bind(this));
229
477
  // Set interval
230
478
  this.setIntervalLength(constants_1.REFRESH_INTERVAL_MS);
231
479
  // If you close the extension, but keep the browser open, the polling continues
@@ -235,7 +483,9 @@ class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPoll
235
483
  }
236
484
  }
237
485
  exports.BridgeStatusController = BridgeStatusController;
238
- _BridgeStatusController_pollingTokensByTxMetaId = new WeakMap(), _BridgeStatusController_clientId = new WeakMap(), _BridgeStatusController_fetchFn = new WeakMap(), _BridgeStatusController_config = new WeakMap(), _BridgeStatusController_restartPollingForIncompleteHistoryItems = new WeakMap(), _BridgeStatusController_fetchBridgeTxStatus = new WeakMap(), _BridgeStatusController_getSrcTxHash = new WeakMap(), _BridgeStatusController_updateSrcTxHash = new WeakMap(), _BridgeStatusController_wipeBridgeStatusByChainId = new WeakMap(), _BridgeStatusController_instances = new WeakSet(), _BridgeStatusController_getMultichainSelectedAccountAddress = function _BridgeStatusController_getMultichainSelectedAccountAddress() {
239
- return (this.messagingSystem.call('AccountsController:getSelectedMultichainAccount')?.address ?? '');
486
+ _BridgeStatusController_pollingTokensByTxMetaId = new WeakMap(), _BridgeStatusController_clientId = new WeakMap(), _BridgeStatusController_fetchFn = new WeakMap(), _BridgeStatusController_config = new WeakMap(), _BridgeStatusController_addTransactionFn = new WeakMap(), _BridgeStatusController_estimateGasFeeFn = new WeakMap(), _BridgeStatusController_addUserOperationFromTransactionFn = new WeakMap(), _BridgeStatusController_restartPollingForIncompleteHistoryItems = new WeakMap(), _BridgeStatusController_fetchBridgeTxStatus = new WeakMap(), _BridgeStatusController_getSrcTxHash = new WeakMap(), _BridgeStatusController_updateSrcTxHash = new WeakMap(), _BridgeStatusController_wipeBridgeStatusByChainId = new WeakMap(), _BridgeStatusController_handleSolanaTx = new WeakMap(), _BridgeStatusController_waitForHashAndReturnFinalTxMeta = new WeakMap(), _BridgeStatusController_handleApprovalTx = new WeakMap(), _BridgeStatusController_handleEvmSmartTransaction = new WeakMap(), _BridgeStatusController_handleEvmTransaction = new WeakMap(), _BridgeStatusController_addTokens = new WeakMap(), _BridgeStatusController_handleUSDTAllowanceReset = new WeakMap(), _BridgeStatusController_calculateGasFees = new WeakMap(), _BridgeStatusController_instances = new WeakSet(), _BridgeStatusController_getMultichainSelectedAccount = function _BridgeStatusController_getMultichainSelectedAccount() {
487
+ return this.messagingSystem.call('AccountsController:getSelectedMultichainAccount');
488
+ }, _BridgeStatusController_getMultichainSelectedAccountAddress = function _BridgeStatusController_getMultichainSelectedAccountAddress() {
489
+ return __classPrivateFieldGet(this, _BridgeStatusController_instances, "m", _BridgeStatusController_getMultichainSelectedAccount).call(this)?.address ?? '';
240
490
  };
241
491
  //# sourceMappingURL=bridge-status-controller.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"bridge-status-controller.cjs","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,mEAAuE;AACvE,qEAA+E;AAC/E,2CAAwD;AAExD,+CAIqB;AACrB,uCAA4E;AAM5E,6DAG+B;AAE/B,MAAM,QAAQ,GAA+C;IAC3D,uGAAuG;IACvG,wDAAwD;IACxD,SAAS,EAAE;QACT,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AASF,MAAa,sBAAuB,SAAQ,IAAA,oDAA+B,GAI1E;IAWC,YAAY,EACV,SAAS,EACT,KAAK,EACL,QAAQ,EACR,OAAO,EACP,MAAM,GASP;QACC,KAAK,CAAC;YACJ,IAAI,EAAE,yCAA6B;YACnC,QAAQ;YACR,SAAS;YACT,8BAA8B;YAC9B,KAAK,EAAE;gBACL,GAAG,kDAAsC;gBACzC,GAAG,KAAK;aACT;SACF,CAAC,CAAC;;QAlCL,0DAAwD,EAAE,EAAC;QAElD,mDAA0B;QAE1B,kDAAwB;QAExB,iDAEP;QAuDF,eAAU,GAAG,GAAG,EAAE;YAChB,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;gBACpB,KAAK,CAAC,SAAS,GAAG,kDAAsC,CAAC,SAAS,CAAC;YACrE,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,qBAAgB,GAAG,CAAC,EAClB,OAAO,EACP,aAAa,GAId,EAAE,EAAE;YACH,qCAAqC;YACrC,IAAI,aAAa,EAAE;gBACjB,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE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C,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAC3B,CAAC;QAEF,eAAe;QACf,IAAI,CAAC,iBAAiB,CAAC,+BAAmB,CAAC,CAAC;QAE5C,+EAA+E;QAC/E,8CAA8C;QAC9C,mFAAmF;QACnF,uBAAA,IAAI,uEAAyC,MAA7C,IAAI,CAA2C,CAAC;IAClD,CAAC;CAgRF;AAlVD,wDAkVC;;IAvJG,OAAO,CACL,IAAI,CAAC,eAAe,CAAC,IAAI,CACvB,iDAAiD,CAClD,EAAE,OAAO,IAAI,EAAE,CACjB,CAAC;AACJ,CAAC","sourcesContent":["import type { StateMetadata } from '@metamask/base-controller';\nimport type { BridgeClientId } from '@metamask/bridge-controller';\nimport { BRIDGE_PROD_API_BASE_URL } from '@metamask/bridge-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { numberToHex, type Hex } from '@metamask/utils';\n\nimport {\n BRIDGE_STATUS_CONTROLLER_NAME,\n DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE,\n REFRESH_INTERVAL_MS,\n} from './constants';\nimport { StatusTypes, type BridgeStatusControllerMessenger } from './types';\nimport type {\n BridgeStatusControllerState,\n StartPollingForBridgeTxStatusArgsSerialized,\n FetchFunction,\n} from './types';\nimport {\n fetchBridgeTxStatus,\n getStatusRequestWithSrcTxHash,\n} from './utils/bridge-status';\n\nconst metadata: StateMetadata<BridgeStatusControllerState> = {\n // We want to persist the bridge status state so that we can show the proper data for the Activity list\n // basically match the behavior of TransactionController\n txHistory: {\n persist: true,\n anonymous: false,\n },\n};\n\n/** The input to start polling for the {@link BridgeStatusController} */\ntype BridgeStatusPollingInput = FetchBridgeTxStatusArgs;\n\ntype SrcTxMetaId = string;\nexport type FetchBridgeTxStatusArgs = {\n bridgeTxMetaId: string;\n};\nexport class BridgeStatusController extends StaticIntervalPollingController<BridgeStatusPollingInput>()<\n typeof BRIDGE_STATUS_CONTROLLER_NAME,\n BridgeStatusControllerState,\n BridgeStatusControllerMessenger\n> {\n #pollingTokensByTxMetaId: Record<SrcTxMetaId, string> = {};\n\n readonly #clientId: BridgeClientId;\n\n readonly #fetchFn: FetchFunction;\n\n readonly #config: {\n customBridgeApiBaseUrl?: string;\n };\n\n constructor({\n messenger,\n state,\n clientId,\n fetchFn,\n config,\n }: {\n messenger: BridgeStatusControllerMessenger;\n state?: Partial<BridgeStatusControllerState>;\n clientId: BridgeClientId;\n fetchFn: FetchFunction;\n config?: {\n customBridgeApiBaseUrl?: string;\n };\n }) {\n super({\n name: BRIDGE_STATUS_CONTROLLER_NAME,\n metadata,\n messenger,\n // Restore the persisted state\n state: {\n ...DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE,\n ...state,\n },\n });\n\n this.#clientId = clientId;\n this.#fetchFn = fetchFn;\n this.#config = config ?? {};\n\n // Register action handlers\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:startPollingForBridgeTxStatus`,\n this.startPollingForBridgeTxStatus.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:wipeBridgeStatus`,\n this.wipeBridgeStatus.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:resetState`,\n this.resetState.bind(this),\n );\n\n // Set interval\n this.setIntervalLength(REFRESH_INTERVAL_MS);\n\n // If you close the extension, but keep the browser open, the polling continues\n // If you close the browser, the polling stops\n // Check for historyItems that do not have a status of complete and restart polling\n this.#restartPollingForIncompleteHistoryItems();\n }\n\n resetState = () => {\n this.update((state) => {\n state.txHistory = DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;\n });\n };\n\n wipeBridgeStatus = ({\n address,\n ignoreNetwork,\n }: {\n address: string;\n ignoreNetwork: boolean;\n }) => {\n // Wipe all networks for this address\n if (ignoreNetwork) {\n this.update((state) => {\n state.txHistory = DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;\n });\n } else {\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const selectedNetworkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n const selectedChainId = selectedNetworkClient.configuration.chainId;\n\n this.#wipeBridgeStatusByChainId(address, selectedChainId);\n }\n };\n\n readonly #restartPollingForIncompleteHistoryItems = () => {\n // Check for historyItems that do not have a status of complete and restart polling\n const { txHistory } = this.state;\n const historyItems = Object.values(txHistory);\n const incompleteHistoryItems = historyItems\n .filter(\n (historyItem) =>\n historyItem.status.status === StatusTypes.PENDING ||\n historyItem.status.status === StatusTypes.UNKNOWN,\n )\n .filter((historyItem) => {\n // Check if we are already polling this tx, if so, skip restarting polling for that\n const srcTxMetaId = historyItem.txMetaId;\n const pollingToken = this.#pollingTokensByTxMetaId[srcTxMetaId];\n return !pollingToken;\n });\n\n incompleteHistoryItems.forEach((historyItem) => {\n const bridgeTxMetaId = historyItem.txMetaId;\n\n // We manually call startPolling() here rather than go through startPollingForBridgeTxStatus()\n // because we don't want to overwrite the existing historyItem in state\n this.#pollingTokensByTxMetaId[bridgeTxMetaId] = this.startPolling({\n bridgeTxMetaId,\n });\n });\n };\n\n startPollingForBridgeTxStatus = (\n startPollingForBridgeTxStatusArgs: StartPollingForBridgeTxStatusArgsSerialized,\n ) => {\n const {\n bridgeTxMeta,\n statusRequest,\n quoteResponse,\n startTime,\n slippagePercentage,\n initialDestAssetBalance,\n targetContractAddress,\n } = startPollingForBridgeTxStatusArgs;\n const accountAddress = this.#getMultichainSelectedAccountAddress();\n // Write all non-status fields to state so we can reference the quote in Activity list without the Bridge API\n // We know it's in progress but not the exact status yet\n const txHistoryItem = {\n txMetaId: bridgeTxMeta.id,\n quote: quoteResponse.quote,\n startTime,\n estimatedProcessingTimeInSeconds:\n quoteResponse.estimatedProcessingTimeInSeconds,\n slippagePercentage,\n pricingData: {\n amountSent: quoteResponse.sentAmount.amount,\n amountSentInUsd: quoteResponse.sentAmount.usd ?? undefined,\n quotedGasInUsd: quoteResponse.gasFee.usd ?? undefined,\n quotedReturnInUsd: quoteResponse.toTokenAmount.usd ?? undefined,\n },\n initialDestAssetBalance,\n targetContractAddress,\n account: accountAddress,\n status: {\n // We always have a PENDING status when we start polling for a tx, don't need the Bridge API for that\n // Also we know the bare minimum fields for status at this point in time\n status: StatusTypes.PENDING,\n srcChain: {\n chainId: statusRequest.srcChainId,\n txHash: statusRequest.srcTxHash,\n },\n },\n hasApprovalTx: Boolean(quoteResponse.approval),\n };\n this.update((state) => {\n // Use the txMeta.id as the key so we can reference the txMeta in TransactionController\n state.txHistory[bridgeTxMeta.id] = txHistoryItem;\n });\n\n this.#pollingTokensByTxMetaId[bridgeTxMeta.id] = this.startPolling({\n bridgeTxMetaId: bridgeTxMeta.id,\n });\n };\n\n // This will be called after you call this.startPolling()\n // The args passed in are the args you passed in to startPolling()\n _executePoll = async (pollingInput: BridgeStatusPollingInput) => {\n await this.#fetchBridgeTxStatus(pollingInput);\n };\n\n #getMultichainSelectedAccountAddress() {\n return (\n this.messagingSystem.call(\n 'AccountsController:getSelectedMultichainAccount',\n )?.address ?? ''\n );\n }\n\n readonly #fetchBridgeTxStatus = async ({\n bridgeTxMetaId,\n }: FetchBridgeTxStatusArgs) => {\n const { txHistory } = this.state;\n\n try {\n // We try here because we receive 500 errors from Bridge API if we try to fetch immediately after submitting the source tx\n // Oddly mostly happens on Optimism, never on Arbitrum. By the 2nd fetch, the Bridge API responds properly.\n // Also srcTxHash may not be available immediately for STX, so we don't want to fetch in those cases\n const historyItem = txHistory[bridgeTxMetaId];\n const srcTxHash = this.#getSrcTxHash(bridgeTxMetaId);\n if (!srcTxHash) {\n return;\n }\n\n this.#updateSrcTxHash(bridgeTxMetaId, srcTxHash);\n\n const statusRequest = getStatusRequestWithSrcTxHash(\n historyItem.quote,\n srcTxHash,\n );\n const status = await fetchBridgeTxStatus(\n statusRequest,\n this.#clientId,\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n );\n const newBridgeHistoryItem = {\n ...historyItem,\n status,\n completionTime:\n status.status === StatusTypes.COMPLETE ||\n status.status === StatusTypes.FAILED\n ? Date.now()\n : undefined, // TODO make this more accurate by looking up dest txHash block time\n };\n\n // No need to purge these on network change or account change, TransactionController does not purge either.\n // TODO In theory we can skip checking status if it's not the current account/network\n // we need to keep track of the account that this is associated with as well so that we don't show it in Activity list for other accounts\n // First stab at this will not stop polling when you are on a different account\n this.update((state) => {\n state.txHistory[bridgeTxMetaId] = newBridgeHistoryItem;\n });\n\n const pollingToken = this.#pollingTokensByTxMetaId[bridgeTxMetaId];\n\n if (\n (status.status === StatusTypes.COMPLETE ||\n status.status === StatusTypes.FAILED) &&\n pollingToken\n ) {\n this.stopPollingByPollingToken(pollingToken);\n\n if (status.status === StatusTypes.COMPLETE) {\n this.messagingSystem.publish(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionComplete`,\n { bridgeHistoryItem: newBridgeHistoryItem },\n );\n }\n if (status.status === StatusTypes.FAILED) {\n this.messagingSystem.publish(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionFailed`,\n { bridgeHistoryItem: newBridgeHistoryItem },\n );\n }\n }\n } catch (e) {\n console.log('Failed to fetch bridge tx status', e);\n }\n };\n\n readonly #getSrcTxHash = (bridgeTxMetaId: string): string | undefined => {\n const { txHistory } = this.state;\n // Prefer the srcTxHash from bridgeStatusState so we don't have to l ook up in TransactionController\n // But it is possible to have bridgeHistoryItem in state without the srcTxHash yet when it is an STX\n const srcTxHash = txHistory[bridgeTxMetaId].status.srcChain.txHash;\n\n if (srcTxHash) {\n return srcTxHash;\n }\n\n // Look up in TransactionController if txMeta has been updated with the srcTxHash\n const txControllerState = this.messagingSystem.call(\n 'TransactionController:getState',\n );\n const txMeta = txControllerState.transactions.find(\n (tx) => tx.id === bridgeTxMetaId,\n );\n return txMeta?.hash;\n };\n\n readonly #updateSrcTxHash = (bridgeTxMetaId: string, srcTxHash: string) => {\n const { txHistory } = this.state;\n if (txHistory[bridgeTxMetaId].status.srcChain.txHash) {\n return;\n }\n\n this.update((state) => {\n state.txHistory[bridgeTxMetaId].status.srcChain.txHash = srcTxHash;\n });\n };\n\n // Wipes the bridge status for the given address and chainId\n // Will match only source chainId to the selectedChainId\n readonly #wipeBridgeStatusByChainId = (\n address: string,\n selectedChainId: Hex,\n ) => {\n const sourceTxMetaIdsToDelete = Object.keys(this.state.txHistory).filter(\n (txMetaId) => {\n const bridgeHistoryItem = this.state.txHistory[txMetaId];\n\n const hexSourceChainId = numberToHex(\n bridgeHistoryItem.quote.srcChainId,\n );\n\n return (\n bridgeHistoryItem.account === address &&\n hexSourceChainId === selectedChainId\n );\n },\n );\n\n sourceTxMetaIdsToDelete.forEach((sourceTxMetaId) => {\n const pollingToken = this.#pollingTokensByTxMetaId[sourceTxMetaId];\n\n if (pollingToken) {\n this.stopPollingByPollingToken(\n this.#pollingTokensByTxMetaId[sourceTxMetaId],\n );\n }\n });\n\n this.update((state) => {\n state.txHistory = sourceTxMetaIdsToDelete.reduce(\n (acc, sourceTxMetaId) => {\n delete acc[sourceTxMetaId];\n return acc;\n },\n state.txHistory,\n );\n });\n };\n}\n"]}
1
+ {"version":3,"file":"bridge-status-controller.cjs","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,mEAOqC;AAMrC,iEAAmD;AACnD,uDAAuD;AACvD,qEAA+E;AAK/E,6EAI0C;AAE1C,2CAAwD;AACxD,+CAAyC;AAEzC,+CAKqB;AACrB,uCAA4E;AAQ5E,6DAG+B;AAC/B,yCAAgD;AAChD,yDAM6B;AAC7B,yDAAuD;AAEvD,MAAM,QAAQ,GAA+C;IAC3D,uGAAuG;IACvG,wDAAwD;IACxD,SAAS,EAAE;QACT,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AASF,MAAa,sBAAuB,SAAQ,IAAA,oDAA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AC,eAAe,CAAC,qBAAqB,CACxC,GAAG,yCAA6B,aAAa,EAC7C,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAC3B,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,yCAA6B,WAAW,EAC3C,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CACzB,CAAC;QAEF,eAAe;QACf,IAAI,CAAC,iBAAiB,CAAC,+BAAmB,CAAC,CAAC;QAE5C,+EAA+E;QAC/E,8CAA8C;QAC9C,mFAAmF;QACnF,uBAAA,IAAI,uEAAyC,MAA7C,IAAI,CAA2C,CAAC;IAClD,CAAC;CAqoBF;AA7tBD,wDA6tBC;;IArgBG,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAC9B,iDAAiD,CAClD,CAAC;AACJ,CAAC;IAGC,OAAO,uBAAA,IAAI,+FAA8B,MAAlC,IAAI,CAAgC,EAAE,OAAO,IAAI,EAAE,CAAC;AAC7D,CAAC","sourcesContent":["import type { StateMetadata } from '@metamask/base-controller';\nimport {\n formatChainIdToHex,\n getEthUsdtResetData,\n isEthUsdt,\n isNativeAddress,\n isSolanaChainId,\n type QuoteResponse,\n} from '@metamask/bridge-controller';\nimport type {\n BridgeAsset,\n QuoteMetadata,\n TxData,\n} from '@metamask/bridge-controller';\nimport { toHex } from '@metamask/controller-utils';\nimport { EthAccountType } from '@metamask/keyring-api';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n TransactionController,\n TransactionParams,\n} from '@metamask/transaction-controller';\nimport {\n TransactionStatus,\n TransactionType,\n type TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { UserOperationController } from '@metamask/user-operation-controller';\nimport { numberToHex, type Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n BRIDGE_PROD_API_BASE_URL,\n BRIDGE_STATUS_CONTROLLER_NAME,\n DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE,\n REFRESH_INTERVAL_MS,\n} from './constants';\nimport { StatusTypes, type BridgeStatusControllerMessenger } from './types';\nimport type {\n BridgeStatusControllerState,\n StartPollingForBridgeTxStatusArgsSerialized,\n FetchFunction,\n BridgeClientId,\n SolanaTransactionMeta,\n} from './types';\nimport {\n fetchBridgeTxStatus,\n getStatusRequestWithSrcTxHash,\n} from './utils/bridge-status';\nimport { getTxGasEstimates } from './utils/gas';\nimport {\n getKeyringRequest,\n getStatusRequestParams,\n getTxMetaFields,\n handleLineaDelay,\n handleSolanaTxResponse,\n} from './utils/transaction';\nimport { generateActionId } from './utils/transaction';\n\nconst metadata: StateMetadata<BridgeStatusControllerState> = {\n // We want to persist the bridge status state so that we can show the proper data for the Activity list\n // basically match the behavior of TransactionController\n txHistory: {\n persist: true,\n anonymous: false,\n },\n};\n\n/** The input to start polling for the {@link BridgeStatusController} */\ntype BridgeStatusPollingInput = FetchBridgeTxStatusArgs;\n\ntype SrcTxMetaId = string;\nexport type FetchBridgeTxStatusArgs = {\n bridgeTxMetaId: string;\n};\nexport class BridgeStatusController extends StaticIntervalPollingController<BridgeStatusPollingInput>()<\n typeof BRIDGE_STATUS_CONTROLLER_NAME,\n BridgeStatusControllerState,\n BridgeStatusControllerMessenger\n> {\n #pollingTokensByTxMetaId: Record<SrcTxMetaId, string> = {};\n\n readonly #clientId: BridgeClientId;\n\n readonly #fetchFn: FetchFunction;\n\n readonly #config: {\n customBridgeApiBaseUrl: string;\n };\n\n readonly #addTransactionFn: typeof TransactionController.prototype.addTransaction;\n\n readonly #estimateGasFeeFn: typeof TransactionController.prototype.estimateGasFee;\n\n readonly #addUserOperationFromTransactionFn?: typeof UserOperationController.prototype.addUserOperationFromTransaction;\n\n constructor({\n messenger,\n state,\n clientId,\n fetchFn,\n addTransactionFn,\n addUserOperationFromTransactionFn,\n estimateGasFeeFn,\n config,\n }: {\n messenger: BridgeStatusControllerMessenger;\n state?: Partial<BridgeStatusControllerState>;\n clientId: BridgeClientId;\n fetchFn: FetchFunction;\n addTransactionFn: typeof TransactionController.prototype.addTransaction;\n estimateGasFeeFn: typeof TransactionController.prototype.estimateGasFee;\n addUserOperationFromTransactionFn?: typeof UserOperationController.prototype.addUserOperationFromTransaction;\n config?: {\n customBridgeApiBaseUrl?: string;\n };\n }) {\n super({\n name: BRIDGE_STATUS_CONTROLLER_NAME,\n metadata,\n messenger,\n // Restore the persisted state\n state: {\n ...DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE,\n ...state,\n },\n });\n\n this.#clientId = clientId;\n this.#fetchFn = fetchFn;\n this.#addTransactionFn = addTransactionFn;\n this.#addUserOperationFromTransactionFn = addUserOperationFromTransactionFn;\n this.#estimateGasFeeFn = estimateGasFeeFn;\n this.#config = {\n customBridgeApiBaseUrl:\n config?.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n };\n\n // Register action handlers\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:startPollingForBridgeTxStatus`,\n this.startPollingForBridgeTxStatus.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:wipeBridgeStatus`,\n this.wipeBridgeStatus.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:resetState`,\n this.resetState.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:submitTx`,\n this.submitTx.bind(this),\n );\n\n // Set interval\n this.setIntervalLength(REFRESH_INTERVAL_MS);\n\n // If you close the extension, but keep the browser open, the polling continues\n // If you close the browser, the polling stops\n // Check for historyItems that do not have a status of complete and restart polling\n this.#restartPollingForIncompleteHistoryItems();\n }\n\n resetState = () => {\n this.update((state) => {\n state.txHistory = DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;\n });\n };\n\n wipeBridgeStatus = ({\n address,\n ignoreNetwork,\n }: {\n address: string;\n ignoreNetwork: boolean;\n }) => {\n // Wipe all networks for this address\n if (ignoreNetwork) {\n this.update((state) => {\n state.txHistory = DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;\n });\n } else {\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const selectedNetworkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n const selectedChainId = selectedNetworkClient.configuration.chainId;\n\n this.#wipeBridgeStatusByChainId(address, selectedChainId);\n }\n };\n\n readonly #restartPollingForIncompleteHistoryItems = () => {\n // Check for historyItems that do not have a status of complete and restart polling\n const { txHistory } = this.state;\n const historyItems = Object.values(txHistory);\n const incompleteHistoryItems = historyItems\n .filter(\n (historyItem) =>\n historyItem.status.status === StatusTypes.PENDING ||\n historyItem.status.status === StatusTypes.UNKNOWN,\n )\n .filter((historyItem) => {\n // Check if we are already polling this tx, if so, skip restarting polling for that\n const srcTxMetaId = historyItem.txMetaId;\n const pollingToken = this.#pollingTokensByTxMetaId[srcTxMetaId];\n return !pollingToken;\n });\n\n incompleteHistoryItems.forEach((historyItem) => {\n const bridgeTxMetaId = historyItem.txMetaId;\n\n // We manually call startPolling() here rather than go through startPollingForBridgeTxStatus()\n // because we don't want to overwrite the existing historyItem in state\n this.#pollingTokensByTxMetaId[bridgeTxMetaId] = this.startPolling({\n bridgeTxMetaId,\n });\n });\n };\n\n /**\n * Starts polling for the bridge tx status\n *\n * @param startPollingForBridgeTxStatusArgs - The args to start polling for the bridge tx status\n */\n startPollingForBridgeTxStatus = (\n startPollingForBridgeTxStatusArgs: StartPollingForBridgeTxStatusArgsSerialized,\n ) => {\n const {\n bridgeTxMeta,\n statusRequest,\n quoteResponse,\n startTime,\n slippagePercentage,\n initialDestAssetBalance,\n targetContractAddress,\n approvalTxId,\n } = startPollingForBridgeTxStatusArgs;\n const accountAddress = this.#getMultichainSelectedAccountAddress();\n // Write all non-status fields to state so we can reference the quote in Activity list without the Bridge API\n // We know it's in progress but not the exact status yet\n const txHistoryItem = {\n txMetaId: bridgeTxMeta.id,\n quote: quoteResponse.quote,\n startTime,\n estimatedProcessingTimeInSeconds:\n quoteResponse.estimatedProcessingTimeInSeconds,\n slippagePercentage,\n pricingData: {\n amountSent: quoteResponse.sentAmount.amount,\n amountSentInUsd: quoteResponse.sentAmount.usd ?? undefined,\n quotedGasInUsd: quoteResponse.gasFee.usd ?? undefined,\n quotedReturnInUsd: quoteResponse.toTokenAmount.usd ?? undefined,\n },\n initialDestAssetBalance,\n targetContractAddress,\n account: accountAddress,\n status: {\n // We always have a PENDING status when we start polling for a tx, don't need the Bridge API for that\n // Also we know the bare minimum fields for status at this point in time\n status: StatusTypes.PENDING,\n srcChain: {\n chainId: statusRequest.srcChainId,\n txHash: statusRequest.srcTxHash,\n },\n },\n hasApprovalTx: Boolean(quoteResponse.approval),\n approvalTxId,\n };\n this.update((state) => {\n // Use the txMeta.id as the key so we can reference the txMeta in TransactionController\n state.txHistory[bridgeTxMeta.id] = txHistoryItem;\n });\n\n this.#pollingTokensByTxMetaId[bridgeTxMeta.id] = this.startPolling({\n bridgeTxMetaId: bridgeTxMeta.id,\n });\n };\n\n // This will be called after you call this.startPolling()\n // The args passed in are the args you passed in to startPolling()\n _executePoll = async (pollingInput: BridgeStatusPollingInput) => {\n await this.#fetchBridgeTxStatus(pollingInput);\n };\n\n #getMultichainSelectedAccount() {\n return this.messagingSystem.call(\n 'AccountsController:getSelectedMultichainAccount',\n );\n }\n\n #getMultichainSelectedAccountAddress() {\n return this.#getMultichainSelectedAccount()?.address ?? '';\n }\n\n readonly #fetchBridgeTxStatus = async ({\n bridgeTxMetaId,\n }: FetchBridgeTxStatusArgs) => {\n const { txHistory } = this.state;\n\n try {\n // We try here because we receive 500 errors from Bridge API if we try to fetch immediately after submitting the source tx\n // Oddly mostly happens on Optimism, never on Arbitrum. By the 2nd fetch, the Bridge API responds properly.\n // Also srcTxHash may not be available immediately for STX, so we don't want to fetch in those cases\n const historyItem = txHistory[bridgeTxMetaId];\n const srcTxHash = this.#getSrcTxHash(bridgeTxMetaId);\n if (!srcTxHash) {\n return;\n }\n\n this.#updateSrcTxHash(bridgeTxMetaId, srcTxHash);\n\n const statusRequest = getStatusRequestWithSrcTxHash(\n historyItem.quote,\n srcTxHash,\n );\n const status = await fetchBridgeTxStatus(\n statusRequest,\n this.#clientId,\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl,\n );\n const newBridgeHistoryItem = {\n ...historyItem,\n status,\n completionTime:\n status.status === StatusTypes.COMPLETE ||\n status.status === StatusTypes.FAILED\n ? Date.now()\n : undefined, // TODO make this more accurate by looking up dest txHash block time\n };\n\n // No need to purge these on network change or account change, TransactionController does not purge either.\n // TODO In theory we can skip checking status if it's not the current account/network\n // we need to keep track of the account that this is associated with as well so that we don't show it in Activity list for other accounts\n // First stab at this will not stop polling when you are on a different account\n this.update((state) => {\n state.txHistory[bridgeTxMetaId] = newBridgeHistoryItem;\n });\n\n const pollingToken = this.#pollingTokensByTxMetaId[bridgeTxMetaId];\n\n if (\n (status.status === StatusTypes.COMPLETE ||\n status.status === StatusTypes.FAILED) &&\n pollingToken\n ) {\n this.stopPollingByPollingToken(pollingToken);\n\n if (status.status === StatusTypes.COMPLETE) {\n this.messagingSystem.publish(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionComplete`,\n { bridgeHistoryItem: newBridgeHistoryItem },\n );\n }\n if (status.status === StatusTypes.FAILED) {\n this.messagingSystem.publish(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionFailed`,\n { bridgeHistoryItem: newBridgeHistoryItem },\n );\n }\n }\n } catch (e) {\n console.log('Failed to fetch bridge tx status', e);\n }\n };\n\n readonly #getSrcTxHash = (bridgeTxMetaId: string): string | undefined => {\n const { txHistory } = this.state;\n // Prefer the srcTxHash from bridgeStatusState so we don't have to l ook up in TransactionController\n // But it is possible to have bridgeHistoryItem in state without the srcTxHash yet when it is an STX\n const srcTxHash = txHistory[bridgeTxMetaId].status.srcChain.txHash;\n\n if (srcTxHash) {\n return srcTxHash;\n }\n\n // Look up in TransactionController if txMeta has been updated with the srcTxHash\n const txControllerState = this.messagingSystem.call(\n 'TransactionController:getState',\n );\n const txMeta = txControllerState.transactions.find(\n (tx: TransactionMeta) => tx.id === bridgeTxMetaId,\n );\n return txMeta?.hash;\n };\n\n readonly #updateSrcTxHash = (bridgeTxMetaId: string, srcTxHash: string) => {\n const { txHistory } = this.state;\n if (txHistory[bridgeTxMetaId].status.srcChain.txHash) {\n return;\n }\n\n this.update((state) => {\n state.txHistory[bridgeTxMetaId].status.srcChain.txHash = srcTxHash;\n });\n };\n\n // Wipes the bridge status for the given address and chainId\n // Will match only source chainId to the selectedChainId\n readonly #wipeBridgeStatusByChainId = (\n address: string,\n selectedChainId: Hex,\n ) => {\n const sourceTxMetaIdsToDelete = Object.keys(this.state.txHistory).filter(\n (txMetaId) => {\n const bridgeHistoryItem = this.state.txHistory[txMetaId];\n\n const hexSourceChainId = numberToHex(\n bridgeHistoryItem.quote.srcChainId,\n );\n\n return (\n bridgeHistoryItem.account === address &&\n hexSourceChainId === selectedChainId\n );\n },\n );\n\n sourceTxMetaIdsToDelete.forEach((sourceTxMetaId) => {\n const pollingToken = this.#pollingTokensByTxMetaId[sourceTxMetaId];\n\n if (pollingToken) {\n this.stopPollingByPollingToken(\n this.#pollingTokensByTxMetaId[sourceTxMetaId],\n );\n }\n });\n\n this.update((state) => {\n state.txHistory = sourceTxMetaIdsToDelete.reduce(\n (acc, sourceTxMetaId) => {\n delete acc[sourceTxMetaId];\n return acc;\n },\n state.txHistory,\n );\n });\n };\n\n /**\n * ******************************************************\n * TX SUBMISSION HANDLING\n *******************************************************\n */\n\n /**\n * Submits the transaction to the snap using the keyring rpc method\n * This adds an approval tx to the ApprovalsController in the background\n * The client needs to handle the approval tx by redirecting to the confirmation page with the approvalTxId in the URL\n *\n * @param quoteResponse - The quote response\n * @param quoteResponse.quote - The quote\n * @returns The transaction meta\n */\n readonly #handleSolanaTx = async (\n quoteResponse: QuoteResponse<string> & QuoteMetadata,\n ) => {\n const selectedAccount = this.#getMultichainSelectedAccount();\n if (!selectedAccount) {\n throw new Error(\n 'Failed to submit cross-chain swap transaction: undefined multichain account',\n );\n }\n if (\n !selectedAccount.metadata?.snap?.id ||\n !selectedAccount.options?.scope\n ) {\n throw new Error(\n 'Failed to submit cross-chain swap transaction: undefined snap id or scope',\n );\n }\n const keyringRequest = getKeyringRequest(quoteResponse, selectedAccount);\n const keyringResponse = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n keyringRequest,\n )) as string | { result: Record<string, string> };\n\n // The extension client actually redirects before it can do anytyhing with this meta\n const txMeta = handleSolanaTxResponse(\n keyringResponse,\n quoteResponse,\n selectedAccount,\n );\n\n // TODO remove this eventually, just returning it now to match extension behavior\n // OR if the snap can propagate the snapRequestId or keyringReqId to the ApprovalsController, this can return the approvalTxId instead and clients won't need to subscribe to the ApprovalsController state to redirect\n return txMeta;\n };\n\n readonly #waitForHashAndReturnFinalTxMeta = async (\n hashPromise?:\n | Awaited<ReturnType<TransactionController['addTransaction']>>['result']\n | Awaited<\n ReturnType<UserOperationController['addUserOperationFromTransaction']>\n >['hash'],\n ): Promise<TransactionMeta | undefined> => {\n const transactionHash = await hashPromise;\n const finalTransactionMeta: TransactionMeta | undefined =\n this.messagingSystem\n .call('TransactionController:getState')\n .transactions.find(\n (tx: TransactionMeta) => tx.hash === transactionHash,\n );\n return finalTransactionMeta;\n };\n\n readonly #handleApprovalTx = async (\n quoteResponse: QuoteResponse<string | TxData> & QuoteMetadata,\n ): Promise<TransactionMeta | undefined> => {\n if (quoteResponse.approval) {\n await this.#handleUSDTAllowanceReset(quoteResponse);\n const approvalTxMeta = await this.#handleEvmTransaction(\n TransactionType.bridgeApproval,\n quoteResponse.approval,\n quoteResponse,\n );\n if (!approvalTxMeta) {\n throw new Error(\n 'Failed to submit bridge tx: approval txMeta is undefined',\n );\n }\n\n await handleLineaDelay(quoteResponse);\n return approvalTxMeta;\n }\n return undefined;\n };\n\n readonly #handleEvmSmartTransaction = async (\n trade: TxData,\n quoteResponse: Omit<QuoteResponse, 'approval' | 'trade'> & QuoteMetadata,\n approvalTxId?: string,\n ) => {\n return await this.#handleEvmTransaction(\n TransactionType.bridge,\n trade,\n quoteResponse,\n approvalTxId,\n false, // Set to false to indicate we don't want to wait for hash\n );\n };\n\n /**\n * Submits an EVM transaction to the TransactionController\n *\n * @param transactionType - The type of transaction to submit\n * @param trade - The trade data to confirm\n * @param quoteResponse - The quote response\n * @param quoteResponse.quote - The quote\n * @param approvalTxId - The tx id of the approval tx\n * @param shouldWaitForHash - Whether to wait for the hash of the transaction\n * @returns The transaction meta\n */\n readonly #handleEvmTransaction = async (\n transactionType: TransactionType,\n trade: TxData,\n quoteResponse: Omit<QuoteResponse, 'approval' | 'trade'> & QuoteMetadata,\n approvalTxId?: string,\n shouldWaitForHash = true,\n ): Promise<TransactionMeta | undefined> => {\n const actionId = generateActionId().toString();\n\n const selectedAccount = this.messagingSystem.call(\n 'AccountsController:getAccountByAddress',\n trade.from,\n );\n if (!selectedAccount) {\n throw new Error(\n 'Failed to submit cross-chain swap transaction: unknown account in trade data',\n );\n }\n const hexChainId = formatChainIdToHex(trade.chainId);\n const networkClientId = this.messagingSystem.call(\n 'NetworkController:findNetworkClientIdByChainId',\n hexChainId,\n );\n\n const requestOptions = {\n actionId,\n networkClientId,\n requireApproval: false,\n type: transactionType,\n origin: 'metamask',\n };\n const transactionParams: Parameters<\n TransactionController['addTransaction']\n >[0] = {\n ...trade,\n chainId: hexChainId,\n gasLimit: trade.gasLimit?.toString(),\n gas: trade.gasLimit?.toString(),\n };\n const transactionParamsWithMaxGas: TransactionParams = {\n ...transactionParams,\n ...(await this.#calculateGasFees(\n transactionParams,\n networkClientId,\n hexChainId,\n )),\n };\n\n let result:\n | Awaited<ReturnType<TransactionController['addTransaction']>>['result']\n | Awaited<\n ReturnType<UserOperationController['addUserOperationFromTransaction']>\n >['hash']\n | undefined;\n let transactionMeta: TransactionMeta | undefined;\n\n const isSmartContractAccount =\n selectedAccount.type === EthAccountType.Erc4337;\n if (isSmartContractAccount && this.#addUserOperationFromTransactionFn) {\n const smartAccountTxResult =\n await this.#addUserOperationFromTransactionFn(\n transactionParamsWithMaxGas,\n requestOptions,\n );\n result = smartAccountTxResult.transactionHash;\n transactionMeta = {\n ...requestOptions,\n chainId: hexChainId,\n txParams: transactionParamsWithMaxGas,\n time: Date.now(),\n id: smartAccountTxResult.id,\n status: TransactionStatus.confirmed,\n };\n } else {\n const addTransactionResult = await this.#addTransactionFn(\n transactionParamsWithMaxGas,\n requestOptions,\n );\n result = addTransactionResult.result;\n transactionMeta = addTransactionResult.transactionMeta;\n }\n\n if (shouldWaitForHash) {\n return await this.#waitForHashAndReturnFinalTxMeta(result);\n }\n\n // TODO why is this needed?\n // Note that updateTransaction doesn't actually error if you add fields that don't conform the to the txMeta type\n // they will be there at runtime, but you just don't get any type safety checks on them\n // const fieldsToAddToTxMeta = getTxMetaFields(quoteResponse, approvalTxId);\n // dispatch(updateTransaction(completeTxMeta);\n\n return {\n ...getTxMetaFields(quoteResponse, approvalTxId),\n ...transactionMeta,\n };\n };\n\n // Only adds tokens if the source or dest chain is an EVM chain bc non-evm tokens\n // are detected by the multichain asset controllers\n readonly #addTokens = (asset: BridgeAsset) => {\n if (isNativeAddress(asset.address) || isSolanaChainId(asset.chainId)) {\n return;\n }\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.messagingSystem.call(\n 'TokensController:addDetectedTokens',\n [\n {\n address: asset.address,\n decimals: asset.decimals,\n image: asset.iconUrl,\n name: asset.name,\n symbol: asset.symbol,\n },\n ],\n {\n chainId: formatChainIdToHex(asset.chainId),\n selectedAddress: this.#getMultichainSelectedAccountAddress(),\n },\n );\n };\n\n readonly #handleUSDTAllowanceReset = async (\n quoteResponse: QuoteResponse<TxData | string> & QuoteMetadata,\n ) => {\n const hexChainId = formatChainIdToHex(quoteResponse.quote.srcChainId);\n if (\n quoteResponse.approval &&\n isEthUsdt(hexChainId, quoteResponse.quote.srcAsset.address)\n ) {\n const allowance = new BigNumber(\n await this.messagingSystem.call(\n 'BridgeController:getBridgeERC20Allowance',\n quoteResponse.quote.srcAsset.address,\n hexChainId,\n ),\n );\n const shouldResetApproval =\n allowance.lt(quoteResponse.sentAmount.amount) && allowance.gt(0);\n if (shouldResetApproval) {\n await this.#handleEvmTransaction(\n TransactionType.bridgeApproval,\n { ...quoteResponse.approval, data: getEthUsdtResetData() },\n quoteResponse,\n );\n }\n }\n };\n\n readonly #calculateGasFees = async (\n transactionParams: TransactionParams,\n networkClientId: string,\n chainId: Hex,\n ) => {\n const { gasFeeEstimates } = this.messagingSystem.call(\n 'GasFeeController:getState',\n );\n const { estimates: txGasFeeEstimates } = await this.#estimateGasFeeFn({\n transactionParams,\n chainId,\n networkClientId,\n });\n const { maxFeePerGas, maxPriorityFeePerGas } = getTxGasEstimates({\n networkGasFeeEstimates: gasFeeEstimates,\n txGasFeeEstimates,\n });\n const maxGasLimit = toHex(transactionParams.gas ?? 0);\n\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n gas: maxGasLimit,\n };\n };\n\n /**\n * Submits a cross-chain swap transaction\n *\n * @param quoteResponse - The quote response\n * @param isStxEnabledOnClient - Whether smart transactions are enabled on the client, for example the getSmartTransactionsEnabled selector value from the extension\n * @returns The transaction meta\n */\n submitTx = async (\n quoteResponse: QuoteResponse<TxData | string> & QuoteMetadata,\n isStxEnabledOnClient: boolean,\n ) => {\n let txMeta: (TransactionMeta & Partial<SolanaTransactionMeta>) | undefined;\n // Submit SOLANA tx\n if (\n isSolanaChainId(quoteResponse.quote.srcChainId) &&\n typeof quoteResponse.trade === 'string'\n ) {\n txMeta = await this.#handleSolanaTx(\n quoteResponse as QuoteResponse<string> & QuoteMetadata,\n );\n }\n // Submit EVM tx\n let approvalTime: number | undefined, approvalTxId: string | undefined;\n if (\n !isSolanaChainId(quoteResponse.quote.srcChainId) &&\n typeof quoteResponse.trade !== 'string'\n ) {\n // Set approval time and id if an approval tx is needed\n const approvalTxMeta = await this.#handleApprovalTx(quoteResponse);\n approvalTime = approvalTxMeta?.time;\n approvalTxId = approvalTxMeta?.id;\n // Handle smart transactions if enabled\n if (isStxEnabledOnClient) {\n txMeta = await this.#handleEvmSmartTransaction(\n quoteResponse.trade,\n quoteResponse,\n approvalTxId,\n );\n } else {\n txMeta = await this.#handleEvmTransaction(\n TransactionType.bridge,\n quoteResponse.trade,\n quoteResponse,\n approvalTxId,\n );\n }\n }\n\n if (!txMeta) {\n throw new Error('Failed to submit bridge tx: txMeta is undefined');\n }\n\n try {\n // Start polling for bridge tx status\n this.startPollingForBridgeTxStatus({\n bridgeTxMeta: txMeta, // Only the id field is used by the BridgeStatusController\n statusRequest: {\n ...getStatusRequestParams(quoteResponse),\n srcTxHash: txMeta.hash,\n },\n quoteResponse,\n slippagePercentage: 0, // TODO include slippage provided by quote if using dynamic slippage, or slippage from quote request\n startTime: approvalTime ?? Date.now(),\n approvalTxId,\n });\n // Add tokens to the token list\n this.#addTokens(quoteResponse.quote.srcAsset);\n this.#addTokens(quoteResponse.quote.destAsset);\n } catch {\n // Ignore errors here, we don't want to crash the app if this fails and tx submission succeeds\n }\n return txMeta;\n };\n}\n"]}
@@ -1,7 +1,11 @@
1
- import type { BridgeClientId } from "@metamask/bridge-controller";
1
+ import { type QuoteResponse } from "@metamask/bridge-controller";
2
+ import type { QuoteMetadata, TxData } from "@metamask/bridge-controller";
3
+ import type { TransactionController } from "@metamask/transaction-controller";
4
+ import { type TransactionMeta } from "@metamask/transaction-controller";
5
+ import type { UserOperationController } from "@metamask/user-operation-controller";
2
6
  import { BRIDGE_STATUS_CONTROLLER_NAME } from "./constants.cjs";
3
7
  import { type BridgeStatusControllerMessenger } from "./types.cjs";
4
- import type { BridgeStatusControllerState, StartPollingForBridgeTxStatusArgsSerialized, FetchFunction } from "./types.cjs";
8
+ import type { BridgeStatusControllerState, StartPollingForBridgeTxStatusArgsSerialized, FetchFunction, BridgeClientId, SolanaTransactionMeta } from "./types.cjs";
5
9
  /** The input to start polling for the {@link BridgeStatusController} */
6
10
  type BridgeStatusPollingInput = FetchBridgeTxStatusArgs;
7
11
  export type FetchBridgeTxStatusArgs = {
@@ -24,11 +28,14 @@ declare const BridgeStatusController_base: (abstract new (...args: any[]) => {
24
28
  }) & typeof import("@metamask/base-controller").BaseController;
25
29
  export declare class BridgeStatusController extends BridgeStatusController_base<typeof BRIDGE_STATUS_CONTROLLER_NAME, BridgeStatusControllerState, BridgeStatusControllerMessenger> {
26
30
  #private;
27
- constructor({ messenger, state, clientId, fetchFn, config, }: {
31
+ constructor({ messenger, state, clientId, fetchFn, addTransactionFn, addUserOperationFromTransactionFn, estimateGasFeeFn, config, }: {
28
32
  messenger: BridgeStatusControllerMessenger;
29
33
  state?: Partial<BridgeStatusControllerState>;
30
34
  clientId: BridgeClientId;
31
35
  fetchFn: FetchFunction;
36
+ addTransactionFn: typeof TransactionController.prototype.addTransaction;
37
+ estimateGasFeeFn: typeof TransactionController.prototype.estimateGasFee;
38
+ addUserOperationFromTransactionFn?: typeof UserOperationController.prototype.addUserOperationFromTransaction;
32
39
  config?: {
33
40
  customBridgeApiBaseUrl?: string;
34
41
  };
@@ -38,8 +45,21 @@ export declare class BridgeStatusController extends BridgeStatusController_base<
38
45
  address: string;
39
46
  ignoreNetwork: boolean;
40
47
  }) => void;
48
+ /**
49
+ * Starts polling for the bridge tx status
50
+ *
51
+ * @param startPollingForBridgeTxStatusArgs - The args to start polling for the bridge tx status
52
+ */
41
53
  startPollingForBridgeTxStatus: (startPollingForBridgeTxStatusArgs: StartPollingForBridgeTxStatusArgsSerialized) => void;
42
54
  _executePoll: (pollingInput: BridgeStatusPollingInput) => Promise<void>;
55
+ /**
56
+ * Submits a cross-chain swap transaction
57
+ *
58
+ * @param quoteResponse - The quote response
59
+ * @param isStxEnabledOnClient - Whether smart transactions are enabled on the client, for example the getSmartTransactionsEnabled selector value from the extension
60
+ * @returns The transaction meta
61
+ */
62
+ submitTx: (quoteResponse: QuoteResponse<TxData | string> & QuoteMetadata, isStxEnabledOnClient: boolean) => Promise<TransactionMeta & Partial<SolanaTransactionMeta>>;
43
63
  }
44
64
  export {};
45
65
  //# sourceMappingURL=bridge-status-controller.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bridge-status-controller.d.cts","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,oCAAoC;AAKlE,OAAO,EACL,6BAA6B,EAG9B,wBAAoB;AACrB,OAAO,EAAe,KAAK,+BAA+B,EAAE,oBAAgB;AAC5E,OAAO,KAAK,EACV,2BAA2B,EAC3B,2CAA2C,EAC3C,aAAa,EACd,oBAAgB;AAejB,wEAAwE;AACxE,KAAK,wBAAwB,GAAG,uBAAuB,CAAC;AAGxD,MAAM,MAAM,uBAAuB,GAAG;IACpC,cAAc,EAAE,MAAM,CAAC;CACxB,CAAC;;;;;;;;;;;;;;;;AACF,qBAAa,sBAAuB,SAAQ,4BAC1C,OAAO,6BAA6B,EACpC,2BAA2B,EAC3B,+BAA+B,CAChC;;gBAWa,EACV,SAAS,EACT,KAAK,EACL,QAAQ,EACR,OAAO,EACP,MAAM,GACP,EAAE;QACD,SAAS,EAAE,+BAA+B,CAAC;QAC3C,KAAK,CAAC,EAAE,OAAO,CAAC,2BAA2B,CAAC,CAAC;QAC7C,QAAQ,EAAE,cAAc,CAAC;QACzB,OAAO,EAAE,aAAa,CAAC;QACvB,MAAM,CAAC,EAAE;YACP,sBAAsB,CAAC,EAAE,MAAM,CAAC;SACjC,CAAC;KACH;IAuCD,UAAU,aAIR;IAEF,gBAAgB;iBAIL,MAAM;uBACA,OAAO;eAmBtB;IA8BF,6BAA6B,sCACQ,2CAA2C,UAiD9E;IAIF,YAAY,iBAAwB,wBAAwB,mBAE1D;CA0JH"}
1
+ {"version":3,"file":"bridge-status-controller.d.cts","sourceRoot":"","sources":["../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