@metamask/bridge-controller 74.0.0 → 75.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/dist/bridge-controller.cjs +17 -19
  3. package/dist/bridge-controller.cjs.map +1 -1
  4. package/dist/bridge-controller.d.cts +5 -13
  5. package/dist/bridge-controller.d.cts.map +1 -1
  6. package/dist/bridge-controller.d.mts +5 -13
  7. package/dist/bridge-controller.d.mts.map +1 -1
  8. package/dist/bridge-controller.mjs +18 -20
  9. package/dist/bridge-controller.mjs.map +1 -1
  10. package/dist/constants/bridge.cjs +2 -0
  11. package/dist/constants/bridge.cjs.map +1 -1
  12. package/dist/constants/bridge.d.cts +4 -1
  13. package/dist/constants/bridge.d.cts.map +1 -1
  14. package/dist/constants/bridge.d.mts +4 -1
  15. package/dist/constants/bridge.d.mts.map +1 -1
  16. package/dist/constants/bridge.mjs +2 -0
  17. package/dist/constants/bridge.mjs.map +1 -1
  18. package/dist/constants/chains.cjs +4 -1
  19. package/dist/constants/chains.cjs.map +1 -1
  20. package/dist/constants/chains.d.cts +3 -0
  21. package/dist/constants/chains.d.cts.map +1 -1
  22. package/dist/constants/chains.d.mts +3 -0
  23. package/dist/constants/chains.d.mts.map +1 -1
  24. package/dist/constants/chains.mjs +3 -0
  25. package/dist/constants/chains.mjs.map +1 -1
  26. package/dist/constants/tokens.cjs +12 -0
  27. package/dist/constants/tokens.cjs.map +1 -1
  28. package/dist/constants/tokens.d.cts +7 -0
  29. package/dist/constants/tokens.d.cts.map +1 -1
  30. package/dist/constants/tokens.d.mts +7 -0
  31. package/dist/constants/tokens.d.mts.map +1 -1
  32. package/dist/constants/tokens.mjs +12 -0
  33. package/dist/constants/tokens.mjs.map +1 -1
  34. package/dist/index.cjs +2 -2
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +2 -2
  37. package/dist/index.d.cts.map +1 -1
  38. package/dist/index.d.mts +2 -2
  39. package/dist/index.d.mts.map +1 -1
  40. package/dist/index.mjs +2 -2
  41. package/dist/index.mjs.map +1 -1
  42. package/dist/selectors.d.cts +143 -143
  43. package/dist/selectors.d.mts +143 -143
  44. package/dist/types.cjs +11 -1
  45. package/dist/types.cjs.map +1 -1
  46. package/dist/types.d.cts +11 -2
  47. package/dist/types.d.cts.map +1 -1
  48. package/dist/types.d.mts +11 -2
  49. package/dist/types.d.mts.map +1 -1
  50. package/dist/types.mjs +10 -0
  51. package/dist/types.mjs.map +1 -1
  52. package/dist/utils/feature-flags.d.cts +1 -1
  53. package/dist/utils/feature-flags.d.mts +1 -1
  54. package/dist/utils/fetch.cjs +3 -1
  55. package/dist/utils/fetch.cjs.map +1 -1
  56. package/dist/utils/fetch.d.cts +3 -3
  57. package/dist/utils/fetch.d.cts.map +1 -1
  58. package/dist/utils/fetch.d.mts +3 -3
  59. package/dist/utils/fetch.d.mts.map +1 -1
  60. package/dist/utils/fetch.mjs +3 -1
  61. package/dist/utils/fetch.mjs.map +1 -1
  62. package/dist/utils/metrics/properties.cjs +2 -0
  63. package/dist/utils/metrics/properties.cjs.map +1 -1
  64. package/dist/utils/metrics/properties.d.cts +2 -0
  65. package/dist/utils/metrics/properties.d.cts.map +1 -1
  66. package/dist/utils/metrics/properties.d.mts +2 -0
  67. package/dist/utils/metrics/properties.d.mts.map +1 -1
  68. package/dist/utils/metrics/properties.mjs +2 -0
  69. package/dist/utils/metrics/properties.mjs.map +1 -1
  70. package/dist/utils/metrics/types.cjs.map +1 -1
  71. package/dist/utils/metrics/types.d.cts +30 -17
  72. package/dist/utils/metrics/types.d.cts.map +1 -1
  73. package/dist/utils/metrics/types.d.mts +30 -17
  74. package/dist/utils/metrics/types.d.mts.map +1 -1
  75. package/dist/utils/metrics/types.mjs.map +1 -1
  76. package/dist/utils/quote.cjs +2 -2
  77. package/dist/utils/quote.cjs.map +1 -1
  78. package/dist/utils/quote.d.cts +1 -1
  79. package/dist/utils/quote.d.cts.map +1 -1
  80. package/dist/utils/quote.d.mts +1 -1
  81. package/dist/utils/quote.d.mts.map +1 -1
  82. package/dist/utils/quote.mjs +1 -1
  83. package/dist/utils/quote.mjs.map +1 -1
  84. package/dist/utils/validators.cjs +2 -9
  85. package/dist/utils/validators.cjs.map +1 -1
  86. package/dist/utils/validators.d.cts +3 -8
  87. package/dist/utils/validators.d.cts.map +1 -1
  88. package/dist/utils/validators.d.mts +3 -8
  89. package/dist/utils/validators.d.mts.map +1 -1
  90. package/dist/utils/validators.mjs +1 -8
  91. package/dist/utils/validators.mjs.map +1 -1
  92. package/package.json +6 -6
package/CHANGELOG.md CHANGED
@@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [75.0.0]
11
+
12
+ ### Added
13
+
14
+ - Add `QUICK_BUY_FOLLOW_TRADING`, `QUICK_BUY_TOKEN_DETAILS`, `BATCH_SELL` and `UNIFIED_SWAP_BRIDGE` to FeatureId enum ([#8964](https://github.com/MetaMask/core/pull/8964))
15
+ - Update metrics schema with `batch_id` property ([#8964](https://github.com/MetaMask/core/pull/8964))
16
+ - Add `ARC` network support ([#9007](https://github.com/MetaMask/core/pull/9007))
17
+ - Add `ARC` into constants `ALLOWED_BRIDGE_CHAIN_IDS`, `SWAPS_TOKEN_OBJECT` and `NETWORK_TO_NAME_MAP`
18
+
19
+ ### Changed
20
+
21
+ - **BREAKING**: require all events to have the `feature_id` property ([#8964](https://github.com/MetaMask/core/pull/8964))
22
+ - **BREAKING**: require FeatureId argument when calling `BridgeController:fetchQuotes` ([#8964](https://github.com/MetaMask/core/pull/8964))
23
+ - Rename FeatureIds to match segment property conventions ([#8964](https://github.com/MetaMask/core/pull/8964))
24
+ - `quickBuy` to `quick_buy_follow_trading` and `quick_buy_token_details`
25
+ - `dappSwap` to `dapp_swap`
26
+ - Bump `@metamask/accounts-controller` from `^39.0.0` to `^39.0.1` ([#9058](https://github.com/MetaMask/core/pull/9058))
27
+ - Bump `@metamask/assets-controller` from `^8.3.2` to `^8.3.3` ([#9058](https://github.com/MetaMask/core/pull/9058))
28
+ - Bump `@metamask/assets-controllers` from `^108.5.0` to `^108.6.0` ([#9058](https://github.com/MetaMask/core/pull/9058))
29
+ - Bump `@metamask/controller-utils` from `^12.1.0` to `^12.1.1` ([#9058](https://github.com/MetaMask/core/pull/9058))
30
+ - Bump `@metamask/transaction-controller` from `^67.0.0` to `^67.1.0` ([#9066](https://github.com/MetaMask/core/pull/9066))
31
+
10
32
  ## [74.0.0]
11
33
 
12
34
  ### Added
@@ -1563,7 +1585,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1563
1585
 
1564
1586
  - Initial release ([#5317](https://github.com/MetaMask/core/pull/5317))
1565
1587
 
1566
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/bridge-controller@74.0.0...HEAD
1588
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/bridge-controller@75.0.0...HEAD
1589
+ [75.0.0]: https://github.com/MetaMask/core/compare/@metamask/bridge-controller@74.0.0...@metamask/bridge-controller@75.0.0
1567
1590
  [74.0.0]: https://github.com/MetaMask/core/compare/@metamask/bridge-controller@73.2.1...@metamask/bridge-controller@74.0.0
1568
1591
  [73.2.1]: https://github.com/MetaMask/core/compare/@metamask/bridge-controller@73.2.0...@metamask/bridge-controller@73.2.1
1569
1592
  [73.2.0]: https://github.com/MetaMask/core/compare/@metamask/bridge-controller@73.1.0...@metamask/bridge-controller@73.2.0
@@ -184,7 +184,7 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
184
184
  if (quoteRequestIndex >= quoteRequestCount) {
185
185
  return;
186
186
  }
187
- __classPrivateFieldGet(this, _BridgeController_trackInputChangedEvents, "f").call(this, paramsToUpdate, quoteRequestIndex);
187
+ __classPrivateFieldGet(this, _BridgeController_trackInputChangedEvents, "f").call(this, paramsToUpdate, context.feature_id, quoteRequestIndex);
188
188
  this.resetState(constants_1.AbortReason.QuoteRequestUpdated, quoteRequestIndex);
189
189
  this.update((state) => {
190
190
  // Update only the specified quote request and keep the rest of the quote requests unchanged
@@ -221,11 +221,11 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
221
221
  * This method does not start polling for quotes and does not emit UnifiedSwapBridge events
222
222
  *
223
223
  * @param quoteRequest - The parameters for quote requests to fetch
224
- * @param abortSignal - The abort signal to cancel all the requests
225
224
  * @param featureId - The feature ID that maps to quoteParam overrides from LD
225
+ * @param abortSignal - The abort signal to cancel all the requests
226
226
  * @returns A list of validated quotes
227
227
  */
228
- this.fetchQuotes = async (quoteRequest, abortSignal = null, featureId = null) => {
228
+ this.fetchQuotes = async (quoteRequest, featureId, abortSignal = null) => {
229
229
  const bridgeFeatureFlags = (0, feature_flags_1.getBridgeFeatureFlags)(this.messenger);
230
230
  const jwt = await __classPrivateFieldGet(this, _BridgeController_getJwt, "f").call(this);
231
231
  // If featureId is specified, retrieve the quoteRequestOverrides for that featureId
@@ -237,7 +237,7 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
237
237
  const { quotes: baseQuotes, validationFailures } = await (0, fetch_1.fetchBridgeQuotes)(quoteRequestOverrides
238
238
  ? { ...quoteRequest, ...quoteRequestOverrides, resetApproval }
239
239
  : { ...quoteRequest, resetApproval }, abortSignal, __classPrivateFieldGet(this, _BridgeController_clientId, "f"), jwt, __classPrivateFieldGet(this, _BridgeController_fetchFn, "f"), __classPrivateFieldGet(this, _BridgeController_config, "f").customBridgeApiBaseUrl ?? bridge_1.BRIDGE_PROD_API_BASE_URL, featureId, __classPrivateFieldGet(this, _BridgeController_clientVersion, "f"));
240
- __classPrivateFieldGet(this, _BridgeController_trackQuoteValidationFailures, "f").call(this, validationFailures);
240
+ __classPrivateFieldGet(this, _BridgeController_trackQuoteValidationFailures, "f").call(this, validationFailures, featureId);
241
241
  const quotesWithFees = await (0, quote_fees_1.appendFeesToQuotes)(baseQuotes, this.messenger, __classPrivateFieldGet(this, _BridgeController_getLayer1GasFee, "f"), __classPrivateFieldGet(this, _BridgeController_instances, "m", _BridgeController_getMultichainSelectedAccount).call(this, quoteRequest.walletAddress));
242
242
  return (0, quote_1.sortQuotes)(quotesWithFees, featureId);
243
243
  };
@@ -287,11 +287,12 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
287
287
  console.log(`Failed to fetch batch sell trades`, error);
288
288
  }
289
289
  };
290
- _BridgeController_trackQuoteValidationFailures.set(this, (validationFailures) => {
290
+ _BridgeController_trackQuoteValidationFailures.set(this, (validationFailures, featureId) => {
291
291
  if (validationFailures.length === 0) {
292
292
  return;
293
293
  }
294
294
  this.trackUnifiedSwapBridgeEvent(constants_1.UnifiedSwapBridgeEventName.QuotesValidationFailed, {
295
+ feature_id: featureId,
295
296
  failures: validationFailures,
296
297
  location: __classPrivateFieldGet(this, _BridgeController_location, "f"),
297
298
  });
@@ -322,12 +323,8 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
322
323
  // Get unique assetIds for all quote requests
323
324
  const assetIds = new Set(quoteRequests
324
325
  .flatMap((quoteRequest) => [
325
- quoteRequest.srcTokenAddress && quoteRequest.srcChainId
326
- ? (0, assets_1.getAssetIdsForToken)(quoteRequest.srcTokenAddress, quoteRequest.srcChainId)
327
- : undefined,
328
- quoteRequest.destTokenAddress && quoteRequest.destChainId
329
- ? (0, assets_1.getAssetIdsForToken)(quoteRequest.destTokenAddress, quoteRequest.destChainId)
330
- : undefined,
326
+ (0, assets_1.getAssetIdsForToken)(quoteRequest.srcTokenAddress, quoteRequest.srcChainId),
327
+ (0, assets_1.getAssetIdsForToken)(quoteRequest.destTokenAddress, quoteRequest.destChainId),
331
328
  ].flat())
332
329
  .filter((assetId) => !(0, selectors_1.selectIsAssetExchangeRateInState)(exchangeRateSources, assetId)));
333
330
  const currency = __classPrivateFieldGet(this, _BridgeController_getUseAssetsControllerForRates, "f").call(this)
@@ -441,8 +438,8 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
441
438
  this.setLocation = (location) => {
442
439
  __classPrivateFieldSet(this, _BridgeController_location, location, "f");
443
440
  };
444
- this.resetState = (reason = constants_1.AbortReason.ResetState, quoteRequestIndex = null) => {
445
- this.stopPollingForQuotes(reason);
441
+ this.resetState = (reason = constants_1.AbortReason.ResetState, quoteRequestIndex = null, context) => {
442
+ this.stopPollingForQuotes(reason, context);
446
443
  this.update((state) => {
447
444
  // Cannot do direct assignment to state, i.e. state = {... }, need to manually assign each field
448
445
  if (quoteRequestIndex === null) {
@@ -539,11 +536,11 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
539
536
  __classPrivateFieldGet(this, _BridgeController_setMinimumBalanceForRentExemptionInLamports, "f").call(this, firstQuoteRequest.srcChainId, selectedAccount?.metadata?.snap?.id);
540
537
  // Use SSE if enabled and return early
541
538
  if (shouldStream || isBatchSellRequest) {
542
- await __classPrivateFieldGet(this, _BridgeController_handleQuoteStreaming, "f").call(this, quoteRequests, jwt, selectedAccount);
539
+ await __classPrivateFieldGet(this, _BridgeController_handleQuoteStreaming, "f").call(this, quoteRequests, context.feature_id, jwt, selectedAccount);
543
540
  return;
544
541
  }
545
542
  // Otherwise use regular fetch
546
- const quotes = await this.fetchQuotes(firstQuoteRequest, __classPrivateFieldGet(this, _BridgeController_abortController, "f")?.signal);
543
+ const quotes = await this.fetchQuotes(firstQuoteRequest, context.feature_id, __classPrivateFieldGet(this, _BridgeController_abortController, "f")?.signal);
547
544
  this.update((state) => {
548
545
  // Set the initial load time if this is the first fetch
549
546
  if (state.quotesRefreshCount ===
@@ -609,7 +606,7 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
609
606
  this.stopAllPolling();
610
607
  }
611
608
  });
612
- _BridgeController_handleQuoteStreaming.set(this, async (quoteRequests, jwt, selectedAccount) => {
609
+ _BridgeController_handleQuoteStreaming.set(this, async (quoteRequests, featureId, jwt, selectedAccount) => {
613
610
  /**
614
611
  * Tracks the number of valid quotes received from the current stream, which is used
615
612
  * to determine when to clear the quotes list and set the initial load time
@@ -620,8 +617,8 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
620
617
  * before setting quotesLoadingStatus to FETCHED
621
618
  */
622
619
  const pendingFeeAppendPromises = new Set();
623
- await (0, fetch_1.fetchBridgeQuoteStream)(__classPrivateFieldGet(this, _BridgeController_fetchFn, "f"), quoteRequests, __classPrivateFieldGet(this, _BridgeController_abortController, "f")?.signal, __classPrivateFieldGet(this, _BridgeController_clientId, "f"), jwt, __classPrivateFieldGet(this, _BridgeController_config, "f").customBridgeApiBaseUrl ?? bridge_1.BRIDGE_PROD_API_BASE_URL, {
624
- onQuoteValidationFailure: __classPrivateFieldGet(this, _BridgeController_trackQuoteValidationFailures, "f"),
620
+ await (0, fetch_1.fetchBridgeQuoteStream)(__classPrivateFieldGet(this, _BridgeController_fetchFn, "f"), quoteRequests, __classPrivateFieldGet(this, _BridgeController_abortController, "f")?.signal, featureId, __classPrivateFieldGet(this, _BridgeController_clientId, "f"), jwt, __classPrivateFieldGet(this, _BridgeController_config, "f").customBridgeApiBaseUrl ?? bridge_1.BRIDGE_PROD_API_BASE_URL, {
621
+ onQuoteValidationFailure: (validationFailures) => __classPrivateFieldGet(this, _BridgeController_trackQuoteValidationFailures, "f").call(this, validationFailures, featureId),
625
622
  onValidQuoteReceived: async (quote) => {
626
623
  const feeAppendPromise = (async () => {
627
624
  const quotesWithFees = await (0, quote_fees_1.appendFeesToQuotes)([quote], this.messenger, __classPrivateFieldGet(this, _BridgeController_getLayer1GasFee, "f"), selectedAccount);
@@ -818,7 +815,7 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
818
815
  return baseProperties;
819
816
  }
820
817
  });
821
- _BridgeController_trackInputChangedEvents.set(this, (paramsToUpdate, quoteRequestIndex = 0) => {
818
+ _BridgeController_trackInputChangedEvents.set(this, (paramsToUpdate, featureId, quoteRequestIndex = 0) => {
822
819
  Object.entries(paramsToUpdate).forEach(([key, value]) => {
823
820
  const inputKey = properties_1.toInputChangedPropertyKey[key];
824
821
  const inputValue = properties_1.toInputChangedPropertyValue[key]?.(paramsToUpdate);
@@ -831,6 +828,7 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
831
828
  input: inputKey,
832
829
  input_value: inputValue,
833
830
  location: __classPrivateFieldGet(this, _BridgeController_location, "f"),
831
+ feature_id: featureId,
834
832
  });
835
833
  }
836
834
  });
@@ -1 +1 @@
1
- {"version":3,"file":"bridge-controller.cjs","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qEAAqE;AACrE,wDAAqD;AACrD,wDAAoD;AACpD,wDAAwD;AAIxD,mEAAuD;AACvD,qEAA+E;AAK/E,mDAM4B;AAC5B,mDAA+C;AAC/C,iDAA6D;AAC7D,mDAA+C;AAC/C,+CAGqB;AACrB,uCAAwC;AAWxC,+CAAsE;AACtE,iDAAuD;AACvD,+CAMwB;AACxB,iEAIiC;AACjC,6DAG+B;AAC/B,6CAKuB;AACvB,6DAKmC;AACnC,+DAQoC;AAOpC,6CAIuB;AACvB,uDAAwD;AACxD,6CAA4E;AAG5E,MAAM,QAAQ,GAAyC;IACrD,YAAY,EAAE;QACZ,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,MAAM,EAAE;QACN,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,qBAAqB,EAAE;QACrB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,iBAAiB,EAAE;QACjB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAA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A8B,IAAI,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,MAAA,CAAC;QAElD,IAAI,CAAC,SAAS,CAAC,4BAA4B,CACzC,IAAI,EACJ,yBAAyB,CAC1B,CAAC;IACJ,CAAC;CAghCF;AA/nCD,4CA+nCC;+lDAhTG,aAAoD;IAEpD,6DAA6D;IAC7D,MAAM,YAAY,GAChB,aAAa,IAAI,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC;IAC5D,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IACjD,CAAC;IACD,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACzC,wCAAwC,EACxC,YAAY,CACb,CAAC;IACF,OAAO,eAAe,CAAC;AACzB,CAAC,qGAE0B,OAAY;IACrC,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACzC,gDAAgD,EAChD,OAAO,CACR,CAAC;IACF,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,wCAAwC,OAAO,EAAE,CAAC,CAAC;IACrE,CAAC;IACD,MAAM,aAAa,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACvC,wCAAwC,EACxC,eAAe,CAChB,CAAC;IACF,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type { StateMetadata } from '@metamask/base-controller';\nimport type { TraceCallback } from '@metamask/controller-utils';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { TransactionController } from '@metamask/transaction-controller';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\n\nimport type { BridgeClientId } from './constants/bridge';\nimport {\n BRIDGE_CONTROLLER_NAME,\n BRIDGE_PROD_API_BASE_URL,\n DEFAULT_BRIDGE_CONTROLLER_STATE,\n METABRIDGE_ETHEREUM_ADDRESS,\n REFRESH_INTERVAL_MS,\n} from './constants/bridge';\nimport { CHAIN_IDS } from './constants/chains';\nimport { SWAPS_CONTRACT_ADDRESSES } from './constants/swaps';\nimport { TraceName } from './constants/traces';\nimport {\n ExchangeRateSourcesForLookup,\n selectIsAssetExchangeRateInState,\n} from './selectors';\nimport { RequestStatus } from './types';\nimport type {\n L1GasFees,\n GenericQuoteRequest,\n NonEvmFees,\n QuoteRequest,\n QuoteResponse,\n BridgeControllerState,\n BridgeControllerMessenger,\n FetchFunction,\n} from './types';\nimport { getAssetIdsForToken, toExchangeRates } from './utils/assets';\nimport { hasSufficientBalance } from './utils/balance';\nimport {\n getDefaultBridgeControllerState,\n isCrossChain,\n isEthUsdt,\n isNonEvmChainId,\n isSolanaChainId,\n} from './utils/bridge';\nimport {\n formatAddressToCaipReference,\n formatChainIdToCaip,\n formatChainIdToHex,\n} from './utils/caip-formatters';\nimport {\n getBridgeFeatureFlags,\n hasMinimumRequiredVersion,\n} from './utils/feature-flags';\nimport {\n fetchAssetPrices,\n fetchBridgeQuotes,\n fetchBridgeQuoteStream,\n fetchBatchSellTrades,\n} from './utils/fetch';\nimport {\n AbortReason,\n MetaMetricsSwapsEventSource,\n MetricsActionType,\n UnifiedSwapBridgeEventName,\n} from './utils/metrics/constants';\nimport {\n formatProviderLabel,\n getAccountHardwareType,\n getRequestParams,\n getSwapTypeFromQuote,\n isCustomSlippage,\n toInputChangedPropertyKey,\n toInputChangedPropertyValue,\n} from './utils/metrics/properties';\nimport type {\n QuoteFetchData,\n RequestMetadata,\n RequiredEventContextFromClient,\n} from './utils/metrics/types';\nimport type { CrossChainSwapsEventProperties } from './utils/metrics/types';\nimport {\n isValidQuoteRequest,\n isValidBatchSellQuoteRequest,\n sortQuotes,\n} from './utils/quote';\nimport { appendFeesToQuotes } from './utils/quote-fees';\nimport { getMinimumBalanceForRentExemptionInLamports } from './utils/snaps';\nimport type { FeatureId } from './utils/validators';\n\nconst metadata: StateMetadata<BridgeControllerState> = {\n quoteRequest: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quotes: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quotesInitialLoadTime: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quotesLastFetched: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quotesLoadingStatus: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quoteFetchError: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quotesRefreshCount: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n assetExchangeRates: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n minimumBalanceForRentExemptionInLamports: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n tokenWarnings: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n tokenSecurityTypeDestination: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quoteStreamComplete: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n batchSellTrades: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n batchSellTradesLoadingStatus: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\n/**\n * The input to start polling for the {@link BridgeController}\n *\n * @param updatedQuoteRequest - The updated quote request\n * @param context - The context contains properties that can't be populated by the\n * controller and need to be provided by the client for analytics\n */\ntype BridgePollingInput = {\n quoteRequests: GenericQuoteRequest[];\n context: Pick<\n RequiredEventContextFromClient,\n UnifiedSwapBridgeEventName.QuotesError\n >[UnifiedSwapBridgeEventName.QuotesError] &\n Pick<\n RequiredEventContextFromClient,\n UnifiedSwapBridgeEventName.QuotesRequested\n >[UnifiedSwapBridgeEventName.QuotesRequested] &\n /**\n * Client-supplied security classification for the destination token\n * (e.g. from token security/scanning data). Stored on the controller\n * and merged into every analytics event that includes\n * `token_address_destination`. Pass `null` when no security data is\n * available for the selected destination token.\n */\n Pick<\n RequiredEventContextFromClient[UnifiedSwapBridgeEventName.InputSourceDestinationSwitched],\n 'token_security_type_destination'\n >;\n};\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'updateBridgeQuoteRequestParams',\n 'fetchQuotes',\n 'updateBatchSellTrades',\n 'stopPollingForQuotes',\n 'setLocation',\n 'resetState',\n 'setChainIntervalLength',\n 'trackUnifiedSwapBridgeEvent',\n] as const;\n\nexport class BridgeController extends StaticIntervalPollingController<BridgePollingInput>()<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState,\n BridgeControllerMessenger\n> {\n #abortController: AbortController | undefined;\n\n #batchSellTradesAbortController: AbortController | undefined;\n\n #quotesFirstFetched: number | undefined;\n\n /**\n * Stores the location/entry point from which the user initiated the swap or bridge flow.\n * Set via setLocation() before navigating to the swap/bridge flow.\n * Used as default for all subsequent internal events.\n */\n #location: MetaMetricsSwapsEventSource = MetaMetricsSwapsEventSource.MainView;\n\n readonly #clientId: BridgeClientId;\n\n readonly #clientVersion: string;\n\n readonly #getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n\n readonly #fetchFn: FetchFunction;\n\n readonly #trackMetaMetricsFn: <\n EventName extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: EventName,\n properties: CrossChainSwapsEventProperties<EventName>,\n ) => void;\n\n readonly #trace: TraceCallback;\n\n readonly #config: {\n customBridgeApiBaseUrl?: string;\n };\n\n /**\n * Returns whether to use AssetsController for exchange rates.\n * Set via constructor option getUseAssetsControllerForRates; defaults to false.\n *\n * @returns True when exchange rates should be read from AssetsController:getExchangeRatesForBridge.\n */\n readonly #getUseAssetsControllerForRates: () => boolean;\n\n constructor({\n messenger,\n state,\n clientId,\n clientVersion,\n getLayer1GasFee,\n fetchFn,\n config,\n trackMetaMetricsFn,\n traceFn,\n getUseAssetsControllerForRates,\n }: {\n messenger: BridgeControllerMessenger;\n state?: Partial<BridgeControllerState>;\n clientId: BridgeClientId;\n clientVersion: string;\n getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n fetchFn: FetchFunction;\n config?: {\n customBridgeApiBaseUrl?: string;\n };\n trackMetaMetricsFn: <\n EventName extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: EventName,\n properties: CrossChainSwapsEventProperties<EventName>,\n ) => void;\n traceFn?: TraceCallback;\n /**\n * When provided, called to determine whether to use AssetsController for exchange rates.\n * When true, rates are read from AssetsController:getExchangeRatesForBridge instead of\n * MultichainAssetsRatesController, TokenRatesController, and CurrencyRateController.\n */\n getUseAssetsControllerForRates?: () => boolean;\n }) {\n super({\n name: BRIDGE_CONTROLLER_NAME,\n metadata,\n messenger,\n state: {\n ...getDefaultBridgeControllerState(),\n ...state,\n },\n });\n\n this.setIntervalLength(REFRESH_INTERVAL_MS);\n\n this.#abortController = new AbortController();\n this.#getLayer1GasFee = getLayer1GasFee;\n this.#clientId = clientId;\n this.#clientVersion = clientVersion;\n this.#fetchFn = fetchFn;\n this.#trackMetaMetricsFn = trackMetaMetricsFn;\n this.#config = config ?? {};\n this.#trace = traceFn ?? (((_request, fn) => fn?.()) as TraceCallback);\n this.#getUseAssetsControllerForRates =\n getUseAssetsControllerForRates ?? (() => false);\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n _executePoll = async (pollingInput: BridgePollingInput) => {\n await this.#fetchBridgeQuotes(pollingInput);\n };\n\n /**\n * Updates the quote request at the specified index with the given parameters, then starts\n * polling for quotes.\n *\n * @param paramsToUpdate - The parameters to update in the quote request at the specified index\n * @param context - metrics context\n * @param quoteRequestIndex - The index of the quote request to update\n * @param quoteRequestCount - The number of quote requests in the UI\n */\n updateBridgeQuoteRequestParams = async (\n paramsToUpdate: Partial<GenericQuoteRequest> & {\n walletAddress: GenericQuoteRequest['walletAddress'];\n },\n context: BridgePollingInput['context'],\n quoteRequestIndex: number = 0,\n quoteRequestCount: number = 1,\n ) => {\n // Guard against updating a quote request that doesn't exist\n if (quoteRequestIndex >= quoteRequestCount) {\n return;\n }\n this.#trackInputChangedEvents(paramsToUpdate, quoteRequestIndex);\n this.resetState(AbortReason.QuoteRequestUpdated, quoteRequestIndex);\n this.update((state) => {\n // Update only the specified quote request and keep the rest of the quote requests unchanged\n state.quoteRequest = state.quoteRequest\n .slice(0, quoteRequestIndex)\n .concat({\n ...DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest[0],\n ...paramsToUpdate,\n })\n .concat(\n state.quoteRequest.slice(quoteRequestIndex + 1, quoteRequestCount),\n );\n state.tokenSecurityTypeDestination =\n context.token_security_type_destination ?? null;\n });\n\n // BatchSell and Unified swaps both use the same polling logic so both validations should pass\n if (\n isValidQuoteRequest(paramsToUpdate) &&\n isValidBatchSellQuoteRequest(this.state.quoteRequest)\n ) {\n this.#quotesFirstFetched = Date.now();\n // Update the insufficientBal and resetApproval params for the quote request\n const quoteWithInsufficientBalAndResetApproval =\n await this.#appendInsufficientBalAndResetApproval(paramsToUpdate);\n this.update((state) => {\n state.quoteRequest[quoteRequestIndex] =\n quoteWithInsufficientBalAndResetApproval;\n });\n\n // Set refresh rate based on the source chain before starting polling\n this.setChainIntervalLength();\n this.startPolling({\n quoteRequests: this.state.quoteRequest,\n context,\n });\n }\n };\n\n /**\n * Fetches quotes for specified request without updating the controller state\n * This method does not start polling for quotes and does not emit UnifiedSwapBridge events\n *\n * @param quoteRequest - The parameters for quote requests to fetch\n * @param abortSignal - The abort signal to cancel all the requests\n * @param featureId - The feature ID that maps to quoteParam overrides from LD\n * @returns A list of validated quotes\n */\n fetchQuotes = async (\n quoteRequest: GenericQuoteRequest,\n abortSignal: AbortSignal | null = null,\n featureId: FeatureId | null = null,\n ): Promise<(QuoteResponse & L1GasFees & NonEvmFees)[]> => {\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messenger);\n const jwt = await this.#getJwt();\n // If featureId is specified, retrieve the quoteRequestOverrides for that featureId\n const quoteRequestOverrides = featureId\n ? bridgeFeatureFlags.quoteRequestOverrides?.[featureId]\n : undefined;\n const resetApproval = await this.#shouldResetApproval(quoteRequest);\n\n // If quoteRequestOverrides is specified, merge it with the quoteRequest\n const { quotes: baseQuotes, validationFailures } = await fetchBridgeQuotes(\n quoteRequestOverrides\n ? { ...quoteRequest, ...quoteRequestOverrides, resetApproval }\n : { ...quoteRequest, resetApproval },\n abortSignal,\n this.#clientId,\n jwt,\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n featureId,\n this.#clientVersion,\n );\n\n this.#trackQuoteValidationFailures(validationFailures);\n\n const quotesWithFees = await appendFeesToQuotes(\n baseQuotes,\n this.messenger,\n this.#getLayer1GasFee,\n this.#getMultichainSelectedAccount(quoteRequest.walletAddress),\n );\n\n return sortQuotes(quotesWithFees, featureId);\n };\n\n /**\n * Fetches gasless transaction data and fees for BatchSell quotes.\n * To use this in the clients, add a listener for the recommendedQuotes and call\n * this handler whenever they change.\n *\n * @param quotes - The quotes to fetch the gasless transaction data and fees for\n * @param stxEnabled - Flag to estimate gas cost more precisely for the batch sell feature.\n */\n updateBatchSellTrades = async (\n quotes: (QuoteResponse | null)[],\n stxEnabled: boolean,\n ): Promise<void> => {\n this.#batchSellTradesAbortController?.abort(\n AbortReason.GaslessTxBatchFetched,\n );\n this.#batchSellTradesAbortController = new AbortController();\n\n this.update((state) => {\n // Set loading status again if recommended quotes are re-ordered\n state.batchSellTradesLoadingStatus = RequestStatus.LOADING;\n });\n\n try {\n const batchSellTradesResponse = await fetchBatchSellTrades(\n quotes,\n stxEnabled,\n this.#batchSellTradesAbortController.signal,\n this.#clientId,\n await this.#getJwt(),\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n this.#clientVersion,\n );\n\n this.update((state) => {\n state.batchSellTrades = batchSellTradesResponse;\n state.batchSellTradesLoadingStatus = RequestStatus.FETCHED;\n });\n\n // TODO if fee.asset.assetId is not in exchange rates, fetch the exchange rate and update the state\n } catch (error) {\n // Ignore abort errors\n if (\n (error as Error).toString().includes('AbortError') ||\n (error as Error).toString().includes('FetchRequestCanceledException') ||\n [\n AbortReason.ResetState,\n AbortReason.NewQuoteRequest,\n AbortReason.QuoteRequestUpdated,\n AbortReason.TransactionSubmitted,\n AbortReason.GaslessTxBatchFetched,\n ].includes(error as AbortReason)\n ) {\n // Exit the function early to prevent other state updates\n return;\n }\n\n this.update((state) => {\n // Reset the batch sell trades if the fetch fails to avoid showing stale data\n state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n // Update loading status\n state.batchSellTradesLoadingStatus = RequestStatus.ERROR;\n });\n console.log(`Failed to fetch batch sell trades`, error);\n }\n };\n\n readonly #trackQuoteValidationFailures = (validationFailures: string[]) => {\n if (validationFailures.length === 0) {\n return;\n }\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesValidationFailed,\n {\n failures: validationFailures,\n location: this.#location,\n },\n );\n };\n\n readonly #getExchangeRateSources = (): ExchangeRateSourcesForLookup => {\n if (this.#getUseAssetsControllerForRates()) {\n return {\n ...this.messenger.call('AssetsController:getExchangeRatesForBridge'),\n historicalPrices: {},\n ...this.state,\n };\n }\n return {\n ...this.messenger.call('MultichainAssetsRatesController:getState'),\n ...this.messenger.call('CurrencyRateController:getState'),\n ...this.messenger.call('TokenRatesController:getState'),\n ...this.state,\n };\n };\n\n /**\n * Fetches the exchange rates for the assets in the quote request if they are not already in the state\n * In addition to the selected tokens, this also fetches the native asset for the source and destination chains\n *\n * @param quoteRequests - The quote requests to fetch the exchange rates for\n */\n readonly #fetchAssetExchangeRates = async (\n quoteRequests: Partial<GenericQuoteRequest>[],\n ) => {\n const exchangeRateSources = this.#getExchangeRateSources();\n\n // Get unique assetIds for all quote requests\n const assetIds = new Set<CaipAssetType>(\n quoteRequests\n .flatMap((quoteRequest) =>\n [\n quoteRequest.srcTokenAddress && quoteRequest.srcChainId\n ? getAssetIdsForToken(\n quoteRequest.srcTokenAddress,\n quoteRequest.srcChainId,\n )\n : undefined,\n quoteRequest.destTokenAddress && quoteRequest.destChainId\n ? getAssetIdsForToken(\n quoteRequest.destTokenAddress,\n quoteRequest.destChainId,\n )\n : undefined,\n ].flat(),\n )\n .filter(\n (assetId: CaipAssetType | undefined): assetId is CaipAssetType =>\n !selectIsAssetExchangeRateInState(exchangeRateSources, assetId),\n ),\n );\n\n const currency = this.#getUseAssetsControllerForRates()\n ? this.messenger.call('AssetsController:getExchangeRatesForBridge')\n .currentCurrency\n : this.messenger.call('CurrencyRateController:getState').currentCurrency;\n\n if (assetIds.size === 0) {\n return;\n }\n\n const pricesByAssetId = await fetchAssetPrices({\n assetIds,\n currencies: new Set([currency]),\n clientId: this.#clientId,\n clientVersion: this.#clientVersion,\n fetchFn: this.#fetchFn,\n signal: this.#abortController?.signal,\n });\n const exchangeRates = toExchangeRates(currency, pricesByAssetId);\n this.update((state) => {\n state.assetExchangeRates = {\n ...state.assetExchangeRates,\n ...exchangeRates,\n };\n });\n };\n\n readonly #hasInsufficientBalance = async (\n quoteRequest: GenericQuoteRequest,\n ) => {\n try {\n const srcChainIdInHex = formatChainIdToHex(quoteRequest.srcChainId);\n const provider =\n this.#getNetworkClientByChainId(srcChainIdInHex)?.provider;\n const normalizedSrcTokenAddress = formatAddressToCaipReference(\n quoteRequest.srcTokenAddress,\n );\n\n return !(\n provider &&\n normalizedSrcTokenAddress &&\n quoteRequest.srcTokenAmount &&\n srcChainIdInHex &&\n (await hasSufficientBalance(\n provider,\n quoteRequest.walletAddress,\n normalizedSrcTokenAddress,\n quoteRequest.srcTokenAmount,\n srcChainIdInHex,\n ))\n );\n } catch (error) {\n console.warn('Failed to set insufficientBal', error);\n // Fall back to true so the backend returns quotes\n return true;\n }\n };\n\n readonly #appendInsufficientBalAndResetApproval = async (\n quoteRequest: GenericQuoteRequest,\n ) => {\n const isSrcChainNonEVM = isNonEvmChainId(quoteRequest.srcChainId);\n const providerConfig = isSrcChainNonEVM\n ? undefined\n : this.#getNetworkClientByChainId(\n formatChainIdToHex(quoteRequest.srcChainId),\n )?.configuration;\n\n let insufficientBal: boolean | undefined;\n let resetApproval: boolean = Boolean(quoteRequest.resetApproval);\n if (isSrcChainNonEVM) {\n // If the source chain is not an EVM network, use value from params\n insufficientBal = quoteRequest.insufficientBal;\n } else if (providerConfig?.rpcUrl?.includes('tenderly')) {\n // If the rpcUrl is a tenderly fork (e2e tests), set insufficientBal=true\n // The bridge-api filters out quotes if the balance on mainnet is insufficient so this override allows quotes to always be returned\n insufficientBal = true;\n } else {\n // Set loading status if RPC calls are made before the quotes are fetched\n this.update((state) => {\n state.quotesLoadingStatus = RequestStatus.LOADING;\n });\n resetApproval = await this.#shouldResetApproval(quoteRequest);\n // Otherwise query the src token balance from the RPC provider\n insufficientBal =\n quoteRequest.insufficientBal ??\n (await this.#hasInsufficientBalance(quoteRequest));\n }\n\n return {\n ...quoteRequest,\n insufficientBal,\n resetApproval,\n };\n };\n\n readonly #shouldResetApproval = async (quoteRequest: GenericQuoteRequest) => {\n if (isNonEvmChainId(quoteRequest.srcChainId)) {\n return false;\n }\n try {\n const normalizedSrcTokenAddress = formatAddressToCaipReference(\n quoteRequest.srcTokenAddress,\n );\n if (isEthUsdt(quoteRequest.srcChainId, normalizedSrcTokenAddress)) {\n const allowance = BigNumber.from(\n await this.#getUSDTMainnetAllowance(\n quoteRequest.walletAddress,\n normalizedSrcTokenAddress,\n quoteRequest.destChainId,\n ),\n );\n return allowance.lt(quoteRequest.srcTokenAmount) && allowance.gt(0);\n }\n return false;\n } catch (error) {\n console.warn('Failed to set resetApproval', error);\n // Fall back to true so the backend returns quotes\n return true;\n }\n };\n\n stopPollingForQuotes = (\n reason?: AbortReason,\n context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived],\n ) => {\n this.stopAllPolling();\n // If polling is stopped before quotes finish loading, track QuotesReceived\n if (this.state.quotesLoadingStatus === RequestStatus.LOADING && context) {\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesReceived,\n context,\n );\n }\n // Clears quotes list in state\n this.#abortController?.abort(reason);\n this.#batchSellTradesAbortController?.abort(reason);\n };\n\n /**\n * Sets the location/entry point for the current swap or bridge flow.\n * Call this when the user enters the flow so that all internally-fired\n * events (InputChanged, QuotesRequested, etc.) carry the correct location.\n *\n * @param location - The entry point from which the user initiated the flow\n */\n setLocation = (location: MetaMetricsSwapsEventSource) => {\n this.#location = location;\n };\n\n resetState = (\n reason = AbortReason.ResetState,\n quoteRequestIndex: number | null = null,\n ) => {\n this.stopPollingForQuotes(reason);\n this.update((state) => {\n // Cannot do direct assignment to state, i.e. state = {... }, need to manually assign each field\n if (quoteRequestIndex === null) {\n // Clear all requests if index is null\n state.quoteRequest = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest;\n } else {\n // Otherwise only clear the specified request\n state.quoteRequest = state.quoteRequest\n .slice(0, quoteRequestIndex)\n .concat(DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest[0])\n .concat(state.quoteRequest.slice(quoteRequestIndex + 1));\n }\n state.quotesInitialLoadTime =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesInitialLoadTime;\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n state.quotesLastFetched =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesLastFetched;\n state.quotesLoadingStatus =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesLoadingStatus;\n state.quoteFetchError = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteFetchError;\n state.quotesRefreshCount =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesRefreshCount;\n state.assetExchangeRates =\n DEFAULT_BRIDGE_CONTROLLER_STATE.assetExchangeRates;\n state.minimumBalanceForRentExemptionInLamports =\n DEFAULT_BRIDGE_CONTROLLER_STATE.minimumBalanceForRentExemptionInLamports;\n state.tokenWarnings = DEFAULT_BRIDGE_CONTROLLER_STATE.tokenWarnings;\n state.tokenSecurityTypeDestination =\n DEFAULT_BRIDGE_CONTROLLER_STATE.tokenSecurityTypeDestination;\n state.quoteStreamComplete =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quoteStreamComplete;\n state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n state.batchSellTradesLoadingStatus =\n DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTradesLoadingStatus;\n });\n };\n\n /**\n * Sets the interval length based on the source chain\n */\n setChainIntervalLength = () => {\n const { state } = this;\n // Assume that BatchSell quote requests all have the same source chain\n // Use the first one to determine refresh rate\n const { srcChainId } = state.quoteRequest[0];\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messenger);\n\n const refreshRateOverride = srcChainId\n ? bridgeFeatureFlags.chains[formatChainIdToCaip(srcChainId)]?.refreshRate\n : undefined;\n const defaultRefreshRate = bridgeFeatureFlags.refreshRate;\n this.setIntervalLength(refreshRateOverride ?? defaultRefreshRate);\n };\n\n readonly #fetchBridgeQuotes = async ({\n quoteRequests,\n context,\n }: BridgePollingInput) => {\n this.#abortController?.abort(AbortReason.NewQuoteRequest);\n this.#batchSellTradesAbortController?.abort(AbortReason.NewQuoteRequest);\n\n this.#abortController = new AbortController();\n\n this.#fetchAssetExchangeRates(quoteRequests).catch((error) =>\n console.warn('Failed to fetch asset exchange rates', error),\n );\n\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesRequested,\n context,\n );\n\n const { sse, maxRefreshCount } = getBridgeFeatureFlags(this.messenger);\n const shouldStream =\n sse?.enabled &&\n hasMinimumRequiredVersion(this.#clientVersion, sse.minimumVersion);\n const isBatchSellRequest = quoteRequests.length > 1;\n\n this.update((state) => {\n state.quoteFetchError = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteFetchError;\n state.tokenWarnings = DEFAULT_BRIDGE_CONTROLLER_STATE.tokenWarnings;\n state.quoteStreamComplete =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quoteStreamComplete;\n state.quotesLastFetched = Date.now();\n state.quotesLoadingStatus = RequestStatus.LOADING;\n // Prevent clients from displaying stale batch sell fees\n if (quoteRequests.length > 1) {\n state.batchSellTradesLoadingStatus = RequestStatus.LOADING;\n state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n }\n });\n\n const jwt = await this.#getJwt();\n\n try {\n const [firstQuoteRequest] = quoteRequests;\n\n const unifiedSwapTraceName = isCrossChain(\n firstQuoteRequest.srcChainId,\n firstQuoteRequest.destChainId,\n )\n ? TraceName.BridgeQuotesFetched\n : TraceName.SwapQuotesFetched;\n\n await this.#trace(\n {\n name: isBatchSellRequest\n ? TraceName.BatchSellQuotesFetched\n : unifiedSwapTraceName,\n data: {\n srcChainId: formatChainIdToCaip(firstQuoteRequest.srcChainId),\n destChainId: formatChainIdToCaip(firstQuoteRequest.destChainId),\n },\n },\n async () => {\n const selectedAccount = this.#getMultichainSelectedAccount(\n firstQuoteRequest.walletAddress,\n );\n // This call is not awaited to prevent blocking quote fetching if the snap takes too long to respond\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#setMinimumBalanceForRentExemptionInLamports(\n firstQuoteRequest.srcChainId,\n selectedAccount?.metadata?.snap?.id,\n );\n // Use SSE if enabled and return early\n if (shouldStream || isBatchSellRequest) {\n await this.#handleQuoteStreaming(\n quoteRequests,\n jwt,\n selectedAccount,\n );\n return;\n }\n // Otherwise use regular fetch\n const quotes = await this.fetchQuotes(\n firstQuoteRequest,\n this.#abortController?.signal,\n );\n this.update((state) => {\n // Set the initial load time if this is the first fetch\n if (\n state.quotesRefreshCount ===\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesRefreshCount &&\n this.#quotesFirstFetched\n ) {\n state.quotesInitialLoadTime =\n Date.now() - this.#quotesFirstFetched;\n }\n state.quotes = quotes;\n state.quotesLoadingStatus = RequestStatus.FETCHED;\n });\n },\n );\n } catch (error) {\n // Reset the quotes list if the fetch fails to avoid showing stale quotes\n this.update((state) => {\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n });\n // Ignore abort errors\n if (\n (error as Error).toString().includes('AbortError') ||\n (error as Error).toString().includes('FetchRequestCanceledException') ||\n [\n AbortReason.ResetState,\n AbortReason.NewQuoteRequest,\n AbortReason.QuoteRequestUpdated,\n AbortReason.TransactionSubmitted,\n ].includes(error as AbortReason)\n ) {\n // Exit the function early to prevent other state updates\n return;\n }\n\n // Update loading status and error message\n this.update((state) => {\n // The error object reference is not guaranteed to exist on mobile so reading\n // the message directly could cause an error.\n let errorMessage;\n try {\n errorMessage =\n (error as Error)?.message ?? (error as Error).toString();\n } catch {\n // Intentionally empty\n } finally {\n state.quoteFetchError = errorMessage ?? 'Unknown error';\n }\n state.quotesLoadingStatus = RequestStatus.ERROR;\n });\n // Track event and log error\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesError,\n context,\n );\n console.log(\n `Failed to ${shouldStream ? 'stream' : 'fetch'} bridge quotes`,\n error,\n );\n }\n\n // Update refresh count after fetching, validation and fee calculation have completed\n this.update((state) => {\n state.quotesRefreshCount += 1;\n });\n const hasNoFundedQuoteRequests = quoteRequests.every(\n ({ insufficientBal }) => Boolean(insufficientBal),\n );\n\n if (\n hasNoFundedQuoteRequests\n ? // If all quote requests are insufficiently funded, stop polling\n // So if a BatchSell has at least 1 sufficiently funded quote request, polling continues\n true\n : // Otherwise continue polling until the maximum number of refreshes has been reached\n this.state.quotesRefreshCount >= maxRefreshCount\n ) {\n this.stopAllPolling();\n }\n };\n\n readonly #handleQuoteStreaming = async (\n quoteRequests: GenericQuoteRequest[],\n jwt?: string,\n selectedAccount?: InternalAccount,\n ) => {\n /**\n * Tracks the number of valid quotes received from the current stream, which is used\n * to determine when to clear the quotes list and set the initial load time\n */\n let validQuotesCounter = 0;\n /**\n * Tracks all pending promises from appendFeesToQuotes calls to ensure they complete\n * before setting quotesLoadingStatus to FETCHED\n */\n const pendingFeeAppendPromises = new Set<Promise<void>>();\n\n await fetchBridgeQuoteStream(\n this.#fetchFn,\n quoteRequests,\n this.#abortController?.signal,\n this.#clientId,\n jwt,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n {\n onQuoteValidationFailure: this.#trackQuoteValidationFailures,\n onValidQuoteReceived: async (quote: QuoteResponse) => {\n const feeAppendPromise = (async () => {\n const quotesWithFees = await appendFeesToQuotes(\n [quote],\n this.messenger,\n this.#getLayer1GasFee,\n selectedAccount,\n );\n if (quotesWithFees.length > 0) {\n validQuotesCounter += 1;\n }\n this.update((state) => {\n // Clear previous quotes and quotes load time when first quote in the current\n // polling loop is received\n // This enables clients to continue showing the previous quotes while new\n // quotes are loading\n // Note: If there are no valid quotes until the 2nd fetch, quotesInitialLoadTime will be > refreshRate\n if (validQuotesCounter === 1) {\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n if (!state.quotesInitialLoadTime && this.#quotesFirstFetched) {\n // Set the initial load time after the first quote is received\n state.quotesInitialLoadTime =\n Date.now() - this.#quotesFirstFetched;\n }\n }\n state.quotes = [...state.quotes, ...quotesWithFees];\n });\n })();\n pendingFeeAppendPromises.add(feeAppendPromise);\n feeAppendPromise\n .catch((error) => {\n // Catch errors to prevent them from breaking stream processing\n // If appendFeesToQuotes throws, the state update never happens, so no invalid entry is added\n console.error('Error appending fees to quote', error);\n })\n .finally(() => {\n pendingFeeAppendPromises.delete(feeAppendPromise);\n });\n // Await the promise to ensure errors are caught and handled before continuing\n // The promise is also tracked in pendingFeeAppendPromises for onClose to wait for\n await feeAppendPromise;\n },\n onTokenWarning: (warning) => {\n this.update((state) => {\n const isDuplicate = state.tokenWarnings.some(\n (existing) => existing.feature_id === warning.feature_id,\n );\n if (!isDuplicate) {\n state.tokenWarnings = [...state.tokenWarnings, warning];\n }\n });\n },\n onComplete: (data) => {\n this.update((state) => {\n state.quoteStreamComplete = data;\n });\n },\n onClose: async () => {\n // Wait for all pending appendFeesToQuotes operations to complete\n // before setting quotesLoadingStatus to FETCHED\n await Promise.allSettled(Array.from(pendingFeeAppendPromises));\n this.update((state) => {\n // If there are no valid quotes in the current stream, clear the quotes list\n // to remove quotes from the previous stream\n if (validQuotesCounter === 0) {\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n }\n state.quotesLoadingStatus = RequestStatus.FETCHED;\n });\n },\n },\n this.#clientVersion,\n );\n };\n\n readonly #setMinimumBalanceForRentExemptionInLamports = async (\n srcChainId: GenericQuoteRequest['srcChainId'],\n snapId?: string,\n ) => {\n if (!isSolanaChainId(srcChainId) || !snapId) {\n return;\n }\n const minimumBalanceForRentExemptionInLamports =\n await getMinimumBalanceForRentExemptionInLamports(snapId, this.messenger);\n this.update((state) => {\n state.minimumBalanceForRentExemptionInLamports =\n minimumBalanceForRentExemptionInLamports;\n });\n };\n\n #getMultichainSelectedAccount(\n walletAddress?: GenericQuoteRequest['walletAddress'],\n ) {\n // Assume that all quotes in a batch are for the same account\n const addressToUse =\n walletAddress ?? this.state.quoteRequest[0].walletAddress;\n if (!addressToUse) {\n throw new Error('Account address is required');\n }\n const selectedAccount = this.messenger.call(\n 'AccountsController:getAccountByAddress',\n addressToUse,\n );\n return selectedAccount;\n }\n\n #getNetworkClientByChainId(chainId: Hex) {\n const networkClientId = this.messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n chainId,\n );\n if (!networkClientId) {\n throw new Error(`No network client found for chainId: ${chainId}`);\n }\n const networkClient = this.messenger.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n return networkClient;\n }\n\n readonly #getJwt = async (): Promise<string | undefined> => {\n try {\n const token = await this.messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n return token;\n } catch (error) {\n console.error('Error getting JWT token for bridge-api request', error);\n return undefined;\n }\n };\n\n readonly #getRequestMetadata = (\n quoteRequestIndex: number = 0,\n ): Omit<\n RequestMetadata,\n 'stx_enabled' | 'usd_amount_source' | 'security_warnings'\n > => {\n const quoteRequest = this.state.quoteRequest[quoteRequestIndex];\n const { walletAddress } = quoteRequest;\n const accountHardwareType = getAccountHardwareType(\n walletAddress\n ? this.#getMultichainSelectedAccount(walletAddress)\n : undefined,\n );\n\n return {\n slippage_limit: quoteRequest.slippage,\n swap_type: getSwapTypeFromQuote(quoteRequest),\n custom_slippage: isCustomSlippage(quoteRequest.slippage),\n account_hardware_type: accountHardwareType,\n is_hardware_wallet: accountHardwareType !== null,\n };\n };\n\n readonly #getQuoteFetchData = (): Omit<\n QuoteFetchData,\n 'best_quote_provider' | 'price_impact' | 'can_submit'\n > => {\n return {\n quotes_count: this.state.quotes.length,\n quotes_list: this.state.quotes.map(({ quote }) =>\n formatProviderLabel(quote),\n ),\n initial_load_time_all_quotes: this.state.quotesInitialLoadTime ?? 0,\n has_gas_included_quote: this.state.quotes.some(\n ({ quote }) => quote.gasIncluded,\n ),\n };\n };\n\n readonly #getEventProperties = <\n EventName extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: EventName,\n propertiesFromClient: Pick<\n RequiredEventContextFromClient,\n EventName\n >[EventName],\n quoteRequestIndex: number = 0,\n ): CrossChainSwapsEventProperties<EventName> => {\n const clientProps = propertiesFromClient as Record<string, unknown>;\n const baseProperties = {\n ...propertiesFromClient,\n location: clientProps?.location ?? this.#location,\n action_type: MetricsActionType.SWAPBRIDGE_V1,\n };\n const quoteRequest = this.state.quoteRequest[quoteRequestIndex];\n switch (eventName) {\n case UnifiedSwapBridgeEventName.ButtonClicked:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.PageViewed:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesValidationFailed:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n refresh_count: this.state.quotesRefreshCount,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesReceived:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n refresh_count: this.state.quotesRefreshCount,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesRequested:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n has_sufficient_funds: !quoteRequest.insufficientBal,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesError:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n error_message: this.state.quoteFetchError,\n has_sufficient_funds: !quoteRequest.insufficientBal,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.AllQuotesOpened:\n case UnifiedSwapBridgeEventName.AllQuotesSorted:\n case UnifiedSwapBridgeEventName.QuoteSelected:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.Failed: {\n // Populate the properties that the error occurred before the tx was submitted\n return {\n ...baseProperties,\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n ...propertiesFromClient,\n };\n }\n case UnifiedSwapBridgeEventName.AssetDetailTooltipClicked:\n case UnifiedSwapBridgeEventName.AssetPickerOpened:\n return baseProperties;\n // Inject `token_security_type_destination` from controller state so the\n // field is always present on this event. `baseProperties` (which spreads\n // `propertiesFromClient`) wins if the client supplies a value explicitly.\n case UnifiedSwapBridgeEventName.InputSourceDestinationSwitched:\n return {\n token_security_type_destination:\n this.state.tokenSecurityTypeDestination,\n ...baseProperties,\n };\n // These events may be published after the bridge-controller state is reset\n // So the BridgeStatusController populates all the properties\n case UnifiedSwapBridgeEventName.Submitted:\n case UnifiedSwapBridgeEventName.Completed:\n return propertiesFromClient;\n case UnifiedSwapBridgeEventName.InputChanged:\n default:\n return baseProperties;\n }\n };\n\n readonly #trackInputChangedEvents = (\n paramsToUpdate: Partial<GenericQuoteRequest>,\n quoteRequestIndex: number = 0,\n ) => {\n Object.entries(paramsToUpdate).forEach(([key, value]) => {\n const inputKey = toInputChangedPropertyKey[key as keyof QuoteRequest];\n const inputValue =\n toInputChangedPropertyValue[key as keyof QuoteRequest]?.(\n paramsToUpdate,\n );\n if (\n inputKey &&\n inputValue !== undefined &&\n this.state.quoteRequest[quoteRequestIndex] &&\n value !==\n this.state.quoteRequest[quoteRequestIndex][\n key as keyof GenericQuoteRequest\n ]\n ) {\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.InputChanged,\n {\n input: inputKey,\n input_value: inputValue,\n location: this.#location,\n },\n );\n }\n });\n };\n\n /**\n * This method tracks cross-chain swaps events\n *\n * @param eventName - The name of the event to track\n * @param propertiesFromClient - Properties that can't be calculated from the event name and need to be provided by the client\n * @param quoteRequestIndex - The index of the quote request to track the event for\n * @example\n * this.trackUnifiedSwapBridgeEvent(UnifiedSwapBridgeEventName.ActionOpened, {\n * location: MetaMetricsSwapsEventSource.MainView,\n * });\n */\n trackUnifiedSwapBridgeEvent = <\n EventName extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: EventName,\n propertiesFromClient: Pick<\n RequiredEventContextFromClient,\n EventName\n >[EventName],\n quoteRequestIndex: number = 0,\n ) => {\n try {\n const combinedPropertiesForEvent = this.#getEventProperties<EventName>(\n eventName,\n propertiesFromClient,\n quoteRequestIndex,\n );\n\n this.#trackMetaMetricsFn(eventName, combinedPropertiesForEvent);\n } catch (error) {\n console.error(\n `Error tracking cross-chain swaps MetaMetrics event ${eventName}`,\n error,\n );\n }\n };\n\n /**\n *\n * @param walletAddress - The address of the account to get the allowance for\n * @param contractAddress - The address of the ERC20 token contract on mainnet\n * @param destinationChainId - The chain ID of the destination network\n * @returns The atomic allowance of the ERC20 token contract\n */\n readonly #getUSDTMainnetAllowance = async (\n walletAddress: string,\n contractAddress: string,\n destinationChainId: GenericQuoteRequest['destChainId'],\n ): Promise<string> => {\n const networkClient = this.#getNetworkClientByChainId(CHAIN_IDS.MAINNET);\n const provider = networkClient?.provider;\n if (!provider) {\n throw new Error('No provider found');\n }\n\n const ethersProvider = new Web3Provider(provider);\n const contract = new Contract(contractAddress, abiERC20, ethersProvider);\n const spenderAddress = isCrossChain(CHAIN_IDS.MAINNET, destinationChainId)\n ? METABRIDGE_ETHEREUM_ADDRESS\n : SWAPS_CONTRACT_ADDRESSES[CHAIN_IDS.MAINNET];\n const allowance: BigNumber = await contract.allowance(\n walletAddress,\n spenderAddress,\n );\n return allowance.toString();\n };\n}\n"]}
1
+ {"version":3,"file":"bridge-controller.cjs","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qEAAqE;AACrE,wDAAqD;AACrD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AAC,YAAY,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IACjD,CAAC;IACD,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACzC,wCAAwC,EACxC,YAAY,CACb,CAAC;IACF,OAAO,eAAe,CAAC;AACzB,CAAC,qGAE0B,OAAY;IACrC,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACzC,gDAAgD,EAChD,OAAO,CACR,CAAC;IACF,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,wCAAwC,OAAO,EAAE,CAAC,CAAC;IACrE,CAAC;IACD,MAAM,aAAa,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACvC,wCAAwC,EACxC,eAAe,CAChB,CAAC;IACF,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type { StateMetadata } from '@metamask/base-controller';\nimport type { TraceCallback } from '@metamask/controller-utils';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { TransactionController } from '@metamask/transaction-controller';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\n\nimport type { BridgeClientId } from './constants/bridge';\nimport {\n BRIDGE_CONTROLLER_NAME,\n BRIDGE_PROD_API_BASE_URL,\n DEFAULT_BRIDGE_CONTROLLER_STATE,\n METABRIDGE_ETHEREUM_ADDRESS,\n REFRESH_INTERVAL_MS,\n} from './constants/bridge';\nimport { CHAIN_IDS } from './constants/chains';\nimport { SWAPS_CONTRACT_ADDRESSES } from './constants/swaps';\nimport { TraceName } from './constants/traces';\nimport {\n ExchangeRateSourcesForLookup,\n selectIsAssetExchangeRateInState,\n} from './selectors';\nimport { FeatureId, RequestStatus } from './types';\nimport type {\n L1GasFees,\n GenericQuoteRequest,\n NonEvmFees,\n QuoteRequest,\n QuoteResponse,\n BridgeControllerState,\n BridgeControllerMessenger,\n FetchFunction,\n} from './types';\nimport { getAssetIdsForToken, toExchangeRates } from './utils/assets';\nimport { hasSufficientBalance } from './utils/balance';\nimport {\n getDefaultBridgeControllerState,\n isCrossChain,\n isEthUsdt,\n isNonEvmChainId,\n isSolanaChainId,\n} from './utils/bridge';\nimport {\n formatAddressToCaipReference,\n formatChainIdToCaip,\n formatChainIdToHex,\n} from './utils/caip-formatters';\nimport {\n getBridgeFeatureFlags,\n hasMinimumRequiredVersion,\n} from './utils/feature-flags';\nimport {\n fetchAssetPrices,\n fetchBridgeQuotes,\n fetchBridgeQuoteStream,\n fetchBatchSellTrades,\n} from './utils/fetch';\nimport {\n AbortReason,\n MetaMetricsSwapsEventSource,\n MetricsActionType,\n UnifiedSwapBridgeEventName,\n} from './utils/metrics/constants';\nimport {\n formatProviderLabel,\n getAccountHardwareType,\n getRequestParams,\n getSwapTypeFromQuote,\n isCustomSlippage,\n toInputChangedPropertyKey,\n toInputChangedPropertyValue,\n} from './utils/metrics/properties';\nimport type {\n QuoteFetchData,\n RequestMetadata,\n RequiredEventContextFromClient,\n} from './utils/metrics/types';\nimport type { CrossChainSwapsEventProperties } from './utils/metrics/types';\nimport {\n isValidQuoteRequest,\n isValidBatchSellQuoteRequest,\n sortQuotes,\n} from './utils/quote';\nimport { appendFeesToQuotes } from './utils/quote-fees';\nimport { getMinimumBalanceForRentExemptionInLamports } from './utils/snaps';\n\nconst metadata: StateMetadata<BridgeControllerState> = {\n quoteRequest: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quotes: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quotesInitialLoadTime: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quotesLastFetched: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quotesLoadingStatus: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quoteFetchError: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quotesRefreshCount: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n assetExchangeRates: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n minimumBalanceForRentExemptionInLamports: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n tokenWarnings: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n tokenSecurityTypeDestination: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n quoteStreamComplete: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n batchSellTrades: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n batchSellTradesLoadingStatus: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\n/**\n * The input to start polling for the {@link BridgeController}\n *\n * @param updatedQuoteRequest - The updated quote request\n * @param context - The context contains properties that can't be populated by the\n * controller and need to be provided by the client for analytics\n */\ntype BridgePollingInput = {\n quoteRequests: GenericQuoteRequest[];\n context: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesError] &\n RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesRequested];\n};\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'updateBridgeQuoteRequestParams',\n 'fetchQuotes',\n 'updateBatchSellTrades',\n 'stopPollingForQuotes',\n 'setLocation',\n 'resetState',\n 'setChainIntervalLength',\n 'trackUnifiedSwapBridgeEvent',\n] as const;\n\nexport class BridgeController extends StaticIntervalPollingController<BridgePollingInput>()<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState,\n BridgeControllerMessenger\n> {\n #abortController: AbortController | undefined;\n\n #batchSellTradesAbortController: AbortController | undefined;\n\n #quotesFirstFetched: number | undefined;\n\n /**\n * Stores the location/entry point from which the user initiated the swap or bridge flow.\n * Set via setLocation() before navigating to the swap/bridge flow.\n * Used as default for all subsequent internal events.\n */\n #location: MetaMetricsSwapsEventSource = MetaMetricsSwapsEventSource.MainView;\n\n readonly #clientId: BridgeClientId;\n\n readonly #clientVersion: string;\n\n readonly #getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n\n readonly #fetchFn: FetchFunction;\n\n readonly #trackMetaMetricsFn: <\n EventName extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: EventName,\n properties: CrossChainSwapsEventProperties<EventName>,\n ) => void;\n\n readonly #trace: TraceCallback;\n\n readonly #config: {\n customBridgeApiBaseUrl?: string;\n };\n\n /**\n * Returns whether to use AssetsController for exchange rates.\n * Set via constructor option getUseAssetsControllerForRates; defaults to false.\n *\n * @returns True when exchange rates should be read from AssetsController:getExchangeRatesForBridge.\n */\n readonly #getUseAssetsControllerForRates: () => boolean;\n\n constructor({\n messenger,\n state,\n clientId,\n clientVersion,\n getLayer1GasFee,\n fetchFn,\n config,\n trackMetaMetricsFn,\n traceFn,\n getUseAssetsControllerForRates,\n }: {\n messenger: BridgeControllerMessenger;\n state?: Partial<BridgeControllerState>;\n clientId: BridgeClientId;\n clientVersion: string;\n getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n fetchFn: FetchFunction;\n config?: {\n customBridgeApiBaseUrl?: string;\n };\n trackMetaMetricsFn: <\n EventName extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: EventName,\n properties: CrossChainSwapsEventProperties<EventName>,\n ) => void;\n traceFn?: TraceCallback;\n /**\n * When provided, called to determine whether to use AssetsController for exchange rates.\n * When true, rates are read from AssetsController:getExchangeRatesForBridge instead of\n * MultichainAssetsRatesController, TokenRatesController, and CurrencyRateController.\n */\n getUseAssetsControllerForRates?: () => boolean;\n }) {\n super({\n name: BRIDGE_CONTROLLER_NAME,\n metadata,\n messenger,\n state: {\n ...getDefaultBridgeControllerState(),\n ...state,\n },\n });\n\n this.setIntervalLength(REFRESH_INTERVAL_MS);\n\n this.#abortController = new AbortController();\n this.#getLayer1GasFee = getLayer1GasFee;\n this.#clientId = clientId;\n this.#clientVersion = clientVersion;\n this.#fetchFn = fetchFn;\n this.#trackMetaMetricsFn = trackMetaMetricsFn;\n this.#config = config ?? {};\n this.#trace = traceFn ?? (((_request, fn) => fn?.()) as TraceCallback);\n this.#getUseAssetsControllerForRates =\n getUseAssetsControllerForRates ?? (() => false);\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n _executePoll = async (pollingInput: BridgePollingInput) => {\n await this.#fetchBridgeQuotes(pollingInput);\n };\n\n /**\n * Updates the quote request at the specified index with the given parameters, then starts\n * polling for quotes.\n *\n * @param paramsToUpdate - The parameters to update in the quote request at the specified index\n * @param context - metrics context\n * @param quoteRequestIndex - The index of the quote request to update\n * @param quoteRequestCount - The number of quote requests in the UI\n */\n updateBridgeQuoteRequestParams = async (\n paramsToUpdate: Partial<GenericQuoteRequest> & {\n walletAddress: GenericQuoteRequest['walletAddress'];\n },\n context: BridgePollingInput['context'],\n quoteRequestIndex: number = 0,\n quoteRequestCount: number = 1,\n ) => {\n // Guard against updating a quote request that doesn't exist\n if (quoteRequestIndex >= quoteRequestCount) {\n return;\n }\n this.#trackInputChangedEvents(\n paramsToUpdate,\n context.feature_id,\n quoteRequestIndex,\n );\n this.resetState(AbortReason.QuoteRequestUpdated, quoteRequestIndex);\n this.update((state) => {\n // Update only the specified quote request and keep the rest of the quote requests unchanged\n state.quoteRequest = state.quoteRequest\n .slice(0, quoteRequestIndex)\n .concat({\n ...DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest[0],\n ...paramsToUpdate,\n })\n .concat(\n state.quoteRequest.slice(quoteRequestIndex + 1, quoteRequestCount),\n );\n state.tokenSecurityTypeDestination =\n context.token_security_type_destination ?? null;\n });\n\n // BatchSell and Unified swaps both use the same polling logic so both validations should pass\n if (\n isValidQuoteRequest(paramsToUpdate) &&\n isValidBatchSellQuoteRequest(this.state.quoteRequest)\n ) {\n this.#quotesFirstFetched = Date.now();\n // Update the insufficientBal and resetApproval params for the quote request\n const quoteWithInsufficientBalAndResetApproval =\n await this.#appendInsufficientBalAndResetApproval(paramsToUpdate);\n this.update((state) => {\n state.quoteRequest[quoteRequestIndex] =\n quoteWithInsufficientBalAndResetApproval;\n });\n\n // Set refresh rate based on the source chain before starting polling\n this.setChainIntervalLength();\n this.startPolling({\n quoteRequests: this.state.quoteRequest,\n context,\n });\n }\n };\n\n /**\n * Fetches quotes for specified request without updating the controller state\n * This method does not start polling for quotes and does not emit UnifiedSwapBridge events\n *\n * @param quoteRequest - The parameters for quote requests to fetch\n * @param featureId - The feature ID that maps to quoteParam overrides from LD\n * @param abortSignal - The abort signal to cancel all the requests\n * @returns A list of validated quotes\n */\n fetchQuotes = async (\n quoteRequest: GenericQuoteRequest,\n featureId: FeatureId,\n abortSignal: AbortSignal | null = null,\n ): Promise<(QuoteResponse & L1GasFees & NonEvmFees)[]> => {\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messenger);\n const jwt = await this.#getJwt();\n // If featureId is specified, retrieve the quoteRequestOverrides for that featureId\n const quoteRequestOverrides = featureId\n ? bridgeFeatureFlags.quoteRequestOverrides?.[featureId]\n : undefined;\n const resetApproval = await this.#shouldResetApproval(quoteRequest);\n\n // If quoteRequestOverrides is specified, merge it with the quoteRequest\n const { quotes: baseQuotes, validationFailures } = await fetchBridgeQuotes(\n quoteRequestOverrides\n ? { ...quoteRequest, ...quoteRequestOverrides, resetApproval }\n : { ...quoteRequest, resetApproval },\n abortSignal,\n this.#clientId,\n jwt,\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n featureId,\n this.#clientVersion,\n );\n\n this.#trackQuoteValidationFailures(validationFailures, featureId);\n\n const quotesWithFees = await appendFeesToQuotes(\n baseQuotes,\n this.messenger,\n this.#getLayer1GasFee,\n this.#getMultichainSelectedAccount(quoteRequest.walletAddress),\n );\n\n return sortQuotes(quotesWithFees, featureId);\n };\n\n /**\n * Fetches gasless transaction data and fees for BatchSell quotes.\n * To use this in the clients, add a listener for the recommendedQuotes and call\n * this handler whenever they change.\n *\n * @param quotes - The quotes to fetch the gasless transaction data and fees for\n * @param stxEnabled - Flag to estimate gas cost more precisely for the batch sell feature.\n */\n updateBatchSellTrades = async (\n quotes: (QuoteResponse | null)[],\n stxEnabled: boolean,\n ): Promise<void> => {\n this.#batchSellTradesAbortController?.abort(\n AbortReason.GaslessTxBatchFetched,\n );\n this.#batchSellTradesAbortController = new AbortController();\n\n this.update((state) => {\n // Set loading status again if recommended quotes are re-ordered\n state.batchSellTradesLoadingStatus = RequestStatus.LOADING;\n });\n\n try {\n const batchSellTradesResponse = await fetchBatchSellTrades(\n quotes,\n stxEnabled,\n this.#batchSellTradesAbortController.signal,\n this.#clientId,\n await this.#getJwt(),\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n this.#clientVersion,\n );\n\n this.update((state) => {\n state.batchSellTrades = batchSellTradesResponse;\n state.batchSellTradesLoadingStatus = RequestStatus.FETCHED;\n });\n\n // TODO if fee.asset.assetId is not in exchange rates, fetch the exchange rate and update the state\n } catch (error) {\n // Ignore abort errors\n if (\n (error as Error).toString().includes('AbortError') ||\n (error as Error).toString().includes('FetchRequestCanceledException') ||\n [\n AbortReason.ResetState,\n AbortReason.NewQuoteRequest,\n AbortReason.QuoteRequestUpdated,\n AbortReason.TransactionSubmitted,\n AbortReason.GaslessTxBatchFetched,\n ].includes(error as AbortReason)\n ) {\n // Exit the function early to prevent other state updates\n return;\n }\n\n this.update((state) => {\n // Reset the batch sell trades if the fetch fails to avoid showing stale data\n state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n // Update loading status\n state.batchSellTradesLoadingStatus = RequestStatus.ERROR;\n });\n console.log(`Failed to fetch batch sell trades`, error);\n }\n };\n\n readonly #trackQuoteValidationFailures = (\n validationFailures: string[],\n featureId: FeatureId,\n ) => {\n if (validationFailures.length === 0) {\n return;\n }\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesValidationFailed,\n {\n feature_id: featureId,\n failures: validationFailures,\n location: this.#location,\n },\n );\n };\n\n readonly #getExchangeRateSources = (): ExchangeRateSourcesForLookup => {\n if (this.#getUseAssetsControllerForRates()) {\n return {\n ...this.messenger.call('AssetsController:getExchangeRatesForBridge'),\n historicalPrices: {},\n ...this.state,\n };\n }\n return {\n ...this.messenger.call('MultichainAssetsRatesController:getState'),\n ...this.messenger.call('CurrencyRateController:getState'),\n ...this.messenger.call('TokenRatesController:getState'),\n ...this.state,\n };\n };\n\n /**\n * Fetches the exchange rates for the assets in the quote request if they are not already in the state\n * In addition to the selected tokens, this also fetches the native asset for the source and destination chains\n *\n * @param quoteRequests - The quote requests to fetch the exchange rates for\n */\n readonly #fetchAssetExchangeRates = async (\n quoteRequests: GenericQuoteRequest[],\n ) => {\n const exchangeRateSources = this.#getExchangeRateSources();\n\n // Get unique assetIds for all quote requests\n const assetIds = new Set<CaipAssetType>(\n quoteRequests\n .flatMap((quoteRequest) =>\n [\n getAssetIdsForToken(\n quoteRequest.srcTokenAddress,\n quoteRequest.srcChainId,\n ),\n getAssetIdsForToken(\n quoteRequest.destTokenAddress,\n quoteRequest.destChainId,\n ),\n ].flat(),\n )\n .filter(\n (assetId: CaipAssetType | undefined): assetId is CaipAssetType =>\n !selectIsAssetExchangeRateInState(exchangeRateSources, assetId),\n ),\n );\n\n const currency = this.#getUseAssetsControllerForRates()\n ? this.messenger.call('AssetsController:getExchangeRatesForBridge')\n .currentCurrency\n : this.messenger.call('CurrencyRateController:getState').currentCurrency;\n\n if (assetIds.size === 0) {\n return;\n }\n\n const pricesByAssetId = await fetchAssetPrices({\n assetIds,\n currencies: new Set([currency]),\n clientId: this.#clientId,\n clientVersion: this.#clientVersion,\n fetchFn: this.#fetchFn,\n signal: this.#abortController?.signal,\n });\n const exchangeRates = toExchangeRates(currency, pricesByAssetId);\n this.update((state) => {\n state.assetExchangeRates = {\n ...state.assetExchangeRates,\n ...exchangeRates,\n };\n });\n };\n\n readonly #hasInsufficientBalance = async (\n quoteRequest: GenericQuoteRequest,\n ) => {\n try {\n const srcChainIdInHex = formatChainIdToHex(quoteRequest.srcChainId);\n const provider =\n this.#getNetworkClientByChainId(srcChainIdInHex)?.provider;\n const normalizedSrcTokenAddress = formatAddressToCaipReference(\n quoteRequest.srcTokenAddress,\n );\n\n return !(\n provider &&\n normalizedSrcTokenAddress &&\n quoteRequest.srcTokenAmount &&\n srcChainIdInHex &&\n (await hasSufficientBalance(\n provider,\n quoteRequest.walletAddress,\n normalizedSrcTokenAddress,\n quoteRequest.srcTokenAmount,\n srcChainIdInHex,\n ))\n );\n } catch (error) {\n console.warn('Failed to set insufficientBal', error);\n // Fall back to true so the backend returns quotes\n return true;\n }\n };\n\n readonly #appendInsufficientBalAndResetApproval = async (\n quoteRequest: GenericQuoteRequest,\n ) => {\n const isSrcChainNonEVM = isNonEvmChainId(quoteRequest.srcChainId);\n const providerConfig = isSrcChainNonEVM\n ? undefined\n : this.#getNetworkClientByChainId(\n formatChainIdToHex(quoteRequest.srcChainId),\n )?.configuration;\n\n let insufficientBal: boolean | undefined;\n let resetApproval: boolean = Boolean(quoteRequest.resetApproval);\n if (isSrcChainNonEVM) {\n // If the source chain is not an EVM network, use value from params\n insufficientBal = quoteRequest.insufficientBal;\n } else if (providerConfig?.rpcUrl?.includes('tenderly')) {\n // If the rpcUrl is a tenderly fork (e2e tests), set insufficientBal=true\n // The bridge-api filters out quotes if the balance on mainnet is insufficient so this override allows quotes to always be returned\n insufficientBal = true;\n } else {\n // Set loading status if RPC calls are made before the quotes are fetched\n this.update((state) => {\n state.quotesLoadingStatus = RequestStatus.LOADING;\n });\n resetApproval = await this.#shouldResetApproval(quoteRequest);\n // Otherwise query the src token balance from the RPC provider\n insufficientBal =\n quoteRequest.insufficientBal ??\n (await this.#hasInsufficientBalance(quoteRequest));\n }\n\n return {\n ...quoteRequest,\n insufficientBal,\n resetApproval,\n };\n };\n\n readonly #shouldResetApproval = async (quoteRequest: GenericQuoteRequest) => {\n if (isNonEvmChainId(quoteRequest.srcChainId)) {\n return false;\n }\n try {\n const normalizedSrcTokenAddress = formatAddressToCaipReference(\n quoteRequest.srcTokenAddress,\n );\n if (isEthUsdt(quoteRequest.srcChainId, normalizedSrcTokenAddress)) {\n const allowance = BigNumber.from(\n await this.#getUSDTMainnetAllowance(\n quoteRequest.walletAddress,\n normalizedSrcTokenAddress,\n quoteRequest.destChainId,\n ),\n );\n return allowance.lt(quoteRequest.srcTokenAmount) && allowance.gt(0);\n }\n return false;\n } catch (error) {\n console.warn('Failed to set resetApproval', error);\n // Fall back to true so the backend returns quotes\n return true;\n }\n };\n\n stopPollingForQuotes = (\n reason?: AbortReason,\n context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived],\n ) => {\n this.stopAllPolling();\n // If polling is stopped before quotes finish loading, track QuotesReceived\n if (this.state.quotesLoadingStatus === RequestStatus.LOADING && context) {\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesReceived,\n context,\n );\n }\n // Clears quotes list in state\n this.#abortController?.abort(reason);\n this.#batchSellTradesAbortController?.abort(reason);\n };\n\n /**\n * Sets the location/entry point for the current swap or bridge flow.\n * Call this when the user enters the flow so that all internally-fired\n * events (InputChanged, QuotesRequested, etc.) carry the correct location.\n *\n * @param location - The entry point from which the user initiated the flow\n */\n setLocation = (location: MetaMetricsSwapsEventSource) => {\n this.#location = location;\n };\n\n resetState = (\n reason = AbortReason.ResetState,\n quoteRequestIndex: number | null = null,\n context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived],\n ) => {\n this.stopPollingForQuotes(reason, context);\n this.update((state) => {\n // Cannot do direct assignment to state, i.e. state = {... }, need to manually assign each field\n if (quoteRequestIndex === null) {\n // Clear all requests if index is null\n state.quoteRequest = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest;\n } else {\n // Otherwise only clear the specified request\n state.quoteRequest = state.quoteRequest\n .slice(0, quoteRequestIndex)\n .concat(DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest[0])\n .concat(state.quoteRequest.slice(quoteRequestIndex + 1));\n }\n state.quotesInitialLoadTime =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesInitialLoadTime;\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n state.quotesLastFetched =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesLastFetched;\n state.quotesLoadingStatus =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesLoadingStatus;\n state.quoteFetchError = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteFetchError;\n state.quotesRefreshCount =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesRefreshCount;\n state.assetExchangeRates =\n DEFAULT_BRIDGE_CONTROLLER_STATE.assetExchangeRates;\n state.minimumBalanceForRentExemptionInLamports =\n DEFAULT_BRIDGE_CONTROLLER_STATE.minimumBalanceForRentExemptionInLamports;\n state.tokenWarnings = DEFAULT_BRIDGE_CONTROLLER_STATE.tokenWarnings;\n state.tokenSecurityTypeDestination =\n DEFAULT_BRIDGE_CONTROLLER_STATE.tokenSecurityTypeDestination;\n state.quoteStreamComplete =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quoteStreamComplete;\n state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n state.batchSellTradesLoadingStatus =\n DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTradesLoadingStatus;\n });\n };\n\n /**\n * Sets the interval length based on the source chain\n */\n setChainIntervalLength = () => {\n const { state } = this;\n // Assume that BatchSell quote requests all have the same source chain\n // Use the first one to determine refresh rate\n const { srcChainId } = state.quoteRequest[0];\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messenger);\n\n const refreshRateOverride = srcChainId\n ? bridgeFeatureFlags.chains[formatChainIdToCaip(srcChainId)]?.refreshRate\n : undefined;\n const defaultRefreshRate = bridgeFeatureFlags.refreshRate;\n this.setIntervalLength(refreshRateOverride ?? defaultRefreshRate);\n };\n\n readonly #fetchBridgeQuotes = async ({\n quoteRequests,\n context,\n }: BridgePollingInput) => {\n this.#abortController?.abort(AbortReason.NewQuoteRequest);\n this.#batchSellTradesAbortController?.abort(AbortReason.NewQuoteRequest);\n\n this.#abortController = new AbortController();\n\n this.#fetchAssetExchangeRates(quoteRequests).catch((error) =>\n console.warn('Failed to fetch asset exchange rates', error),\n );\n\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesRequested,\n context,\n );\n\n const { sse, maxRefreshCount } = getBridgeFeatureFlags(this.messenger);\n const shouldStream =\n sse?.enabled &&\n hasMinimumRequiredVersion(this.#clientVersion, sse.minimumVersion);\n const isBatchSellRequest = quoteRequests.length > 1;\n\n this.update((state) => {\n state.quoteFetchError = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteFetchError;\n state.tokenWarnings = DEFAULT_BRIDGE_CONTROLLER_STATE.tokenWarnings;\n state.quoteStreamComplete =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quoteStreamComplete;\n state.quotesLastFetched = Date.now();\n state.quotesLoadingStatus = RequestStatus.LOADING;\n // Prevent clients from displaying stale batch sell fees\n if (quoteRequests.length > 1) {\n state.batchSellTradesLoadingStatus = RequestStatus.LOADING;\n state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n }\n });\n\n const jwt = await this.#getJwt();\n\n try {\n const [firstQuoteRequest] = quoteRequests;\n\n const unifiedSwapTraceName = isCrossChain(\n firstQuoteRequest.srcChainId,\n firstQuoteRequest.destChainId,\n )\n ? TraceName.BridgeQuotesFetched\n : TraceName.SwapQuotesFetched;\n\n await this.#trace(\n {\n name: isBatchSellRequest\n ? TraceName.BatchSellQuotesFetched\n : unifiedSwapTraceName,\n data: {\n srcChainId: formatChainIdToCaip(firstQuoteRequest.srcChainId),\n destChainId: formatChainIdToCaip(firstQuoteRequest.destChainId),\n },\n },\n async () => {\n const selectedAccount = this.#getMultichainSelectedAccount(\n firstQuoteRequest.walletAddress,\n );\n // This call is not awaited to prevent blocking quote fetching if the snap takes too long to respond\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#setMinimumBalanceForRentExemptionInLamports(\n firstQuoteRequest.srcChainId,\n selectedAccount?.metadata?.snap?.id,\n );\n // Use SSE if enabled and return early\n if (shouldStream || isBatchSellRequest) {\n await this.#handleQuoteStreaming(\n quoteRequests,\n context.feature_id,\n jwt,\n selectedAccount,\n );\n return;\n }\n // Otherwise use regular fetch\n const quotes = await this.fetchQuotes(\n firstQuoteRequest,\n context.feature_id,\n this.#abortController?.signal,\n );\n this.update((state) => {\n // Set the initial load time if this is the first fetch\n if (\n state.quotesRefreshCount ===\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesRefreshCount &&\n this.#quotesFirstFetched\n ) {\n state.quotesInitialLoadTime =\n Date.now() - this.#quotesFirstFetched;\n }\n state.quotes = quotes;\n state.quotesLoadingStatus = RequestStatus.FETCHED;\n });\n },\n );\n } catch (error) {\n // Reset the quotes list if the fetch fails to avoid showing stale quotes\n this.update((state) => {\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n });\n // Ignore abort errors\n if (\n (error as Error).toString().includes('AbortError') ||\n (error as Error).toString().includes('FetchRequestCanceledException') ||\n [\n AbortReason.ResetState,\n AbortReason.NewQuoteRequest,\n AbortReason.QuoteRequestUpdated,\n AbortReason.TransactionSubmitted,\n ].includes(error as AbortReason)\n ) {\n // Exit the function early to prevent other state updates\n return;\n }\n\n // Update loading status and error message\n this.update((state) => {\n // The error object reference is not guaranteed to exist on mobile so reading\n // the message directly could cause an error.\n let errorMessage;\n try {\n errorMessage =\n (error as Error)?.message ?? (error as Error).toString();\n } catch {\n // Intentionally empty\n } finally {\n state.quoteFetchError = errorMessage ?? 'Unknown error';\n }\n state.quotesLoadingStatus = RequestStatus.ERROR;\n });\n // Track event and log error\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesError,\n context,\n );\n console.log(\n `Failed to ${shouldStream ? 'stream' : 'fetch'} bridge quotes`,\n error,\n );\n }\n\n // Update refresh count after fetching, validation and fee calculation have completed\n this.update((state) => {\n state.quotesRefreshCount += 1;\n });\n const hasNoFundedQuoteRequests = quoteRequests.every(\n ({ insufficientBal }) => Boolean(insufficientBal),\n );\n\n if (\n hasNoFundedQuoteRequests\n ? // If all quote requests are insufficiently funded, stop polling\n // So if a BatchSell has at least 1 sufficiently funded quote request, polling continues\n true\n : // Otherwise continue polling until the maximum number of refreshes has been reached\n this.state.quotesRefreshCount >= maxRefreshCount\n ) {\n this.stopAllPolling();\n }\n };\n\n readonly #handleQuoteStreaming = async (\n quoteRequests: GenericQuoteRequest[],\n featureId: FeatureId,\n jwt?: string,\n selectedAccount?: InternalAccount,\n ) => {\n /**\n * Tracks the number of valid quotes received from the current stream, which is used\n * to determine when to clear the quotes list and set the initial load time\n */\n let validQuotesCounter = 0;\n /**\n * Tracks all pending promises from appendFeesToQuotes calls to ensure they complete\n * before setting quotesLoadingStatus to FETCHED\n */\n const pendingFeeAppendPromises = new Set<Promise<void>>();\n\n await fetchBridgeQuoteStream(\n this.#fetchFn,\n quoteRequests,\n this.#abortController?.signal,\n featureId,\n this.#clientId,\n jwt,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n {\n onQuoteValidationFailure: (validationFailures) =>\n this.#trackQuoteValidationFailures(validationFailures, featureId),\n onValidQuoteReceived: async (quote: QuoteResponse) => {\n const feeAppendPromise = (async () => {\n const quotesWithFees = await appendFeesToQuotes(\n [quote],\n this.messenger,\n this.#getLayer1GasFee,\n selectedAccount,\n );\n if (quotesWithFees.length > 0) {\n validQuotesCounter += 1;\n }\n this.update((state) => {\n // Clear previous quotes and quotes load time when first quote in the current\n // polling loop is received\n // This enables clients to continue showing the previous quotes while new\n // quotes are loading\n // Note: If there are no valid quotes until the 2nd fetch, quotesInitialLoadTime will be > refreshRate\n if (validQuotesCounter === 1) {\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n if (!state.quotesInitialLoadTime && this.#quotesFirstFetched) {\n // Set the initial load time after the first quote is received\n state.quotesInitialLoadTime =\n Date.now() - this.#quotesFirstFetched;\n }\n }\n state.quotes = [...state.quotes, ...quotesWithFees];\n });\n })();\n pendingFeeAppendPromises.add(feeAppendPromise);\n feeAppendPromise\n .catch((error) => {\n // Catch errors to prevent them from breaking stream processing\n // If appendFeesToQuotes throws, the state update never happens, so no invalid entry is added\n console.error('Error appending fees to quote', error);\n })\n .finally(() => {\n pendingFeeAppendPromises.delete(feeAppendPromise);\n });\n // Await the promise to ensure errors are caught and handled before continuing\n // The promise is also tracked in pendingFeeAppendPromises for onClose to wait for\n await feeAppendPromise;\n },\n onTokenWarning: (warning) => {\n this.update((state) => {\n const isDuplicate = state.tokenWarnings.some(\n (existing) => existing.feature_id === warning.feature_id,\n );\n if (!isDuplicate) {\n state.tokenWarnings = [...state.tokenWarnings, warning];\n }\n });\n },\n onComplete: (data) => {\n this.update((state) => {\n state.quoteStreamComplete = data;\n });\n },\n onClose: async () => {\n // Wait for all pending appendFeesToQuotes operations to complete\n // before setting quotesLoadingStatus to FETCHED\n await Promise.allSettled(Array.from(pendingFeeAppendPromises));\n this.update((state) => {\n // If there are no valid quotes in the current stream, clear the quotes list\n // to remove quotes from the previous stream\n if (validQuotesCounter === 0) {\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n }\n state.quotesLoadingStatus = RequestStatus.FETCHED;\n });\n },\n },\n this.#clientVersion,\n );\n };\n\n readonly #setMinimumBalanceForRentExemptionInLamports = async (\n srcChainId: GenericQuoteRequest['srcChainId'],\n snapId?: string,\n ) => {\n if (!isSolanaChainId(srcChainId) || !snapId) {\n return;\n }\n const minimumBalanceForRentExemptionInLamports =\n await getMinimumBalanceForRentExemptionInLamports(snapId, this.messenger);\n this.update((state) => {\n state.minimumBalanceForRentExemptionInLamports =\n minimumBalanceForRentExemptionInLamports;\n });\n };\n\n #getMultichainSelectedAccount(\n walletAddress?: GenericQuoteRequest['walletAddress'],\n ) {\n // Assume that all quotes in a batch are for the same account\n const addressToUse =\n walletAddress ?? this.state.quoteRequest[0].walletAddress;\n if (!addressToUse) {\n throw new Error('Account address is required');\n }\n const selectedAccount = this.messenger.call(\n 'AccountsController:getAccountByAddress',\n addressToUse,\n );\n return selectedAccount;\n }\n\n #getNetworkClientByChainId(chainId: Hex) {\n const networkClientId = this.messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n chainId,\n );\n if (!networkClientId) {\n throw new Error(`No network client found for chainId: ${chainId}`);\n }\n const networkClient = this.messenger.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n return networkClient;\n }\n\n readonly #getJwt = async (): Promise<string | undefined> => {\n try {\n const token = await this.messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n return token;\n } catch (error) {\n console.error('Error getting JWT token for bridge-api request', error);\n return undefined;\n }\n };\n\n readonly #getRequestMetadata = (\n quoteRequestIndex: number = 0,\n ): Omit<\n RequestMetadata,\n 'stx_enabled' | 'usd_amount_source' | 'security_warnings'\n > => {\n const quoteRequest = this.state.quoteRequest[quoteRequestIndex];\n const { walletAddress } = quoteRequest;\n const accountHardwareType = getAccountHardwareType(\n walletAddress\n ? this.#getMultichainSelectedAccount(walletAddress)\n : undefined,\n );\n\n return {\n slippage_limit: quoteRequest.slippage,\n swap_type: getSwapTypeFromQuote(quoteRequest),\n custom_slippage: isCustomSlippage(quoteRequest.slippage),\n account_hardware_type: accountHardwareType,\n is_hardware_wallet: accountHardwareType !== null,\n };\n };\n\n readonly #getQuoteFetchData = (): Omit<\n QuoteFetchData,\n 'best_quote_provider' | 'price_impact' | 'can_submit'\n > => {\n return {\n quotes_count: this.state.quotes.length,\n quotes_list: this.state.quotes.map(({ quote }) =>\n formatProviderLabel(quote),\n ),\n initial_load_time_all_quotes: this.state.quotesInitialLoadTime ?? 0,\n has_gas_included_quote: this.state.quotes.some(\n ({ quote }) => quote.gasIncluded,\n ),\n };\n };\n\n readonly #getEventProperties = <\n EventName extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: EventName,\n propertiesFromClient: Pick<\n RequiredEventContextFromClient,\n EventName\n >[EventName],\n quoteRequestIndex: number = 0,\n ): CrossChainSwapsEventProperties<EventName> => {\n const clientProps = propertiesFromClient as Record<string, unknown>;\n const baseProperties = {\n ...propertiesFromClient,\n location: clientProps?.location ?? this.#location,\n action_type: MetricsActionType.SWAPBRIDGE_V1,\n };\n const quoteRequest = this.state.quoteRequest[quoteRequestIndex];\n switch (eventName) {\n case UnifiedSwapBridgeEventName.ButtonClicked:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.PageViewed:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesValidationFailed:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n refresh_count: this.state.quotesRefreshCount,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesReceived:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n refresh_count: this.state.quotesRefreshCount,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesRequested:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n has_sufficient_funds: !quoteRequest.insufficientBal,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesError:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n error_message: this.state.quoteFetchError,\n has_sufficient_funds: !quoteRequest.insufficientBal,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.AllQuotesOpened:\n case UnifiedSwapBridgeEventName.AllQuotesSorted:\n case UnifiedSwapBridgeEventName.QuoteSelected:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.Failed: {\n // Populate the properties that the error occurred before the tx was submitted\n return {\n ...baseProperties,\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n ...propertiesFromClient,\n };\n }\n case UnifiedSwapBridgeEventName.AssetDetailTooltipClicked:\n case UnifiedSwapBridgeEventName.AssetPickerOpened:\n return baseProperties;\n // Inject `token_security_type_destination` from controller state so the\n // field is always present on this event. `baseProperties` (which spreads\n // `propertiesFromClient`) wins if the client supplies a value explicitly.\n case UnifiedSwapBridgeEventName.InputSourceDestinationSwitched:\n return {\n token_security_type_destination:\n this.state.tokenSecurityTypeDestination,\n ...baseProperties,\n };\n // These events may be published after the bridge-controller state is reset\n // So the BridgeStatusController populates all the properties\n case UnifiedSwapBridgeEventName.Submitted:\n case UnifiedSwapBridgeEventName.Completed:\n return propertiesFromClient;\n case UnifiedSwapBridgeEventName.InputChanged:\n default:\n return baseProperties;\n }\n };\n\n readonly #trackInputChangedEvents = (\n paramsToUpdate: Partial<GenericQuoteRequest>,\n featureId: FeatureId,\n quoteRequestIndex: number = 0,\n ) => {\n Object.entries(paramsToUpdate).forEach(([key, value]) => {\n const inputKey = toInputChangedPropertyKey[key as keyof QuoteRequest];\n const inputValue =\n toInputChangedPropertyValue[key as keyof QuoteRequest]?.(\n paramsToUpdate,\n );\n if (\n inputKey &&\n inputValue !== undefined &&\n this.state.quoteRequest[quoteRequestIndex] &&\n value !==\n this.state.quoteRequest[quoteRequestIndex][\n key as keyof GenericQuoteRequest\n ]\n ) {\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.InputChanged,\n {\n input: inputKey,\n input_value: inputValue,\n location: this.#location,\n feature_id: featureId,\n },\n );\n }\n });\n };\n\n /**\n * This method tracks cross-chain swaps events\n *\n * @param eventName - The name of the event to track\n * @param propertiesFromClient - Properties that can't be calculated from the event name and need to be provided by the client\n * @param quoteRequestIndex - The index of the quote request to track the event for\n * @example\n * this.trackUnifiedSwapBridgeEvent(UnifiedSwapBridgeEventName.ActionOpened, {\n * location: MetaMetricsSwapsEventSource.MainView,\n * });\n */\n trackUnifiedSwapBridgeEvent = <\n EventName extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: EventName,\n propertiesFromClient: Pick<\n RequiredEventContextFromClient,\n EventName\n >[EventName],\n quoteRequestIndex: number = 0,\n ) => {\n try {\n const combinedPropertiesForEvent = this.#getEventProperties<EventName>(\n eventName,\n propertiesFromClient,\n quoteRequestIndex,\n );\n\n this.#trackMetaMetricsFn(eventName, combinedPropertiesForEvent);\n } catch (error) {\n console.error(\n `Error tracking cross-chain swaps MetaMetrics event ${eventName}`,\n error,\n );\n }\n };\n\n /**\n *\n * @param walletAddress - The address of the account to get the allowance for\n * @param contractAddress - The address of the ERC20 token contract on mainnet\n * @param destinationChainId - The chain ID of the destination network\n * @returns The atomic allowance of the ERC20 token contract\n */\n readonly #getUSDTMainnetAllowance = async (\n walletAddress: string,\n contractAddress: string,\n destinationChainId: GenericQuoteRequest['destChainId'],\n ): Promise<string> => {\n const networkClient = this.#getNetworkClientByChainId(CHAIN_IDS.MAINNET);\n const provider = networkClient?.provider;\n if (!provider) {\n throw new Error('No provider found');\n }\n\n const ethersProvider = new Web3Provider(provider);\n const contract = new Contract(contractAddress, abiERC20, ethersProvider);\n const spenderAddress = isCrossChain(CHAIN_IDS.MAINNET, destinationChainId)\n ? METABRIDGE_ETHEREUM_ADDRESS\n : SWAPS_CONTRACT_ADDRESSES[CHAIN_IDS.MAINNET];\n const allowance: BigNumber = await contract.allowance(\n walletAddress,\n spenderAddress,\n );\n return allowance.toString();\n };\n}\n"]}
@@ -2,11 +2,11 @@ import type { TraceCallback } from "@metamask/controller-utils";
2
2
  import type { TransactionController } from "@metamask/transaction-controller";
3
3
  import type { BridgeClientId } from "./constants/bridge.cjs";
4
4
  import { BRIDGE_CONTROLLER_NAME } from "./constants/bridge.cjs";
5
+ import { FeatureId } from "./types.cjs";
5
6
  import type { L1GasFees, GenericQuoteRequest, NonEvmFees, QuoteResponse, BridgeControllerState, BridgeControllerMessenger, FetchFunction } from "./types.cjs";
6
7
  import { AbortReason, MetaMetricsSwapsEventSource, UnifiedSwapBridgeEventName } from "./utils/metrics/constants.cjs";
7
8
  import type { RequiredEventContextFromClient } from "./utils/metrics/types.cjs";
8
9
  import type { CrossChainSwapsEventProperties } from "./utils/metrics/types.cjs";
9
- import type { FeatureId } from "./utils/validators.cjs";
10
10
  /**
11
11
  * The input to start polling for the {@link BridgeController}
12
12
  *
@@ -16,15 +16,7 @@ import type { FeatureId } from "./utils/validators.cjs";
16
16
  */
17
17
  type BridgePollingInput = {
18
18
  quoteRequests: GenericQuoteRequest[];
19
- context: Pick<RequiredEventContextFromClient, UnifiedSwapBridgeEventName.QuotesError>[UnifiedSwapBridgeEventName.QuotesError] & Pick<RequiredEventContextFromClient, UnifiedSwapBridgeEventName.QuotesRequested>[UnifiedSwapBridgeEventName.QuotesRequested] &
20
- /**
21
- * Client-supplied security classification for the destination token
22
- * (e.g. from token security/scanning data). Stored on the controller
23
- * and merged into every analytics event that includes
24
- * `token_address_destination`. Pass `null` when no security data is
25
- * available for the selected destination token.
26
- */
27
- Pick<RequiredEventContextFromClient[UnifiedSwapBridgeEventName.InputSourceDestinationSwitched], 'token_security_type_destination'>;
19
+ context: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesError] & RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesRequested];
28
20
  };
29
21
  declare const BridgeController_base: (abstract new (...args: any[]) => {
30
22
  readonly "__#17@#intervalIds": Record<string, NodeJS.Timeout>;
@@ -80,11 +72,11 @@ export declare class BridgeController extends BridgeController_base<typeof BRIDG
80
72
  * This method does not start polling for quotes and does not emit UnifiedSwapBridge events
81
73
  *
82
74
  * @param quoteRequest - The parameters for quote requests to fetch
83
- * @param abortSignal - The abort signal to cancel all the requests
84
75
  * @param featureId - The feature ID that maps to quoteParam overrides from LD
76
+ * @param abortSignal - The abort signal to cancel all the requests
85
77
  * @returns A list of validated quotes
86
78
  */
87
- fetchQuotes: (quoteRequest: GenericQuoteRequest, abortSignal?: AbortSignal | null, featureId?: FeatureId | null) => Promise<(QuoteResponse & L1GasFees & NonEvmFees)[]>;
79
+ fetchQuotes: (quoteRequest: GenericQuoteRequest, featureId: FeatureId, abortSignal?: AbortSignal | null) => Promise<(QuoteResponse & L1GasFees & NonEvmFees)[]>;
88
80
  /**
89
81
  * Fetches gasless transaction data and fees for BatchSell quotes.
90
82
  * To use this in the clients, add a listener for the recommendedQuotes and call
@@ -103,7 +95,7 @@ export declare class BridgeController extends BridgeController_base<typeof BRIDG
103
95
  * @param location - The entry point from which the user initiated the flow
104
96
  */
105
97
  setLocation: (location: MetaMetricsSwapsEventSource) => void;
106
- resetState: (reason?: AbortReason, quoteRequestIndex?: number | null) => void;
98
+ resetState: (reason?: AbortReason, quoteRequestIndex?: number | null, context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived]) => void;
107
99
  /**
108
100
  * Sets the interval length based on the source chain
109
101
  */
@@ -1 +1 @@
1
- {"version":3,"file":"bridge-controller.d.cts","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,mCAAmC;AAIhE,OAAO,KAAK,EAAE,qBAAqB,EAAE,yCAAyC;AAG9E,OAAO,KAAK,EAAE,cAAc,EAAE,+BAA2B;AACzD,OAAO,EACL,sBAAsB,EAKvB,+BAA2B;AAS5B,OAAO,KAAK,EACV,SAAS,EACT,mBAAmB,EACnB,UAAU,EAEV,aAAa,EACb,qBAAqB,EACrB,yBAAyB,EACzB,aAAa,EACd,oBAAgB;AAyBjB,OAAO,EACL,WAAW,EACX,2BAA2B,EAE3B,0BAA0B,EAC3B,sCAAkC;AAUnC,OAAO,KAAK,EAGV,8BAA8B,EAC/B,kCAA8B;AAC/B,OAAO,KAAK,EAAE,8BAA8B,EAAE,kCAA8B;AAQ5E,OAAO,KAAK,EAAE,SAAS,EAAE,+BAA2B;AAyFpD;;;;;;GAMG;AACH,KAAK,kBAAkB,GAAG;IACxB,aAAa,EAAE,mBAAmB,EAAE,CAAC;IACrC,OAAO,EAAE,IAAI,CACX,8BAA8B,EAC9B,0BAA0B,CAAC,WAAW,CACvC,CAAC,0BAA0B,CAAC,WAAW,CAAC,GACvC,IAAI,CACF,8BAA8B,EAC9B,0BAA0B,CAAC,eAAe,CAC3C,CAAC,0BAA0B,CAAC,eAAe,CAAC;IAC7C;;;;;;OAMG;IACH,IAAI,CACF,8BAA8B,CAAC,0BAA0B,CAAC,8BAA8B,CAAC,EACzF,iCAAiC,CAClC,CAAC;CACL,CAAC;;;;;;;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