@metamask-previews/bridge-status-controller 12.0.1-preview-bb41e02a → 12.0.1-preview-4e2f3d19

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 (40) hide show
  1. package/CHANGELOG.md +11 -2
  2. package/dist/bridge-status-controller.cjs +183 -21
  3. package/dist/bridge-status-controller.cjs.map +1 -1
  4. package/dist/bridge-status-controller.d.cts +10 -7
  5. package/dist/bridge-status-controller.d.cts.map +1 -1
  6. package/dist/bridge-status-controller.d.mts +10 -7
  7. package/dist/bridge-status-controller.d.mts.map +1 -1
  8. package/dist/bridge-status-controller.mjs +185 -23
  9. package/dist/bridge-status-controller.mjs.map +1 -1
  10. package/dist/constants.cjs +2 -1
  11. package/dist/constants.cjs.map +1 -1
  12. package/dist/constants.d.cts +1 -0
  13. package/dist/constants.d.cts.map +1 -1
  14. package/dist/constants.d.mts +1 -0
  15. package/dist/constants.d.mts.map +1 -1
  16. package/dist/constants.mjs +1 -0
  17. package/dist/constants.mjs.map +1 -1
  18. package/dist/types.cjs.map +1 -1
  19. package/dist/types.d.cts +14 -3
  20. package/dist/types.d.cts.map +1 -1
  21. package/dist/types.d.mts +14 -3
  22. package/dist/types.d.mts.map +1 -1
  23. package/dist/types.mjs.map +1 -1
  24. package/dist/utils/gas.cjs +31 -0
  25. package/dist/utils/gas.cjs.map +1 -0
  26. package/dist/utils/gas.d.cts +20 -0
  27. package/dist/utils/gas.d.cts.map +1 -0
  28. package/dist/utils/gas.d.mts +20 -0
  29. package/dist/utils/gas.d.mts.map +1 -0
  30. package/dist/utils/gas.mjs +27 -0
  31. package/dist/utils/gas.mjs.map +1 -0
  32. package/dist/utils/transaction.cjs +28 -16
  33. package/dist/utils/transaction.cjs.map +1 -1
  34. package/dist/utils/transaction.d.cts +8 -18
  35. package/dist/utils/transaction.d.cts.map +1 -1
  36. package/dist/utils/transaction.d.mts +8 -18
  37. package/dist/utils/transaction.d.mts.map +1 -1
  38. package/dist/utils/transaction.mjs +26 -16
  39. package/dist/utils/transaction.mjs.map +1 -1
  40. package/package.json +12 -4
package/CHANGELOG.md CHANGED
@@ -9,14 +9,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Added
11
11
 
12
- - **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))
12
+ - **BREAKING:** Add `@metamask/snaps-controllers` peer dependency at `^9.19.0` ([#5634](https://github.com/MetaMask/core/pull/5634))
13
+ - **BREAKING:** Add `@metamask/gas-fee-controller` peer dependency at `^23.0.0` ([#5643](https://github.com/MetaMask/core/pull/5643))
14
+ - **BREAKING:** Add `@metamask/assets-controllers` peer dependency at `^57.0.0` ([#5643](https://github.com/MetaMask/core/pull/5643))
15
+ - Add `@metamask/user-operation-controller` dependency at `^33.0.0` ([#5643](https://github.com/MetaMask/core/pull/5643))
13
16
  - Add `uuid` dependency at `^8.3.2` ([#5634](https://github.com/MetaMask/core/pull/5634))
17
+ - Add `@metamask/keyring-api` dependency at `^17.4.0` ([#5643](https://github.com/MetaMask/core/pull/5643))
18
+ - Add `bignumber.js` dependency at `^9.1.2` ([#5643](https://github.com/MetaMask/core/pull/5643))
14
19
  - Add `submitTx` handler that submits cross-chain swaps transactions and triggers polling for destination transaction status ([#5634](https://github.com/MetaMask/core/pull/5634))
20
+ - Enable submitting EVM transactions using `submitTx` ([#5643](https://github.com/MetaMask/core/pull/5643))
21
+ - Add functionality for importing tokens from transaction after successful confirmation ([#5643](https://github.com/MetaMask/core/pull/5643))
15
22
 
16
23
  ### Changed
17
24
 
18
- - Bump `@metamask/bridge-controller` dependency to `^15.0.0` ([#5657](https://github.com/MetaMask/core/pull/5657), [#5665](https://github.com/MetaMask/core/pull/5665))
25
+ - **BREAKING** Change `@metamask/bridge-controller` from dependency to peer dependency and bump to `^15.0.0` ([#5643](https://github.com/MetaMask/core/pull/5643))
19
26
  - Add optional config.customBridgeApiBaseUrl constructor arg to set the bridge-api base URL ([#5634](https://github.com/MetaMask/core/pull/5634))
27
+ - 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))
28
+ - 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))
20
29
 
21
30
  ### Fixed
22
31
 
@@ -10,16 +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_getMultichainSelectedAccount, _BridgeStatusController_getMultichainSelectedAccountAddress, _BridgeStatusController_fetchBridgeTxStatus, _BridgeStatusController_getSrcTxHash, _BridgeStatusController_updateSrcTxHash, _BridgeStatusController_wipeBridgeStatusByChainId, _BridgeStatusController_handleSolanaTx;
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");
22
27
  const transaction_1 = require("./utils/transaction.cjs");
28
+ const transaction_2 = require("./utils/transaction.cjs");
23
29
  const metadata = {
24
30
  // We want to persist the bridge status state so that we can show the proper data for the Activity list
25
31
  // basically match the behavior of TransactionController
@@ -29,7 +35,7 @@ const metadata = {
29
35
  },
30
36
  };
31
37
  class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPollingController)() {
32
- constructor({ messenger, state, clientId, fetchFn, config, }) {
38
+ constructor({ messenger, state, clientId, fetchFn, addTransactionFn, addUserOperationFromTransactionFn, estimateGasFeeFn, config, }) {
33
39
  super({
34
40
  name: constants_1.BRIDGE_STATUS_CONTROLLER_NAME,
35
41
  metadata,
@@ -45,6 +51,9 @@ class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPoll
45
51
  _BridgeStatusController_clientId.set(this, void 0);
46
52
  _BridgeStatusController_fetchFn.set(this, void 0);
47
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);
48
57
  this.resetState = () => {
49
58
  this.update((state) => {
50
59
  state.txHistory = constants_1.DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;
@@ -231,7 +240,9 @@ class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPoll
231
240
  *******************************************************
232
241
  */
233
242
  /**
234
- * Submits a solana swap or bridge transaction using the snap controller
243
+ * Submits the transaction to the snap using the keyring rpc method
244
+ * This adds an approval tx to the ApprovalsController in the background
245
+ * The client needs to handle the approval tx by redirecting to the confirmation page with the approvalTxId in the URL
235
246
  *
236
247
  * @param quoteResponse - The quote response
237
248
  * @param quoteResponse.quote - The quote
@@ -246,55 +257,203 @@ class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPoll
246
257
  !selectedAccount.options?.scope) {
247
258
  throw new Error('Failed to submit cross-chain swap transaction: undefined snap id or scope');
248
259
  }
249
- /**
250
- * Submit the transaction to the snap using the keyring rpc method
251
- * This adds an approval tx to the ApprovalsController in the background
252
- * The client needs to handle the approval tx by redirecting to the confirmation page with the approvalTxId in the URL
253
- */
254
260
  const keyringRequest = (0, transaction_1.getKeyringRequest)(quoteResponse, selectedAccount);
255
261
  const keyringResponse = (await this.messagingSystem.call('SnapController:handleRequest', keyringRequest));
256
262
  // The extension client actually redirects before it can do anytyhing with this meta
257
- const txMeta = (0, transaction_1.handleSolanaTxResponse)(keyringResponse, quoteResponse, selectedAccount.metadata.snap.id, selectedAccount.address);
263
+ const txMeta = (0, transaction_1.handleSolanaTxResponse)(keyringResponse, quoteResponse, selectedAccount);
258
264
  // TODO remove this eventually, just returning it now to match extension behavior
259
265
  // 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
260
266
  return txMeta;
261
267
  });
268
+ _BridgeStatusController_waitForHashAndReturnFinalTxMeta.set(this, async (hashPromise) => {
269
+ const transactionHash = await hashPromise;
270
+ const finalTransactionMeta = this.messagingSystem
271
+ .call('TransactionController:getState')
272
+ .transactions.find((tx) => tx.hash === transactionHash);
273
+ return finalTransactionMeta;
274
+ });
275
+ _BridgeStatusController_handleApprovalTx.set(this, async (quoteResponse) => {
276
+ if (quoteResponse.approval) {
277
+ await __classPrivateFieldGet(this, _BridgeStatusController_handleUSDTAllowanceReset, "f").call(this, quoteResponse);
278
+ const approvalTxMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, transaction_controller_1.TransactionType.bridgeApproval, quoteResponse.approval, quoteResponse);
279
+ if (!approvalTxMeta) {
280
+ throw new Error('Failed to submit bridge tx: approval txMeta is undefined');
281
+ }
282
+ await (0, transaction_1.handleLineaDelay)(quoteResponse);
283
+ return approvalTxMeta;
284
+ }
285
+ return undefined;
286
+ });
287
+ _BridgeStatusController_handleEvmSmartTransaction.set(this, async (trade, quoteResponse, approvalTxId) => {
288
+ return await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, transaction_controller_1.TransactionType.bridge, trade, quoteResponse, approvalTxId, false);
289
+ });
262
290
  /**
263
- * Submits a cross-chain swap transaction
291
+ * Submits an EVM transaction to the TransactionController
264
292
  *
293
+ * @param transactionType - The type of transaction to submit
294
+ * @param trade - The trade data to confirm
265
295
  * @param quoteResponse - The quote response
266
296
  * @param quoteResponse.quote - The quote
267
- * @param quoteResponse.trade - The trade
268
- * @param quoteResponse.approval - The approval
297
+ * @param approvalTxId - The tx id of the approval tx
298
+ * @param shouldWaitForHash - Whether to wait for the hash of the transaction
269
299
  * @returns The transaction meta
270
300
  */
271
- this.submitTx = async (quoteResponse) => {
272
- this.stopAllPolling();
273
- if (!(0, bridge_controller_1.isSolanaChainId)(quoteResponse.quote.srcChainId)) {
274
- throw new Error('Failed to submit bridge tx: only Solana is supported');
301
+ _BridgeStatusController_handleEvmTransaction.set(this, async (transactionType, trade, quoteResponse, approvalTxId, shouldWaitForHash = true) => {
302
+ const actionId = (0, transaction_2.generateActionId)().toString();
303
+ const selectedAccount = this.messagingSystem.call('AccountsController:getAccountByAddress', trade.from);
304
+ if (!selectedAccount) {
305
+ throw new Error('Failed to submit cross-chain swap transaction: unknown account in trade data');
306
+ }
307
+ const hexChainId = (0, bridge_controller_1.formatChainIdToHex)(trade.chainId);
308
+ const networkClientId = this.messagingSystem.call('NetworkController:findNetworkClientIdByChainId', hexChainId);
309
+ const requestOptions = {
310
+ actionId,
311
+ networkClientId,
312
+ requireApproval: false,
313
+ type: transactionType,
314
+ origin: 'metamask',
315
+ approvalTxId,
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;
275
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) => {
276
417
  let txMeta;
277
418
  // Submit SOLANA tx
278
419
  if ((0, bridge_controller_1.isSolanaChainId)(quoteResponse.quote.srcChainId) &&
279
420
  typeof quoteResponse.trade === 'string') {
280
421
  txMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleSolanaTx, "f").call(this, quoteResponse);
281
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
+ }
282
439
  if (!txMeta) {
283
440
  throw new Error('Failed to submit bridge tx: txMeta is undefined');
284
441
  }
285
- // Start polling for bridge tx status
286
442
  try {
287
- const statusRequestCommon = (0, transaction_1.getStatusRequestParams)(quoteResponse);
443
+ // Start polling for bridge tx status
288
444
  this.startPollingForBridgeTxStatus({
289
445
  bridgeTxMeta: txMeta,
290
446
  statusRequest: {
291
- ...statusRequestCommon,
447
+ ...(0, transaction_1.getStatusRequestParams)(quoteResponse),
292
448
  srcTxHash: txMeta.hash,
293
449
  },
294
450
  quoteResponse,
295
451
  slippagePercentage: 0,
296
- startTime: Date.now(),
452
+ startTime: approvalTime ?? Date.now(),
297
453
  });
454
+ // Add tokens to the token list
455
+ __classPrivateFieldGet(this, _BridgeStatusController_addTokens, "f").call(this, quoteResponse.quote.srcAsset);
456
+ __classPrivateFieldGet(this, _BridgeStatusController_addTokens, "f").call(this, quoteResponse.quote.destAsset);
298
457
  }
299
458
  catch {
300
459
  // Ignore errors here, we don't want to crash the app if this fails and tx submission succeeds
@@ -303,6 +462,9 @@ class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPoll
303
462
  };
304
463
  __classPrivateFieldSet(this, _BridgeStatusController_clientId, clientId, "f");
305
464
  __classPrivateFieldSet(this, _BridgeStatusController_fetchFn, fetchFn, "f");
465
+ __classPrivateFieldSet(this, _BridgeStatusController_addTransactionFn, addTransactionFn, "f");
466
+ __classPrivateFieldSet(this, _BridgeStatusController_addUserOperationFromTransactionFn, addUserOperationFromTransactionFn, "f");
467
+ __classPrivateFieldSet(this, _BridgeStatusController_estimateGasFeeFn, estimateGasFeeFn, "f");
306
468
  __classPrivateFieldSet(this, _BridgeStatusController_config, {
307
469
  customBridgeApiBaseUrl: config?.customBridgeApiBaseUrl ?? constants_1.BRIDGE_PROD_API_BASE_URL,
308
470
  }, "f");
@@ -320,7 +482,7 @@ class BridgeStatusController extends (0, polling_controller_1.StaticIntervalPoll
320
482
  }
321
483
  }
322
484
  exports.BridgeStatusController = BridgeStatusController;
323
- _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_handleSolanaTx = new WeakMap(), _BridgeStatusController_instances = new WeakSet(), _BridgeStatusController_getMultichainSelectedAccount = function _BridgeStatusController_getMultichainSelectedAccount() {
485
+ _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() {
324
486
  return this.messagingSystem.call('AccountsController:getSelectedMultichainAccount');
325
487
  }, _BridgeStatusController_getMultichainSelectedAccountAddress = function _BridgeStatusController_getMultichainSelectedAccountAddress() {
326
488
  return __classPrivateFieldGet(this, _BridgeStatusController_instances, "m", _BridgeStatusController_getMultichainSelectedAccount).call(this)?.address ?? '';
@@ -1 +1 @@
1
- {"version":3,"file":"bridge-status-controller.cjs","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,mEAGqC;AAErC,qEAA+E;AAE/E,2CAAwD;AAExD,+CAKqB;AACrB,uCAA4E;AAO5E,6DAG+B;AAC/B,yDAI6B;AAE7B,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,EAA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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;CAiYF;AA1cD,wDA0cC;;IAnQG,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 isSolanaChainId,\n type QuoteResponse,\n} from '@metamask/bridge-controller';\nimport type { QuoteMetadata, TxData } from '@metamask/bridge-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport { numberToHex, type Hex } from '@metamask/utils';\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} from './types';\nimport {\n fetchBridgeTxStatus,\n getStatusRequestWithSrcTxHash,\n} from './utils/bridge-status';\nimport {\n getKeyringRequest,\n getStatusRequestParams,\n handleSolanaTxResponse,\n} 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 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 = {\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 } = 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 #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) => 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 a solana swap or bridge transaction using the snap controller\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 /**\n * Submit 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 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.metadata.snap.id,\n selectedAccount.address,\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 /**\n * Submits a cross-chain swap transaction\n *\n * @param quoteResponse - The quote response\n * @param quoteResponse.quote - The quote\n * @param quoteResponse.trade - The trade\n * @param quoteResponse.approval - The approval\n * @returns The transaction meta\n */\n submitTx = async (\n quoteResponse: QuoteResponse<TxData | string> & QuoteMetadata,\n ) => {\n this.stopAllPolling();\n\n if (!isSolanaChainId(quoteResponse.quote.srcChainId)) {\n throw new Error('Failed to submit bridge tx: only Solana is supported');\n }\n\n let txMeta: TransactionMeta | 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\n if (!txMeta) {\n throw new Error('Failed to submit bridge tx: txMeta is undefined');\n }\n\n // Start polling for bridge tx status\n try {\n const statusRequestCommon = getStatusRequestParams(quoteResponse);\n this.startPollingForBridgeTxStatus({\n bridgeTxMeta: txMeta, // Only the id field is used by the BridgeStatusController\n statusRequest: {\n ...statusRequestCommon,\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: Date.now(),\n });\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
+ {"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+B,GAI1E;IAiBC,YAAY,EACV,SAAS,EACT,KAAK,EACL,QAAQ,EACR,OAAO,EACP,gBAAgB,EAChB,iCAAiC,EACjC,gBAAgB,EAChB,MAAM,GAYP;QACC,KAAK,CAAC;YACJ,IAAI,EAAE,yCAA6B;YACnC,QAAQ;YACR,SAAS;YACT,8BAA8B;YAC9B,KAAK,EAAE;gBACL,GAAG,kDAAsC;gBACzC,GAAG,K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B,CAAC,+BAAmB,CAAC,CAAC;QAE5C,+EAA+E;QAC/E,8CAA8C;QAC9C,mFAAmF;QACnF,uBAAA,IAAI,uEAAyC,MAA7C,IAAI,CAA2C,CAAC;IAClD,CAAC;CAioBF;AAztBD,wDAytBC;;IAngBG,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 } = 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 #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 approvalTxId,\n };\n const transactionParams = {\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 });\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,9 +1,11 @@
1
1
  import { type QuoteResponse } from "@metamask/bridge-controller";
2
2
  import type { QuoteMetadata, TxData } from "@metamask/bridge-controller";
3
- import type { TransactionMeta } from "@metamask/transaction-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";
4
6
  import { BRIDGE_STATUS_CONTROLLER_NAME } from "./constants.cjs";
5
7
  import { type BridgeStatusControllerMessenger } from "./types.cjs";
6
- import type { BridgeStatusControllerState, StartPollingForBridgeTxStatusArgsSerialized, FetchFunction, BridgeClientId } from "./types.cjs";
8
+ import type { BridgeStatusControllerState, StartPollingForBridgeTxStatusArgsSerialized, FetchFunction, BridgeClientId, SolanaTransactionMeta } from "./types.cjs";
7
9
  /** The input to start polling for the {@link BridgeStatusController} */
8
10
  type BridgeStatusPollingInput = FetchBridgeTxStatusArgs;
9
11
  export type FetchBridgeTxStatusArgs = {
@@ -26,11 +28,14 @@ declare const BridgeStatusController_base: (abstract new (...args: any[]) => {
26
28
  }) & typeof import("@metamask/base-controller").BaseController;
27
29
  export declare class BridgeStatusController extends BridgeStatusController_base<typeof BRIDGE_STATUS_CONTROLLER_NAME, BridgeStatusControllerState, BridgeStatusControllerMessenger> {
28
30
  #private;
29
- constructor({ messenger, state, clientId, fetchFn, config, }: {
31
+ constructor({ messenger, state, clientId, fetchFn, addTransactionFn, addUserOperationFromTransactionFn, estimateGasFeeFn, config, }: {
30
32
  messenger: BridgeStatusControllerMessenger;
31
33
  state?: Partial<BridgeStatusControllerState>;
32
34
  clientId: BridgeClientId;
33
35
  fetchFn: FetchFunction;
36
+ addTransactionFn: typeof TransactionController.prototype.addTransaction;
37
+ estimateGasFeeFn: typeof TransactionController.prototype.estimateGasFee;
38
+ addUserOperationFromTransactionFn?: typeof UserOperationController.prototype.addUserOperationFromTransaction;
34
39
  config?: {
35
40
  customBridgeApiBaseUrl?: string;
36
41
  };
@@ -51,12 +56,10 @@ export declare class BridgeStatusController extends BridgeStatusController_base<
51
56
  * Submits a cross-chain swap transaction
52
57
  *
53
58
  * @param quoteResponse - The quote response
54
- * @param quoteResponse.quote - The quote
55
- * @param quoteResponse.trade - The trade
56
- * @param quoteResponse.approval - The approval
59
+ * @param isStxEnabledOnClient - Whether smart transactions are enabled on the client, for example the getSmartTransactionsEnabled selector value from the extension
57
60
  * @returns The transaction meta
58
61
  */
59
- submitTx: (quoteResponse: QuoteResponse<TxData | string> & QuoteMetadata) => Promise<TransactionMeta>;
62
+ submitTx: (quoteResponse: QuoteResponse<TxData | string> & QuoteMetadata, isStxEnabledOnClient: boolean) => Promise<TransactionMeta & Partial<SolanaTransactionMeta>>;
60
63
  }
61
64
  export {};
62
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,EAEL,KAAK,aAAa,EACnB,oCAAoC;AACrC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,oCAAoC;AAEzE,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AAGxE,OAAO,EAEL,6BAA6B,EAG9B,wBAAoB;AACrB,OAAO,EAAe,KAAK,+BAA+B,EAAE,oBAAgB;AAC5E,OAAO,KAAK,EACV,2BAA2B,EAC3B,2CAA2C,EAC3C,aAAa,EACb,cAAc,EACf,oBAAgB;AAoBjB,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;IA8CD,UAAU,aAIR;IAEF,gBAAgB;iBAIL,MAAM;uBACA,OAAO;eAmBtB;IA8BF;;;;OAIG;IACH,6BAA6B,sCACQ,2CAA2C,UAiD9E;IAIF,YAAY,iBAAwB,wBAAwB,mBAE1D;IAmNF;;;;;;;;OAQG;IACH,QAAQ,kBACS,cAAc,MAAM,GAAG,MAAM,CAAC,GAAG,aAAa,8BAwC7D;CACH"}
1
+ {"version":3,"file":"bridge-status-controller.d.cts","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":"AACA,OAAO,EAML,KAAK,aAAa,EACnB,oCAAoC;AACrC,OAAO,KAAK,EAEV,aAAa,EACb,MAAM,EACP,oCAAoC;AAIrC,OAAO,KAAK,EACV,qBAAqB,EAEtB,yCAAyC;AAC1C,OAAO,EAGL,KAAK,eAAe,EACrB,yCAAyC;AAC1C,OAAO,KAAK,EAA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GAAG,aAAa,wBACvC,OAAO,+DA8D7B;CACH"}
@@ -1,9 +1,11 @@
1
1
  import { type QuoteResponse } from "@metamask/bridge-controller";
2
2
  import type { QuoteMetadata, TxData } from "@metamask/bridge-controller";
3
- import type { TransactionMeta } from "@metamask/transaction-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";
4
6
  import { BRIDGE_STATUS_CONTROLLER_NAME } from "./constants.mjs";
5
7
  import { type BridgeStatusControllerMessenger } from "./types.mjs";
6
- import type { BridgeStatusControllerState, StartPollingForBridgeTxStatusArgsSerialized, FetchFunction, BridgeClientId } from "./types.mjs";
8
+ import type { BridgeStatusControllerState, StartPollingForBridgeTxStatusArgsSerialized, FetchFunction, BridgeClientId, SolanaTransactionMeta } from "./types.mjs";
7
9
  /** The input to start polling for the {@link BridgeStatusController} */
8
10
  type BridgeStatusPollingInput = FetchBridgeTxStatusArgs;
9
11
  export type FetchBridgeTxStatusArgs = {
@@ -26,11 +28,14 @@ declare const BridgeStatusController_base: (abstract new (...args: any[]) => {
26
28
  }) & typeof import("@metamask/base-controller").BaseController;
27
29
  export declare class BridgeStatusController extends BridgeStatusController_base<typeof BRIDGE_STATUS_CONTROLLER_NAME, BridgeStatusControllerState, BridgeStatusControllerMessenger> {
28
30
  #private;
29
- constructor({ messenger, state, clientId, fetchFn, config, }: {
31
+ constructor({ messenger, state, clientId, fetchFn, addTransactionFn, addUserOperationFromTransactionFn, estimateGasFeeFn, config, }: {
30
32
  messenger: BridgeStatusControllerMessenger;
31
33
  state?: Partial<BridgeStatusControllerState>;
32
34
  clientId: BridgeClientId;
33
35
  fetchFn: FetchFunction;
36
+ addTransactionFn: typeof TransactionController.prototype.addTransaction;
37
+ estimateGasFeeFn: typeof TransactionController.prototype.estimateGasFee;
38
+ addUserOperationFromTransactionFn?: typeof UserOperationController.prototype.addUserOperationFromTransaction;
34
39
  config?: {
35
40
  customBridgeApiBaseUrl?: string;
36
41
  };
@@ -51,12 +56,10 @@ export declare class BridgeStatusController extends BridgeStatusController_base<
51
56
  * Submits a cross-chain swap transaction
52
57
  *
53
58
  * @param quoteResponse - The quote response
54
- * @param quoteResponse.quote - The quote
55
- * @param quoteResponse.trade - The trade
56
- * @param quoteResponse.approval - The approval
59
+ * @param isStxEnabledOnClient - Whether smart transactions are enabled on the client, for example the getSmartTransactionsEnabled selector value from the extension
57
60
  * @returns The transaction meta
58
61
  */
59
- submitTx: (quoteResponse: QuoteResponse<TxData | string> & QuoteMetadata) => Promise<TransactionMeta>;
62
+ submitTx: (quoteResponse: QuoteResponse<TxData | string> & QuoteMetadata, isStxEnabledOnClient: boolean) => Promise<TransactionMeta & Partial<SolanaTransactionMeta>>;
60
63
  }
61
64
  export {};
62
65
  //# sourceMappingURL=bridge-status-controller.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bridge-status-controller.d.mts","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,aAAa,EACnB,oCAAoC;AACrC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,oCAAoC;AAEzE,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AAGxE,OAAO,EAEL,6BAA6B,EAG9B,wBAAoB;AACrB,OAAO,EAAe,KAAK,+BAA+B,EAAE,oBAAgB;AAC5E,OAAO,KAAK,EACV,2BAA2B,EAC3B,2CAA2C,EAC3C,aAAa,EACb,cAAc,EACf,oBAAgB;AAoBjB,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;IA8CD,UAAU,aAIR;IAEF,gBAAgB;iBAIL,MAAM;uBACA,OAAO;eAmBtB;IA8BF;;;;OAIG;IACH,6BAA6B,sCACQ,2CAA2C,UAiD9E;IAIF,YAAY,iBAAwB,wBAAwB,mBAE1D;IAmNF;;;;;;;;OAQG;IACH,QAAQ,kBACS,cAAc,MAAM,GAAG,MAAM,CAAC,GAAG,aAAa,8BAwC7D;CACH"}
1
+ {"version":3,"file":"bridge-status-controller.d.mts","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":"AACA,OAAO,EAML,KAAK,aAAa,EACnB,oCAAoC;AACrC,OAAO,KAAK,EAEV,aAAa,EACb,MAAM,EACP,oCAAoC;AAIrC,OAAO,KAAK,EACV,qBAAqB,EAEtB,yCAAyC;AAC1C,OAAO,EAGL,KAAK,eAAe,EACrB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,uBAAuB,EAAE,4CAA4C;AAInF,OAAO,EAEL,6BAA6B,EAG9B,wBAAoB;AACrB,OAAO,EAAe,KAAK,+BAA+B,EAAE,oBAAgB;AAC5E,OAAO,KAAK,EACV,2BAA2B,EAC3B,2CAA2C,EAC3C,aAAa,EACb,cAAc,EACd,qBAAqB,EACtB,oBAAgB;AAwBjB,wEAAwE;AACxE,KAAK,wBAAwB,GAAG,uBAAuB,CAAC;AAGxD,MAAM,MAAM,uBAAuB,GAAG;IACpC,cAAc,EAAE,MAAM,CAAC;CACxB,CAAC;;;;;;;;;;;;;;;;AACF,qBAAa,sBAAuB,SAAQ,4BAC1C,OAA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