@metamask-previews/bridge-status-controller 12.0.1-preview-6c44e568 → 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 -3
  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
@@ -9,14 +9,20 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  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");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- 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
- import { isSolanaChainId } from "@metamask/bridge-controller";
12
+ 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;
13
+ import { formatChainIdToHex, getEthUsdtResetData, isEthUsdt, isNativeAddress, isSolanaChainId } from "@metamask/bridge-controller";
14
+ import { toHex } from "@metamask/controller-utils";
15
+ import { EthAccountType } from "@metamask/keyring-api";
14
16
  import { StaticIntervalPollingController } from "@metamask/polling-controller";
17
+ import { TransactionStatus, TransactionType } from "@metamask/transaction-controller";
15
18
  import { numberToHex } from "@metamask/utils";
19
+ import { BigNumber } from "bignumber.js";
16
20
  import { BRIDGE_PROD_API_BASE_URL, BRIDGE_STATUS_CONTROLLER_NAME, DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE, REFRESH_INTERVAL_MS } from "./constants.mjs";
17
21
  import { StatusTypes } from "./types.mjs";
18
22
  import { fetchBridgeTxStatus, getStatusRequestWithSrcTxHash } from "./utils/bridge-status.mjs";
19
- import { getKeyringRequest, getStatusRequestParams, handleSolanaTxResponse } from "./utils/transaction.mjs";
23
+ import { getTxGasEstimates } from "./utils/gas.mjs";
24
+ import { getKeyringRequest, getStatusRequestParams, getTxMetaFields, handleLineaDelay, handleSolanaTxResponse } from "./utils/transaction.mjs";
25
+ import { generateActionId } from "./utils/transaction.mjs";
20
26
  const metadata = {
21
27
  // We want to persist the bridge status state so that we can show the proper data for the Activity list
22
28
  // basically match the behavior of TransactionController
@@ -26,7 +32,7 @@ const metadata = {
26
32
  },
27
33
  };
28
34
  export class BridgeStatusController extends StaticIntervalPollingController() {
29
- constructor({ messenger, state, clientId, fetchFn, config, }) {
35
+ constructor({ messenger, state, clientId, fetchFn, addTransactionFn, addUserOperationFromTransactionFn, estimateGasFeeFn, config, }) {
30
36
  super({
31
37
  name: BRIDGE_STATUS_CONTROLLER_NAME,
32
38
  metadata,
@@ -42,6 +48,9 @@ export class BridgeStatusController extends StaticIntervalPollingController() {
42
48
  _BridgeStatusController_clientId.set(this, void 0);
43
49
  _BridgeStatusController_fetchFn.set(this, void 0);
44
50
  _BridgeStatusController_config.set(this, void 0);
51
+ _BridgeStatusController_addTransactionFn.set(this, void 0);
52
+ _BridgeStatusController_estimateGasFeeFn.set(this, void 0);
53
+ _BridgeStatusController_addUserOperationFromTransactionFn.set(this, void 0);
45
54
  this.resetState = () => {
46
55
  this.update((state) => {
47
56
  state.txHistory = DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;
@@ -228,7 +237,9 @@ export class BridgeStatusController extends StaticIntervalPollingController() {
228
237
  *******************************************************
229
238
  */
230
239
  /**
231
- * Submits a solana swap or bridge transaction using the snap controller
240
+ * Submits the transaction to the snap using the keyring rpc method
241
+ * This adds an approval tx to the ApprovalsController in the background
242
+ * The client needs to handle the approval tx by redirecting to the confirmation page with the approvalTxId in the URL
232
243
  *
233
244
  * @param quoteResponse - The quote response
234
245
  * @param quoteResponse.quote - The quote
@@ -243,55 +254,203 @@ export class BridgeStatusController extends StaticIntervalPollingController() {
243
254
  !selectedAccount.options?.scope) {
244
255
  throw new Error('Failed to submit cross-chain swap transaction: undefined snap id or scope');
245
256
  }
246
- /**
247
- * Submit the transaction to the snap using the keyring rpc method
248
- * This adds an approval tx to the ApprovalsController in the background
249
- * The client needs to handle the approval tx by redirecting to the confirmation page with the approvalTxId in the URL
250
- */
251
257
  const keyringRequest = getKeyringRequest(quoteResponse, selectedAccount);
252
258
  const keyringResponse = (await this.messagingSystem.call('SnapController:handleRequest', keyringRequest));
253
259
  // The extension client actually redirects before it can do anytyhing with this meta
254
- const txMeta = handleSolanaTxResponse(keyringResponse, quoteResponse, selectedAccount.metadata.snap.id, selectedAccount.address);
260
+ const txMeta = handleSolanaTxResponse(keyringResponse, quoteResponse, selectedAccount);
255
261
  // TODO remove this eventually, just returning it now to match extension behavior
256
262
  // 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
257
263
  return txMeta;
258
264
  });
265
+ _BridgeStatusController_waitForHashAndReturnFinalTxMeta.set(this, async (hashPromise) => {
266
+ const transactionHash = await hashPromise;
267
+ const finalTransactionMeta = this.messagingSystem
268
+ .call('TransactionController:getState')
269
+ .transactions.find((tx) => tx.hash === transactionHash);
270
+ return finalTransactionMeta;
271
+ });
272
+ _BridgeStatusController_handleApprovalTx.set(this, async (quoteResponse) => {
273
+ if (quoteResponse.approval) {
274
+ await __classPrivateFieldGet(this, _BridgeStatusController_handleUSDTAllowanceReset, "f").call(this, quoteResponse);
275
+ const approvalTxMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, TransactionType.bridgeApproval, quoteResponse.approval, quoteResponse);
276
+ if (!approvalTxMeta) {
277
+ throw new Error('Failed to submit bridge tx: approval txMeta is undefined');
278
+ }
279
+ await handleLineaDelay(quoteResponse);
280
+ return approvalTxMeta;
281
+ }
282
+ return undefined;
283
+ });
284
+ _BridgeStatusController_handleEvmSmartTransaction.set(this, async (trade, quoteResponse, approvalTxId) => {
285
+ return await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, TransactionType.bridge, trade, quoteResponse, approvalTxId, false);
286
+ });
259
287
  /**
260
- * Submits a cross-chain swap transaction
288
+ * Submits an EVM transaction to the TransactionController
261
289
  *
290
+ * @param transactionType - The type of transaction to submit
291
+ * @param trade - The trade data to confirm
262
292
  * @param quoteResponse - The quote response
263
293
  * @param quoteResponse.quote - The quote
264
- * @param quoteResponse.trade - The trade
265
- * @param quoteResponse.approval - The approval
294
+ * @param approvalTxId - The tx id of the approval tx
295
+ * @param shouldWaitForHash - Whether to wait for the hash of the transaction
266
296
  * @returns The transaction meta
267
297
  */
268
- this.submitTx = async (quoteResponse) => {
269
- this.stopAllPolling();
270
- if (!isSolanaChainId(quoteResponse.quote.srcChainId)) {
271
- throw new Error('Failed to submit bridge tx: only Solana is supported');
298
+ _BridgeStatusController_handleEvmTransaction.set(this, async (transactionType, trade, quoteResponse, approvalTxId, shouldWaitForHash = true) => {
299
+ const actionId = generateActionId().toString();
300
+ const selectedAccount = this.messagingSystem.call('AccountsController:getAccountByAddress', trade.from);
301
+ if (!selectedAccount) {
302
+ throw new Error('Failed to submit cross-chain swap transaction: unknown account in trade data');
303
+ }
304
+ const hexChainId = formatChainIdToHex(trade.chainId);
305
+ const networkClientId = this.messagingSystem.call('NetworkController:findNetworkClientIdByChainId', hexChainId);
306
+ const requestOptions = {
307
+ actionId,
308
+ networkClientId,
309
+ requireApproval: false,
310
+ type: transactionType,
311
+ origin: 'metamask',
312
+ approvalTxId,
313
+ };
314
+ const transactionParams = {
315
+ ...trade,
316
+ chainId: hexChainId,
317
+ gasLimit: trade.gasLimit?.toString(),
318
+ gas: trade.gasLimit?.toString(),
319
+ };
320
+ const transactionParamsWithMaxGas = {
321
+ ...transactionParams,
322
+ ...(await __classPrivateFieldGet(this, _BridgeStatusController_calculateGasFees, "f").call(this, transactionParams, networkClientId, hexChainId)),
323
+ };
324
+ let result;
325
+ let transactionMeta;
326
+ const isSmartContractAccount = selectedAccount.type === EthAccountType.Erc4337;
327
+ if (isSmartContractAccount && __classPrivateFieldGet(this, _BridgeStatusController_addUserOperationFromTransactionFn, "f")) {
328
+ const smartAccountTxResult = await __classPrivateFieldGet(this, _BridgeStatusController_addUserOperationFromTransactionFn, "f").call(this, transactionParamsWithMaxGas, requestOptions);
329
+ result = smartAccountTxResult.transactionHash;
330
+ transactionMeta = {
331
+ ...requestOptions,
332
+ chainId: hexChainId,
333
+ txParams: transactionParamsWithMaxGas,
334
+ time: Date.now(),
335
+ id: smartAccountTxResult.id,
336
+ status: TransactionStatus.confirmed,
337
+ };
338
+ }
339
+ else {
340
+ const addTransactionResult = await __classPrivateFieldGet(this, _BridgeStatusController_addTransactionFn, "f").call(this, transactionParamsWithMaxGas, requestOptions);
341
+ result = addTransactionResult.result;
342
+ transactionMeta = addTransactionResult.transactionMeta;
343
+ }
344
+ if (shouldWaitForHash) {
345
+ return await __classPrivateFieldGet(this, _BridgeStatusController_waitForHashAndReturnFinalTxMeta, "f").call(this, result);
346
+ }
347
+ // TODO why is this needed?
348
+ // Note that updateTransaction doesn't actually error if you add fields that don't conform the to the txMeta type
349
+ // they will be there at runtime, but you just don't get any type safety checks on them
350
+ // const fieldsToAddToTxMeta = getTxMetaFields(quoteResponse, approvalTxId);
351
+ // dispatch(updateTransaction(completeTxMeta);
352
+ return {
353
+ ...getTxMetaFields(quoteResponse, approvalTxId),
354
+ ...transactionMeta,
355
+ };
356
+ });
357
+ // Only adds tokens if the source or dest chain is an EVM chain bc non-evm tokens
358
+ // are detected by the multichain asset controllers
359
+ _BridgeStatusController_addTokens.set(this, (asset) => {
360
+ if (isNativeAddress(asset.address) || isSolanaChainId(asset.chainId)) {
361
+ return;
272
362
  }
363
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
364
+ this.messagingSystem.call('TokensController:addDetectedTokens', [
365
+ {
366
+ address: asset.address,
367
+ decimals: asset.decimals,
368
+ image: asset.iconUrl,
369
+ name: asset.name,
370
+ symbol: asset.symbol,
371
+ },
372
+ ], {
373
+ chainId: formatChainIdToHex(asset.chainId),
374
+ selectedAddress: __classPrivateFieldGet(this, _BridgeStatusController_instances, "m", _BridgeStatusController_getMultichainSelectedAccountAddress).call(this),
375
+ });
376
+ });
377
+ _BridgeStatusController_handleUSDTAllowanceReset.set(this, async (quoteResponse) => {
378
+ const hexChainId = formatChainIdToHex(quoteResponse.quote.srcChainId);
379
+ if (quoteResponse.approval &&
380
+ isEthUsdt(hexChainId, quoteResponse.quote.srcAsset.address)) {
381
+ const allowance = new BigNumber(await this.messagingSystem.call('BridgeController:getBridgeERC20Allowance', quoteResponse.quote.srcAsset.address, hexChainId));
382
+ const shouldResetApproval = allowance.lt(quoteResponse.sentAmount.amount) && allowance.gt(0);
383
+ if (shouldResetApproval) {
384
+ await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, TransactionType.bridgeApproval, { ...quoteResponse.approval, data: getEthUsdtResetData() }, quoteResponse);
385
+ }
386
+ }
387
+ });
388
+ _BridgeStatusController_calculateGasFees.set(this, async (transactionParams, networkClientId, chainId) => {
389
+ const { gasFeeEstimates } = this.messagingSystem.call('GasFeeController:getState');
390
+ const { estimates: txGasFeeEstimates } = await __classPrivateFieldGet(this, _BridgeStatusController_estimateGasFeeFn, "f").call(this, {
391
+ transactionParams,
392
+ chainId,
393
+ networkClientId,
394
+ });
395
+ const { maxFeePerGas, maxPriorityFeePerGas } = getTxGasEstimates({
396
+ networkGasFeeEstimates: gasFeeEstimates,
397
+ txGasFeeEstimates,
398
+ });
399
+ const maxGasLimit = toHex(transactionParams.gas ?? 0);
400
+ return {
401
+ maxFeePerGas,
402
+ maxPriorityFeePerGas,
403
+ gas: maxGasLimit,
404
+ };
405
+ });
406
+ /**
407
+ * Submits a cross-chain swap transaction
408
+ *
409
+ * @param quoteResponse - The quote response
410
+ * @param isStxEnabledOnClient - Whether smart transactions are enabled on the client, for example the getSmartTransactionsEnabled selector value from the extension
411
+ * @returns The transaction meta
412
+ */
413
+ this.submitTx = async (quoteResponse, isStxEnabledOnClient) => {
273
414
  let txMeta;
274
415
  // Submit SOLANA tx
275
416
  if (isSolanaChainId(quoteResponse.quote.srcChainId) &&
276
417
  typeof quoteResponse.trade === 'string') {
277
418
  txMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleSolanaTx, "f").call(this, quoteResponse);
278
419
  }
420
+ // Submit EVM tx
421
+ let approvalTime, approvalTxId;
422
+ if (!isSolanaChainId(quoteResponse.quote.srcChainId) &&
423
+ typeof quoteResponse.trade !== 'string') {
424
+ // Set approval time and id if an approval tx is needed
425
+ const approvalTxMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleApprovalTx, "f").call(this, quoteResponse);
426
+ approvalTime = approvalTxMeta?.time;
427
+ approvalTxId = approvalTxMeta?.id;
428
+ // Handle smart transactions if enabled
429
+ if (isStxEnabledOnClient) {
430
+ txMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmSmartTransaction, "f").call(this, quoteResponse.trade, quoteResponse, approvalTxId);
431
+ }
432
+ else {
433
+ txMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, TransactionType.bridge, quoteResponse.trade, quoteResponse, approvalTxId);
434
+ }
435
+ }
279
436
  if (!txMeta) {
280
437
  throw new Error('Failed to submit bridge tx: txMeta is undefined');
281
438
  }
282
- // Start polling for bridge tx status
283
439
  try {
284
- const statusRequestCommon = getStatusRequestParams(quoteResponse);
440
+ // Start polling for bridge tx status
285
441
  this.startPollingForBridgeTxStatus({
286
442
  bridgeTxMeta: txMeta,
287
443
  statusRequest: {
288
- ...statusRequestCommon,
444
+ ...getStatusRequestParams(quoteResponse),
289
445
  srcTxHash: txMeta.hash,
290
446
  },
291
447
  quoteResponse,
292
448
  slippagePercentage: 0,
293
- startTime: Date.now(),
449
+ startTime: approvalTime ?? Date.now(),
294
450
  });
451
+ // Add tokens to the token list
452
+ __classPrivateFieldGet(this, _BridgeStatusController_addTokens, "f").call(this, quoteResponse.quote.srcAsset);
453
+ __classPrivateFieldGet(this, _BridgeStatusController_addTokens, "f").call(this, quoteResponse.quote.destAsset);
295
454
  }
296
455
  catch {
297
456
  // Ignore errors here, we don't want to crash the app if this fails and tx submission succeeds
@@ -300,6 +459,9 @@ export class BridgeStatusController extends StaticIntervalPollingController() {
300
459
  };
301
460
  __classPrivateFieldSet(this, _BridgeStatusController_clientId, clientId, "f");
302
461
  __classPrivateFieldSet(this, _BridgeStatusController_fetchFn, fetchFn, "f");
462
+ __classPrivateFieldSet(this, _BridgeStatusController_addTransactionFn, addTransactionFn, "f");
463
+ __classPrivateFieldSet(this, _BridgeStatusController_addUserOperationFromTransactionFn, addUserOperationFromTransactionFn, "f");
464
+ __classPrivateFieldSet(this, _BridgeStatusController_estimateGasFeeFn, estimateGasFeeFn, "f");
303
465
  __classPrivateFieldSet(this, _BridgeStatusController_config, {
304
466
  customBridgeApiBaseUrl: config?.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,
305
467
  }, "f");
@@ -316,7 +478,7 @@ export class BridgeStatusController extends StaticIntervalPollingController() {
316
478
  __classPrivateFieldGet(this, _BridgeStatusController_restartPollingForIncompleteHistoryItems, "f").call(this);
317
479
  }
318
480
  }
319
- _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() {
481
+ _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() {
320
482
  return this.messagingSystem.call('AccountsController:getSelectedMultichainAccount');
321
483
  }, _BridgeStatusController_getMultichainSelectedAccountAddress = function _BridgeStatusController_getMultichainSelectedAccountAddress() {
322
484
  return __classPrivateFieldGet(this, _BridgeStatusController_instances, "m", _BridgeStatusController_getMultichainSelectedAccount).call(this)?.address ?? '';
@@ -1 +1 @@
1
- {"version":3,"file":"bridge-status-controller.mjs","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EACL,eAAe,EAEhB,oCAAoC;AAErC,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAE/E,OAAO,EAAE,WAAW,EAAY,wBAAwB;AAExD,OAAO,EACL,wBAAwB,EACxB,6BAA6B,EAC7B,sCAAsC,EACtC,mBAAmB,EACpB,wBAAoB;AACrB,OAAO,EAAE,WAAW,EAAwC,oBAAgB;AAO5E,OAAO,EACL,mBAAmB,EACnB,6BAA6B,EAC9B,kCAA8B;AAC/B,OAAO,EACL,iBAAiB,EACjB,sBAAsB,EACtB,sBAAsB,EACvB,gCAA4B;AAE7B,MAAM,QAAQ,GAA+C;IAC3D,uGAAuG;IACvG,wDAAwD;IACxD,SAAS,EAAE;QACT,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AASF,MAAM,OAAO,sBAAuB,SAAQ,+BAA+B,EAI1E;IAWC,YAAY,EACV,SAAS,EACT,KAAK,EACL,QAAQ,EACR,OAAO,EACP,MAAM,GASP;QACC,KAAK,CAAC;YACJ,IAAI,EAAE,6BAA6B;YACnC,QAAQ;YACR,SAAS;YACT,8BAA8B;YAC9B,KAAK,EAAE;gBACL,GAAG,sCAAsC;gBACzC,GAAG,KAAK;aACT;SACF,CAAC,CAAC;;QAlCL,0DAAwD,EAAE,EAAC;QAElD,mDAA0B;QAE1B,kDAAwB;QAExB,iDAEP;QA8DF,eA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AAI,CAA2C,CAAC;IAClD,CAAC;CAiYF;;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.mjs","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,eAAe,EACf,eAAe,EAEhB,oCAAoC;AAMrC,OAAO,EAAE,KAAK,EAAE,mCAAmC;AACnD,OAAO,EAAE,cAAc,EAAE,8BAA8B;AACvD,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAK/E,OAAO,EACL,iBAAiB,EACjB,eAAe,EAEhB,yCAAyC;AAE1C,OAAO,EAAE,WAAW,EAAY,wBAAwB;AACxD,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EACL,wBAAwB,EACxB,6BAA6B,EAC7B,sCAAsC,EACtC,mBAAmB,EACpB,wBAAoB;AACrB,OAAO,EAAE,WAAW,EAAwC,oBAAgB;AAQ5E,OAAO,EACL,mBAAmB,EACnB,6BAA6B,EAC9B,kCAA8B;AAC/B,OAAO,EAAE,iBAAiB,EAAE,wBAAoB;AAChD,OAAO,EACL,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,gBAAgB,EAChB,sBAAsB,EACvB,gCAA4B;AAC7B,OAAO,EAAE,gBAAgB,EAAE,gCAA4B;AAEvD,MAAM,QAAQ,GAA+C;IAC3D,uGAAuG;IACvG,wDAAwD;IACxD,SAAS,EAAE;QACT,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AASF,MAAM,OAAO,sBAAuB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ACxC,GAAG,6BAA6B,WAAW,EAC3C,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CACzB,CAAC;QAEF,eAAe;QACf,IAAI,CAAC,iBAAiB,CAAC,mBAAmB,CAAC,CAAC;QAE5C,+EAA+E;QAC/E,8CAA8C;QAC9C,mFAAmF;QACnF,uBAAA,IAAI,uEAAyC,MAA7C,IAAI,CAA2C,CAAC;IAClD,CAAC;CAioBF;;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,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BRIDGE_PROD_API_BASE_URL = exports.DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE = exports.BRIDGE_STATUS_CONTROLLER_NAME = exports.REFRESH_INTERVAL_MS = void 0;
3
+ exports.LINEA_DELAY_MS = exports.BRIDGE_PROD_API_BASE_URL = exports.DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE = exports.BRIDGE_STATUS_CONTROLLER_NAME = exports.REFRESH_INTERVAL_MS = void 0;
4
4
  exports.REFRESH_INTERVAL_MS = 10 * 1000;
5
5
  exports.BRIDGE_STATUS_CONTROLLER_NAME = 'BridgeStatusController';
6
6
  exports.DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE = {
7
7
  txHistory: {},
8
8
  };
9
9
  exports.BRIDGE_PROD_API_BASE_URL = 'https://bridge.api.cx.metamask.io';
10
+ exports.LINEA_DELAY_MS = 5000;
10
11
  //# sourceMappingURL=constants.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAEa,QAAA,mBAAmB,GAAG,EAAE,GAAG,IAAI,CAAC;AAEhC,QAAA,6BAA6B,GAAG,wBAAwB,CAAC;AAEzD,QAAA,sCAAsC,GACjD;IACE,SAAS,EAAE,EAAE;CACd,CAAC;AAES,QAAA,wBAAwB,GAAG,mCAAmC,CAAC","sourcesContent":["import type { BridgeStatusControllerState } from './types';\n\nexport const REFRESH_INTERVAL_MS = 10 * 1000;\n\nexport const BRIDGE_STATUS_CONTROLLER_NAME = 'BridgeStatusController';\n\nexport const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState =\n {\n txHistory: {},\n };\n\nexport const BRIDGE_PROD_API_BASE_URL = 'https://bridge.api.cx.metamask.io';\n"]}
1
+ {"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAEa,QAAA,mBAAmB,GAAG,EAAE,GAAG,IAAI,CAAC;AAEhC,QAAA,6BAA6B,GAAG,wBAAwB,CAAC;AAEzD,QAAA,sCAAsC,GACjD;IACE,SAAS,EAAE,EAAE;CACd,CAAC;AAES,QAAA,wBAAwB,GAAG,mCAAmC,CAAC;AAE/D,QAAA,cAAc,GAAG,IAAI,CAAC","sourcesContent":["import type { BridgeStatusControllerState } from './types';\n\nexport const REFRESH_INTERVAL_MS = 10 * 1000;\n\nexport const BRIDGE_STATUS_CONTROLLER_NAME = 'BridgeStatusController';\n\nexport const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState =\n {\n txHistory: {},\n };\n\nexport const BRIDGE_PROD_API_BASE_URL = 'https://bridge.api.cx.metamask.io';\n\nexport const LINEA_DELAY_MS = 5000;\n"]}
@@ -3,4 +3,5 @@ export declare const REFRESH_INTERVAL_MS: number;
3
3
  export declare const BRIDGE_STATUS_CONTROLLER_NAME = "BridgeStatusController";
4
4
  export declare const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState;
5
5
  export declare const BRIDGE_PROD_API_BASE_URL = "https://bridge.api.cx.metamask.io";
6
+ export declare const LINEA_DELAY_MS = 5000;
6
7
  //# sourceMappingURL=constants.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,oBAAgB;AAE3D,eAAO,MAAM,mBAAmB,QAAY,CAAC;AAE7C,eAAO,MAAM,6BAA6B,2BAA2B,CAAC;AAEtE,eAAO,MAAM,sCAAsC,EAAE,2BAGlD,CAAC;AAEJ,eAAO,MAAM,wBAAwB,sCAAsC,CAAC"}
1
+ {"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,oBAAgB;AAE3D,eAAO,MAAM,mBAAmB,QAAY,CAAC;AAE7C,eAAO,MAAM,6BAA6B,2BAA2B,CAAC;AAEtE,eAAO,MAAM,sCAAsC,EAAE,2BAGlD,CAAC;AAEJ,eAAO,MAAM,wBAAwB,sCAAsC,CAAC;AAE5E,eAAO,MAAM,cAAc,OAAO,CAAC"}
@@ -3,4 +3,5 @@ export declare const REFRESH_INTERVAL_MS: number;
3
3
  export declare const BRIDGE_STATUS_CONTROLLER_NAME = "BridgeStatusController";
4
4
  export declare const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState;
5
5
  export declare const BRIDGE_PROD_API_BASE_URL = "https://bridge.api.cx.metamask.io";
6
+ export declare const LINEA_DELAY_MS = 5000;
6
7
  //# sourceMappingURL=constants.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,oBAAgB;AAE3D,eAAO,MAAM,mBAAmB,QAAY,CAAC;AAE7C,eAAO,MAAM,6BAA6B,2BAA2B,CAAC;AAEtE,eAAO,MAAM,sCAAsC,EAAE,2BAGlD,CAAC;AAEJ,eAAO,MAAM,wBAAwB,sCAAsC,CAAC"}
1
+ {"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,oBAAgB;AAE3D,eAAO,MAAM,mBAAmB,QAAY,CAAC;AAE7C,eAAO,MAAM,6BAA6B,2BAA2B,CAAC;AAEtE,eAAO,MAAM,sCAAsC,EAAE,2BAGlD,CAAC;AAEJ,eAAO,MAAM,wBAAwB,sCAAsC,CAAC;AAE5E,eAAO,MAAM,cAAc,OAAO,CAAC"}
@@ -4,4 +4,5 @@ export const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE = {
4
4
  txHistory: {},
5
5
  };
6
6
  export const BRIDGE_PROD_API_BASE_URL = 'https://bridge.api.cx.metamask.io';
7
+ export const LINEA_DELAY_MS = 5000;
7
8
  //# sourceMappingURL=constants.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7C,MAAM,CAAC,MAAM,6BAA6B,GAAG,wBAAwB,CAAC;AAEtE,MAAM,CAAC,MAAM,sCAAsC,GACjD;IACE,SAAS,EAAE,EAAE;CACd,CAAC;AAEJ,MAAM,CAAC,MAAM,wBAAwB,GAAG,mCAAmC,CAAC","sourcesContent":["import type { BridgeStatusControllerState } from './types';\n\nexport const REFRESH_INTERVAL_MS = 10 * 1000;\n\nexport const BRIDGE_STATUS_CONTROLLER_NAME = 'BridgeStatusController';\n\nexport const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState =\n {\n txHistory: {},\n };\n\nexport const BRIDGE_PROD_API_BASE_URL = 'https://bridge.api.cx.metamask.io';\n"]}
1
+ {"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7C,MAAM,CAAC,MAAM,6BAA6B,GAAG,wBAAwB,CAAC;AAEtE,MAAM,CAAC,MAAM,sCAAsC,GACjD;IACE,SAAS,EAAE,EAAE;CACd,CAAC;AAEJ,MAAM,CAAC,MAAM,wBAAwB,GAAG,mCAAmC,CAAC;AAE5E,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAC","sourcesContent":["import type { BridgeStatusControllerState } from './types';\n\nexport const REFRESH_INTERVAL_MS = 10 * 1000;\n\nexport const BRIDGE_STATUS_CONTROLLER_NAME = 'BridgeStatusController';\n\nexport const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState =\n {\n txHistory: {},\n };\n\nexport const BRIDGE_PROD_API_BASE_URL = 'https://bridge.api.cx.metamask.io';\n\nexport const LINEA_DELAY_MS = 5000;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.cjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AA2BA,8EAA8E;AAC9E,2BAA2B;AAE3B,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,yCAAuB,CAAA;IACvB,mCAAiB,CAAA;AACnB,CAAC,EAHW,cAAc,8BAAd,cAAc,QAGzB;AAQD,IAAY,WAKX;AALD,WAAY,WAAW;IACrB,kCAAmB,CAAA;IACnB,gCAAiB,CAAA;IACjB,kCAAmB,CAAA;IACnB,oCAAqB,CAAA;AACvB,CAAC,EALW,WAAW,2BAAX,WAAW,QAKtB;AA2DD,IAAY,QAaX;AAbD,WAAY,QAAQ;IAClB,uBAAW,CAAA;IACX,2BAAe,CAAA;IACf,uCAA2B,CAAA;IAC3B,+BAAmB,CAAA;IACnB,+BAAmB,CAAA;IACnB,mCAAuB,CAAA;IACvB,qCAAyB,CAAA;IACzB,6BAAiB,CAAA;IACjB,6BAAiB,CAAA;IACjB,iCAAqB,CAAA;IACrB,2BAAe,CAAA;IACf,2BAAe,CAAA;AACjB,CAAC,EAbW,QAAQ,wBAAR,QAAQ,QAanB;AAED,IAAY,OAGX;AAHD,WAAY,OAAO;IACjB,oCAAyB,CAAA;IACzB,4BAAiB,CAAA;AACnB,CAAC,EAHW,OAAO,uBAAP,OAAO,QAGlB;AAaD,IAAY,WAIX;AAJD,WAAY,WAAW;IACrB,gCAAiB,CAAA;IACjB,4BAAa,CAAA;IACb,gCAAiB,CAAA;AACnB,CAAC,EAJW,WAAW,2BAAX,WAAW,QAItB;AAoDD,IAAY,kBAMX;AAND,WAAY,kBAAkB;IAC5B,0FAAoE,CAAA;IACpE,6DAAuC,CAAA;IACvC,4CAAsB,CAAA;IACtB,gDAA0B,CAAA;IAC1B,4CAAsB,CAAA;AACxB,CAAC,EANW,kBAAkB,kCAAlB,kBAAkB,QAM7B","sourcesContent":["import type { AccountsControllerGetSelectedMultichainAccountAction } from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n} from '@metamask/base-controller';\nimport type {\n ChainId,\n Quote,\n QuoteMetadata,\n QuoteResponse,\n TxData,\n} from '@metamask/bridge-controller';\nimport type {\n NetworkControllerFindNetworkClientIdByChainIdAction,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n} from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type {\n TransactionControllerGetStateAction,\n TransactionMeta,\n} from '@metamask/transaction-controller';\n\nimport type { BridgeStatusController } from './bridge-status-controller';\nimport type { BRIDGE_STATUS_CONTROLLER_NAME } from './constants';\n\n// All fields need to be types not interfaces, same with their children fields\n// o/w you get a type error\n\nexport enum BridgeClientId {\n EXTENSION = 'extension',\n MOBILE = 'mobile',\n}\n\nexport type FetchFunction = (\n input: RequestInfo | URL,\n init?: RequestInit,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => Promise<any>;\n\nexport enum StatusTypes {\n UNKNOWN = 'UNKNOWN',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n COMPLETE = 'COMPLETE',\n}\n\nexport type StatusRequest = {\n bridgeId: string; // lifi, socket, squid\n srcTxHash?: string; // lifi, socket, squid, might be undefined for STX\n bridge: string; // lifi, socket, squid\n srcChainId: ChainId; // lifi, socket, squid\n destChainId: ChainId; // lifi, socket, squid\n quote?: Quote; // squid\n refuel?: boolean; // lifi\n};\n\nexport type StatusRequestDto = Omit<\n StatusRequest,\n 'quote' | 'srcChainId' | 'destChainId' | 'refuel'\n> & {\n srcChainId: string; // lifi, socket, squid\n destChainId: string; // lifi, socket, squid\n requestId?: string;\n refuel?: string; // lifi\n};\n\nexport type StatusRequestWithSrcTxHash = StatusRequest & {\n srcTxHash: string;\n};\n\nexport type Asset = {\n chainId: ChainId;\n address: string;\n symbol: string;\n name: string;\n decimals: number;\n icon?: string | null;\n};\n\nexport type SrcChainStatus = {\n chainId: ChainId;\n /**\n * The txHash of the transaction on the source chain.\n * This might be undefined for smart transactions (STX)\n */\n txHash?: string;\n /**\n * The atomic amount of the token sent minus fees on the source chain\n */\n amount?: string;\n token?: Record<string, never> | Asset;\n};\n\nexport type DestChainStatus = {\n chainId: ChainId;\n txHash?: string;\n /**\n * The atomic amount of the token received on the destination chain\n */\n amount?: string;\n token?: Record<string, never> | Asset;\n};\n\nexport enum BridgeId {\n HOP = 'hop',\n CELER = 'celer',\n CELERCIRCLE = 'celercircle',\n CONNEXT = 'connext',\n POLYGON = 'polygon',\n AVALANCHE = 'avalanche',\n MULTICHAIN = 'multichain',\n AXELAR = 'axelar',\n ACROSS = 'across',\n STARGATE = 'stargate',\n RELAY = 'relay',\n MAYAN = 'mayan',\n}\n\nexport enum FeeType {\n METABRIDGE = 'metabridge',\n REFUEL = 'refuel',\n}\n\nexport type FeeData = {\n amount: string;\n asset: Asset;\n};\n\nexport type Protocol = {\n displayName?: string;\n icon?: string;\n name?: string; // for legacy quotes\n};\n\nexport enum ActionTypes {\n BRIDGE = 'bridge',\n SWAP = 'swap',\n REFUEL = 'refuel',\n}\n\nexport type Step = {\n action: ActionTypes;\n srcChainId: ChainId;\n destChainId?: ChainId;\n srcAsset: Asset;\n destAsset: Asset;\n srcAmount: string;\n destAmount: string;\n protocol: Protocol;\n};\n\nexport type StatusResponse = {\n status: StatusTypes;\n srcChain: SrcChainStatus;\n destChain?: DestChainStatus;\n bridge?: BridgeId;\n isExpectedToken?: boolean;\n isUnrecognizedRouterAddress?: boolean;\n refuel?: RefuelStatusResponse;\n};\n\nexport type RefuelStatusResponse = object & StatusResponse;\n\nexport type RefuelData = object & Step;\n\nexport type BridgeHistoryItem = {\n txMetaId: string; // Need this to handle STX that might not have a txHash immediately\n quote: Quote;\n status: StatusResponse;\n startTime?: number; // timestamp in ms\n estimatedProcessingTimeInSeconds: number;\n slippagePercentage: number;\n completionTime?: number; // timestamp in ms\n pricingData?: {\n /**\n * From QuoteMetadata.sentAmount.amount, the actual amount sent by user in non-atomic decimal form\n */\n amountSent: string;\n amountSentInUsd?: string;\n quotedGasInUsd?: string; // from QuoteMetadata.gasFee.usd\n quotedReturnInUsd?: string; // from QuoteMetadata.toTokenAmount.usd\n quotedRefuelSrcAmountInUsd?: string;\n quotedRefuelDestAmountInUsd?: string;\n };\n initialDestAssetBalance?: string;\n targetContractAddress?: string;\n account: string;\n hasApprovalTx: boolean;\n};\n\nexport enum BridgeStatusAction {\n START_POLLING_FOR_BRIDGE_TX_STATUS = 'startPollingForBridgeTxStatus',\n WIPE_BRIDGE_STATUS = 'wipeBridgeStatus',\n GET_STATE = 'getState',\n RESET_STATE = 'resetState',\n SUBMIT_TX = 'submitTx',\n}\n\nexport type TokenAmountValuesSerialized = {\n amount: string;\n valueInCurrency: string | null;\n usd: string | null;\n};\n\nexport type QuoteMetadataSerialized = {\n gasFee: TokenAmountValuesSerialized;\n /**\n * The total network fee for the bridge transaction\n * estimatedGasFees + relayerFees\n */\n totalNetworkFee: TokenAmountValuesSerialized;\n /**\n * The total max network fee for the bridge transaction\n * maxGasFees + relayerFees\n */\n totalMaxNetworkFee: TokenAmountValuesSerialized;\n toTokenAmount: TokenAmountValuesSerialized;\n /**\n * The adjusted return for the bridge transaction\n * destTokenAmount - totalNetworkFee\n */\n adjustedReturn: Omit<TokenAmountValuesSerialized, 'amount'>;\n /**\n * The actual amount sent by user in non-atomic decimal form\n * srcTokenAmount + metabridgeFee\n */\n sentAmount: TokenAmountValuesSerialized;\n swapRate: string; // destTokenAmount / sentAmount\n /**\n * The cost of the bridge transaction\n * sentAmount - adjustedReturn\n */\n cost: Omit<TokenAmountValuesSerialized, 'amount'>;\n};\n\nexport type StartPollingForBridgeTxStatusArgs = {\n bridgeTxMeta: TransactionMeta;\n statusRequest: StatusRequest;\n quoteResponse: QuoteResponse & QuoteMetadata;\n startTime?: BridgeHistoryItem['startTime'];\n slippagePercentage: BridgeHistoryItem['slippagePercentage'];\n initialDestAssetBalance?: BridgeHistoryItem['initialDestAssetBalance'];\n targetContractAddress?: BridgeHistoryItem['targetContractAddress'];\n};\n\n/**\n * Chrome: The BigNumber values are automatically serialized to strings when sent to the background\n * Firefox: The BigNumber values are not serialized to strings when sent to the background,\n * so we force the ui to do it manually, by using StartPollingForBridgeTxStatusArgsSerialized type on the startPollingForBridgeTxStatus action\n */\nexport type StartPollingForBridgeTxStatusArgsSerialized = Omit<\n StartPollingForBridgeTxStatusArgs,\n 'quoteResponse'\n> & {\n quoteResponse: QuoteResponse<string | TxData> & QuoteMetadata;\n};\n\nexport type SourceChainTxMetaId = string;\n\nexport type BridgeStatusControllerState = {\n txHistory: Record<SourceChainTxMetaId, BridgeHistoryItem>;\n};\n\n// Actions\ntype BridgeStatusControllerAction<\n FunctionName extends keyof BridgeStatusController,\n> = {\n type: `${typeof BRIDGE_STATUS_CONTROLLER_NAME}:${FunctionName}`;\n handler: BridgeStatusController[FunctionName];\n};\n\nexport type BridgeStatusControllerGetStateAction = ControllerGetStateAction<\n typeof BRIDGE_STATUS_CONTROLLER_NAME,\n BridgeStatusControllerState\n>;\n\n// Maps to BridgeController function names\nexport type BridgeStatusControllerStartPollingForBridgeTxStatusAction =\n BridgeStatusControllerAction<BridgeStatusAction.START_POLLING_FOR_BRIDGE_TX_STATUS>;\n\nexport type BridgeStatusControllerWipeBridgeStatusAction =\n BridgeStatusControllerAction<BridgeStatusAction.WIPE_BRIDGE_STATUS>;\n\nexport type BridgeStatusControllerResetStateAction =\n BridgeStatusControllerAction<BridgeStatusAction.RESET_STATE>;\n\nexport type BridgeStatusControllerSubmitTxAction =\n BridgeStatusControllerAction<BridgeStatusAction.SUBMIT_TX>;\n\nexport type BridgeStatusControllerActions =\n | BridgeStatusControllerStartPollingForBridgeTxStatusAction\n | BridgeStatusControllerWipeBridgeStatusAction\n | BridgeStatusControllerResetStateAction\n | BridgeStatusControllerGetStateAction\n | BridgeStatusControllerSubmitTxAction;\n\n// Events\nexport type BridgeStatusControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof BRIDGE_STATUS_CONTROLLER_NAME,\n BridgeStatusControllerState\n>;\n\nexport type BridgeStatusControllerBridgeTransactionCompleteEvent = {\n type: `${typeof BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionComplete`;\n payload: [{ bridgeHistoryItem: BridgeHistoryItem }];\n};\n\nexport type BridgeStatusControllerBridgeTransactionFailedEvent = {\n type: `${typeof BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionFailed`;\n payload: [{ bridgeHistoryItem: BridgeHistoryItem }];\n};\n\nexport type BridgeStatusControllerEvents =\n | BridgeStatusControllerStateChangeEvent\n | BridgeStatusControllerBridgeTransactionCompleteEvent\n | BridgeStatusControllerBridgeTransactionFailedEvent;\n\n/**\n * The external actions available to the BridgeStatusController.\n */\ntype AllowedActions =\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | AccountsControllerGetSelectedMultichainAccountAction\n | HandleSnapRequest\n | TransactionControllerGetStateAction;\n\n/**\n * The external events available to the BridgeStatusController.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger for the BridgeStatusController.\n */\nexport type BridgeStatusControllerMessenger = RestrictedMessenger<\n typeof BRIDGE_STATUS_CONTROLLER_NAME,\n BridgeStatusControllerActions | AllowedActions,\n BridgeStatusControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n"]}
1
+ {"version":3,"file":"types.cjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAkCA,8EAA8E;AAC9E,2BAA2B;AAE3B,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,yCAAuB,CAAA;IACvB,mCAAiB,CAAA;AACnB,CAAC,EAHW,cAAc,8BAAd,cAAc,QAGzB;AAQD,IAAY,WAKX;AALD,WAAY,WAAW;IACrB,kCAAmB,CAAA;IACnB,gCAAiB,CAAA;IACjB,kCAAmB,CAAA;IACnB,oCAAqB,CAAA;AACvB,CAAC,EALW,WAAW,2BAAX,WAAW,QAKtB;AAqED,IAAY,QAaX;AAbD,WAAY,QAAQ;IAClB,uBAAW,CAAA;IACX,2BAAe,CAAA;IACf,uCAA2B,CAAA;IAC3B,+BAAmB,CAAA;IACnB,+BAAmB,CAAA;IACnB,mCAAuB,CAAA;IACvB,qCAAyB,CAAA;IACzB,6BAAiB,CAAA;IACjB,6BAAiB,CAAA;IACjB,iCAAqB,CAAA;IACrB,2BAAe,CAAA;IACf,2BAAe,CAAA;AACjB,CAAC,EAbW,QAAQ,wBAAR,QAAQ,QAanB;AAED,IAAY,OAGX;AAHD,WAAY,OAAO;IACjB,oCAAyB,CAAA;IACzB,4BAAiB,CAAA;AACnB,CAAC,EAHW,OAAO,uBAAP,OAAO,QAGlB;AAaD,IAAY,WAIX;AAJD,WAAY,WAAW;IACrB,gCAAiB,CAAA;IACjB,4BAAa,CAAA;IACb,gCAAiB,CAAA;AACnB,CAAC,EAJW,WAAW,2BAAX,WAAW,QAItB;AAoDD,IAAY,kBAMX;AAND,WAAY,kBAAkB;IAC5B,0FAAoE,CAAA;IACpE,6DAAuC,CAAA;IACvC,4CAAsB,CAAA;IACtB,gDAA0B,CAAA;IAC1B,4CAAsB,CAAA;AACxB,CAAC,EANW,kBAAkB,kCAAlB,kBAAkB,QAM7B","sourcesContent":["import type {\n AccountsControllerGetAccountByAddressAction,\n AccountsControllerGetSelectedMultichainAccountAction,\n} from '@metamask/accounts-controller';\nimport type { TokensControllerAddDetectedTokensAction } from '@metamask/assets-controllers';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n} from '@metamask/base-controller';\nimport type {\n BridgeBackgroundAction,\n BridgeControllerAction,\n ChainId,\n Quote,\n QuoteMetadata,\n QuoteResponse,\n TxData,\n} from '@metamask/bridge-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n NetworkControllerFindNetworkClientIdByChainIdAction,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n} from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type {\n TransactionControllerGetStateAction,\n TransactionMeta,\n} from '@metamask/transaction-controller';\n\nimport type { BridgeStatusController } from './bridge-status-controller';\nimport type { BRIDGE_STATUS_CONTROLLER_NAME } from './constants';\n\n// All fields need to be types not interfaces, same with their children fields\n// o/w you get a type error\n\nexport enum BridgeClientId {\n EXTENSION = 'extension',\n MOBILE = 'mobile',\n}\n\nexport type FetchFunction = (\n input: RequestInfo | URL,\n init?: RequestInit,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => Promise<any>;\n\nexport enum StatusTypes {\n UNKNOWN = 'UNKNOWN',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n COMPLETE = 'COMPLETE',\n}\n\n/**\n * These fields are specific to Solana transactions and can likely be infered from TransactionMeta\n *\n * @deprecated these should be removed eventually\n */\nexport type SolanaTransactionMeta = {\n isSolana: boolean;\n isBridgeTx: boolean;\n};\n\nexport type StatusRequest = {\n bridgeId: string; // lifi, socket, squid\n srcTxHash?: string; // lifi, socket, squid, might be undefined for STX\n bridge: string; // lifi, socket, squid\n srcChainId: ChainId; // lifi, socket, squid\n destChainId: ChainId; // lifi, socket, squid\n quote?: Quote; // squid\n refuel?: boolean; // lifi\n};\n\nexport type StatusRequestDto = Omit<\n StatusRequest,\n 'quote' | 'srcChainId' | 'destChainId' | 'refuel'\n> & {\n srcChainId: string; // lifi, socket, squid\n destChainId: string; // lifi, socket, squid\n requestId?: string;\n refuel?: string; // lifi\n};\n\nexport type StatusRequestWithSrcTxHash = StatusRequest & {\n srcTxHash: string;\n};\n\nexport type Asset = {\n chainId: ChainId;\n address: string;\n symbol: string;\n name: string;\n decimals: number;\n icon?: string | null;\n};\n\nexport type SrcChainStatus = {\n chainId: ChainId;\n /**\n * The txHash of the transaction on the source chain.\n * This might be undefined for smart transactions (STX)\n */\n txHash?: string;\n /**\n * The atomic amount of the token sent minus fees on the source chain\n */\n amount?: string;\n token?: Record<string, never> | Asset;\n};\n\nexport type DestChainStatus = {\n chainId: ChainId;\n txHash?: string;\n /**\n * The atomic amount of the token received on the destination chain\n */\n amount?: string;\n token?: Record<string, never> | Asset;\n};\n\nexport enum BridgeId {\n HOP = 'hop',\n CELER = 'celer',\n CELERCIRCLE = 'celercircle',\n CONNEXT = 'connext',\n POLYGON = 'polygon',\n AVALANCHE = 'avalanche',\n MULTICHAIN = 'multichain',\n AXELAR = 'axelar',\n ACROSS = 'across',\n STARGATE = 'stargate',\n RELAY = 'relay',\n MAYAN = 'mayan',\n}\n\nexport enum FeeType {\n METABRIDGE = 'metabridge',\n REFUEL = 'refuel',\n}\n\nexport type FeeData = {\n amount: string;\n asset: Asset;\n};\n\nexport type Protocol = {\n displayName?: string;\n icon?: string;\n name?: string; // for legacy quotes\n};\n\nexport enum ActionTypes {\n BRIDGE = 'bridge',\n SWAP = 'swap',\n REFUEL = 'refuel',\n}\n\nexport type Step = {\n action: ActionTypes;\n srcChainId: ChainId;\n destChainId?: ChainId;\n srcAsset: Asset;\n destAsset: Asset;\n srcAmount: string;\n destAmount: string;\n protocol: Protocol;\n};\n\nexport type StatusResponse = {\n status: StatusTypes;\n srcChain: SrcChainStatus;\n destChain?: DestChainStatus;\n bridge?: BridgeId;\n isExpectedToken?: boolean;\n isUnrecognizedRouterAddress?: boolean;\n refuel?: RefuelStatusResponse;\n};\n\nexport type RefuelStatusResponse = object & StatusResponse;\n\nexport type RefuelData = object & Step;\n\nexport type BridgeHistoryItem = {\n txMetaId: string; // Need this to handle STX that might not have a txHash immediately\n quote: Quote;\n status: StatusResponse;\n startTime?: number; // timestamp in ms\n estimatedProcessingTimeInSeconds: number;\n slippagePercentage: number;\n completionTime?: number; // timestamp in ms\n pricingData?: {\n /**\n * From QuoteMetadata.sentAmount.amount, the actual amount sent by user in non-atomic decimal form\n */\n amountSent: string;\n amountSentInUsd?: string;\n quotedGasInUsd?: string; // from QuoteMetadata.gasFee.usd\n quotedReturnInUsd?: string; // from QuoteMetadata.toTokenAmount.usd\n quotedRefuelSrcAmountInUsd?: string;\n quotedRefuelDestAmountInUsd?: string;\n };\n initialDestAssetBalance?: string;\n targetContractAddress?: string;\n account: string;\n hasApprovalTx: boolean;\n};\n\nexport enum BridgeStatusAction {\n START_POLLING_FOR_BRIDGE_TX_STATUS = 'startPollingForBridgeTxStatus',\n WIPE_BRIDGE_STATUS = 'wipeBridgeStatus',\n GET_STATE = 'getState',\n RESET_STATE = 'resetState',\n SUBMIT_TX = 'submitTx',\n}\n\nexport type TokenAmountValuesSerialized = {\n amount: string;\n valueInCurrency: string | null;\n usd: string | null;\n};\n\nexport type QuoteMetadataSerialized = {\n gasFee: TokenAmountValuesSerialized;\n /**\n * The total network fee for the bridge transaction\n * estimatedGasFees + relayerFees\n */\n totalNetworkFee: TokenAmountValuesSerialized;\n /**\n * The total max network fee for the bridge transaction\n * maxGasFees + relayerFees\n */\n totalMaxNetworkFee: TokenAmountValuesSerialized;\n toTokenAmount: TokenAmountValuesSerialized;\n /**\n * The adjusted return for the bridge transaction\n * destTokenAmount - totalNetworkFee\n */\n adjustedReturn: Omit<TokenAmountValuesSerialized, 'amount'>;\n /**\n * The actual amount sent by user in non-atomic decimal form\n * srcTokenAmount + metabridgeFee\n */\n sentAmount: TokenAmountValuesSerialized;\n swapRate: string; // destTokenAmount / sentAmount\n /**\n * The cost of the bridge transaction\n * sentAmount - adjustedReturn\n */\n cost: Omit<TokenAmountValuesSerialized, 'amount'>;\n};\n\nexport type StartPollingForBridgeTxStatusArgs = {\n bridgeTxMeta: TransactionMeta;\n statusRequest: StatusRequest;\n quoteResponse: QuoteResponse & QuoteMetadata;\n startTime?: BridgeHistoryItem['startTime'];\n slippagePercentage: BridgeHistoryItem['slippagePercentage'];\n initialDestAssetBalance?: BridgeHistoryItem['initialDestAssetBalance'];\n targetContractAddress?: BridgeHistoryItem['targetContractAddress'];\n};\n\n/**\n * Chrome: The BigNumber values are automatically serialized to strings when sent to the background\n * Firefox: The BigNumber values are not serialized to strings when sent to the background,\n * so we force the ui to do it manually, by using StartPollingForBridgeTxStatusArgsSerialized type on the startPollingForBridgeTxStatus action\n */\nexport type StartPollingForBridgeTxStatusArgsSerialized = Omit<\n StartPollingForBridgeTxStatusArgs,\n 'quoteResponse'\n> & {\n quoteResponse: QuoteResponse<string | TxData> & QuoteMetadata;\n};\n\nexport type SourceChainTxMetaId = string;\n\nexport type BridgeStatusControllerState = {\n txHistory: Record<SourceChainTxMetaId, BridgeHistoryItem>;\n};\n\n// Actions\ntype BridgeStatusControllerAction<\n FunctionName extends keyof BridgeStatusController,\n> = {\n type: `${typeof BRIDGE_STATUS_CONTROLLER_NAME}:${FunctionName}`;\n handler: BridgeStatusController[FunctionName];\n};\n\nexport type BridgeStatusControllerGetStateAction = ControllerGetStateAction<\n typeof BRIDGE_STATUS_CONTROLLER_NAME,\n BridgeStatusControllerState\n>;\n\n// Maps to BridgeController function names\nexport type BridgeStatusControllerStartPollingForBridgeTxStatusAction =\n BridgeStatusControllerAction<BridgeStatusAction.START_POLLING_FOR_BRIDGE_TX_STATUS>;\n\nexport type BridgeStatusControllerWipeBridgeStatusAction =\n BridgeStatusControllerAction<BridgeStatusAction.WIPE_BRIDGE_STATUS>;\n\nexport type BridgeStatusControllerResetStateAction =\n BridgeStatusControllerAction<BridgeStatusAction.RESET_STATE>;\n\nexport type BridgeStatusControllerSubmitTxAction =\n BridgeStatusControllerAction<BridgeStatusAction.SUBMIT_TX>;\n\nexport type BridgeStatusControllerActions =\n | BridgeStatusControllerStartPollingForBridgeTxStatusAction\n | BridgeStatusControllerWipeBridgeStatusAction\n | BridgeStatusControllerResetStateAction\n | BridgeStatusControllerGetStateAction\n | BridgeStatusControllerSubmitTxAction;\n\n// Events\nexport type BridgeStatusControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof BRIDGE_STATUS_CONTROLLER_NAME,\n BridgeStatusControllerState\n>;\n\nexport type BridgeStatusControllerBridgeTransactionCompleteEvent = {\n type: `${typeof BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionComplete`;\n payload: [{ bridgeHistoryItem: BridgeHistoryItem }];\n};\n\nexport type BridgeStatusControllerBridgeTransactionFailedEvent = {\n type: `${typeof BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionFailed`;\n payload: [{ bridgeHistoryItem: BridgeHistoryItem }];\n};\n\nexport type BridgeStatusControllerEvents =\n | BridgeStatusControllerStateChangeEvent\n | BridgeStatusControllerBridgeTransactionCompleteEvent\n | BridgeStatusControllerBridgeTransactionFailedEvent;\n\n/**\n * The external actions available to the BridgeStatusController.\n */\ntype AllowedActions =\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | AccountsControllerGetSelectedMultichainAccountAction\n | HandleSnapRequest\n | TransactionControllerGetStateAction\n | BridgeControllerAction<BridgeBackgroundAction.GET_BRIDGE_ERC20_ALLOWANCE>\n | GetGasFeeState\n | AccountsControllerGetAccountByAddressAction\n | TokensControllerAddDetectedTokensAction;\n\n/**\n * The external events available to the BridgeStatusController.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger for the BridgeStatusController.\n */\nexport type BridgeStatusControllerMessenger = RestrictedMessenger<\n typeof BRIDGE_STATUS_CONTROLLER_NAME,\n BridgeStatusControllerActions | AllowedActions,\n BridgeStatusControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n"]}