@metamask-previews/bridge-controller 77.8.0-preview-ec4680201 → 77.8.0-preview-7aad920a3

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 (196) hide show
  1. package/CHANGELOG.md +12 -2
  2. package/dist/bridge-controller.cjs +8 -3
  3. package/dist/bridge-controller.cjs.map +1 -1
  4. package/dist/bridge-controller.d.cts +2 -1
  5. package/dist/bridge-controller.d.cts.map +1 -1
  6. package/dist/bridge-controller.d.mts +2 -1
  7. package/dist/bridge-controller.d.mts.map +1 -1
  8. package/dist/bridge-controller.mjs +8 -3
  9. package/dist/bridge-controller.mjs.map +1 -1
  10. package/dist/coercers/quote-response-v1-to-v2.cjs +137 -0
  11. package/dist/coercers/quote-response-v1-to-v2.cjs.map +1 -0
  12. package/dist/coercers/quote-response-v1-to-v2.d.cts +13 -0
  13. package/dist/coercers/quote-response-v1-to-v2.d.cts.map +1 -0
  14. package/dist/coercers/quote-response-v1-to-v2.d.mts +13 -0
  15. package/dist/coercers/quote-response-v1-to-v2.d.mts.map +1 -0
  16. package/dist/coercers/quote-response-v1-to-v2.mjs +132 -0
  17. package/dist/coercers/quote-response-v1-to-v2.mjs.map +1 -0
  18. package/dist/coercers/quote-response-v2-to-v1.cjs +173 -0
  19. package/dist/coercers/quote-response-v2-to-v1.cjs.map +1 -0
  20. package/dist/coercers/quote-response-v2-to-v1.d.cts +13 -0
  21. package/dist/coercers/quote-response-v2-to-v1.d.cts.map +1 -0
  22. package/dist/coercers/quote-response-v2-to-v1.d.mts +13 -0
  23. package/dist/coercers/quote-response-v2-to-v1.d.mts.map +1 -0
  24. package/dist/coercers/quote-response-v2-to-v1.mjs +169 -0
  25. package/dist/coercers/quote-response-v2-to-v1.mjs.map +1 -0
  26. package/dist/index.cjs +21 -2
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +13 -5
  29. package/dist/index.d.cts.map +1 -1
  30. package/dist/index.d.mts +13 -5
  31. package/dist/index.d.mts.map +1 -1
  32. package/dist/index.mjs +8 -2
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/selectors.cjs +53 -31
  35. package/dist/selectors.cjs.map +1 -1
  36. package/dist/selectors.d.cts +5831 -35747
  37. package/dist/selectors.d.cts.map +1 -1
  38. package/dist/selectors.d.mts +5831 -35747
  39. package/dist/selectors.d.mts.map +1 -1
  40. package/dist/selectors.mjs +53 -31
  41. package/dist/selectors.mjs.map +1 -1
  42. package/dist/types.cjs.map +1 -1
  43. package/dist/types.d.cts +2 -7
  44. package/dist/types.d.cts.map +1 -1
  45. package/dist/types.d.mts +2 -7
  46. package/dist/types.d.mts.map +1 -1
  47. package/dist/types.mjs.map +1 -1
  48. package/dist/utils/bridge.cjs +1 -5
  49. package/dist/utils/bridge.cjs.map +1 -1
  50. package/dist/utils/bridge.d.cts +2 -19
  51. package/dist/utils/bridge.d.cts.map +1 -1
  52. package/dist/utils/bridge.d.mts +2 -19
  53. package/dist/utils/bridge.d.mts.map +1 -1
  54. package/dist/utils/bridge.mjs +0 -3
  55. package/dist/utils/bridge.mjs.map +1 -1
  56. package/dist/utils/caip-formatters.cjs +0 -3
  57. package/dist/utils/caip-formatters.cjs.map +1 -1
  58. package/dist/utils/caip-formatters.d.cts.map +1 -1
  59. package/dist/utils/caip-formatters.d.mts.map +1 -1
  60. package/dist/utils/caip-formatters.mjs +0 -3
  61. package/dist/utils/caip-formatters.mjs.map +1 -1
  62. package/dist/utils/feature-flags.d.cts +2 -2
  63. package/dist/utils/feature-flags.d.mts +2 -2
  64. package/dist/utils/fetch.cjs +37 -40
  65. package/dist/utils/fetch.cjs.map +1 -1
  66. package/dist/utils/fetch.d.cts +10 -4
  67. package/dist/utils/fetch.d.cts.map +1 -1
  68. package/dist/utils/fetch.d.mts +10 -4
  69. package/dist/utils/fetch.d.mts.map +1 -1
  70. package/dist/utils/fetch.mjs +37 -40
  71. package/dist/utils/fetch.mjs.map +1 -1
  72. package/dist/utils/metrics/properties.cjs +6 -6
  73. package/dist/utils/metrics/properties.cjs.map +1 -1
  74. package/dist/utils/metrics/properties.d.cts +8 -5
  75. package/dist/utils/metrics/properties.d.cts.map +1 -1
  76. package/dist/utils/metrics/properties.d.mts +8 -5
  77. package/dist/utils/metrics/properties.d.mts.map +1 -1
  78. package/dist/utils/metrics/properties.mjs +6 -6
  79. package/dist/utils/metrics/properties.mjs.map +1 -1
  80. package/dist/utils/metrics/types.cjs.map +1 -1
  81. package/dist/utils/metrics/types.d.cts +1 -1
  82. package/dist/utils/metrics/types.d.cts.map +1 -1
  83. package/dist/utils/metrics/types.d.mts +1 -1
  84. package/dist/utils/metrics/types.d.mts.map +1 -1
  85. package/dist/utils/metrics/types.mjs.map +1 -1
  86. package/dist/utils/number-formatters.cjs +74 -1
  87. package/dist/utils/number-formatters.cjs.map +1 -1
  88. package/dist/utils/number-formatters.d.cts +18 -0
  89. package/dist/utils/number-formatters.d.cts.map +1 -1
  90. package/dist/utils/number-formatters.d.mts +18 -0
  91. package/dist/utils/number-formatters.d.mts.map +1 -1
  92. package/dist/utils/number-formatters.mjs +71 -0
  93. package/dist/utils/number-formatters.mjs.map +1 -1
  94. package/dist/utils/quote-fees.cjs +23 -22
  95. package/dist/utils/quote-fees.cjs.map +1 -1
  96. package/dist/utils/quote-fees.d.cts +4 -2
  97. package/dist/utils/quote-fees.d.cts.map +1 -1
  98. package/dist/utils/quote-fees.d.mts +4 -2
  99. package/dist/utils/quote-fees.d.mts.map +1 -1
  100. package/dist/utils/quote-fees.mjs +24 -23
  101. package/dist/utils/quote-fees.mjs.map +1 -1
  102. package/dist/utils/quote-metadata/calculators.cjs +74 -36
  103. package/dist/utils/quote-metadata/calculators.cjs.map +1 -1
  104. package/dist/utils/quote-metadata/calculators.d.cts +22 -14
  105. package/dist/utils/quote-metadata/calculators.d.cts.map +1 -1
  106. package/dist/utils/quote-metadata/calculators.d.mts +22 -14
  107. package/dist/utils/quote-metadata/calculators.d.mts.map +1 -1
  108. package/dist/utils/quote-metadata/calculators.mjs +73 -36
  109. package/dist/utils/quote-metadata/calculators.mjs.map +1 -1
  110. package/dist/utils/quote-metadata/merge.cjs +24 -4
  111. package/dist/utils/quote-metadata/merge.cjs.map +1 -1
  112. package/dist/utils/quote-metadata/merge.d.cts +7 -3
  113. package/dist/utils/quote-metadata/merge.d.cts.map +1 -1
  114. package/dist/utils/quote-metadata/merge.d.mts +7 -3
  115. package/dist/utils/quote-metadata/merge.d.mts.map +1 -1
  116. package/dist/utils/quote-metadata/merge.mjs +24 -4
  117. package/dist/utils/quote-metadata/merge.mjs.map +1 -1
  118. package/dist/utils/quote-metadata/to-normalized-amounts.cjs +38 -0
  119. package/dist/utils/quote-metadata/to-normalized-amounts.cjs.map +1 -0
  120. package/dist/utils/quote-metadata/to-normalized-amounts.d.cts +10 -0
  121. package/dist/utils/quote-metadata/to-normalized-amounts.d.cts.map +1 -0
  122. package/dist/utils/quote-metadata/to-normalized-amounts.d.mts +10 -0
  123. package/dist/utils/quote-metadata/to-normalized-amounts.d.mts.map +1 -0
  124. package/dist/utils/quote-metadata/to-normalized-amounts.mjs +34 -0
  125. package/dist/utils/quote-metadata/to-normalized-amounts.mjs.map +1 -0
  126. package/dist/utils/quote-metadata/to-quote-metadata-v1.cjs +39 -0
  127. package/dist/utils/quote-metadata/to-quote-metadata-v1.cjs.map +1 -0
  128. package/dist/utils/quote-metadata/to-quote-metadata-v1.d.cts +13 -0
  129. package/dist/utils/quote-metadata/to-quote-metadata-v1.d.cts.map +1 -0
  130. package/dist/utils/quote-metadata/to-quote-metadata-v1.d.mts +13 -0
  131. package/dist/utils/quote-metadata/to-quote-metadata-v1.d.mts.map +1 -0
  132. package/dist/utils/quote-metadata/to-quote-metadata-v1.mjs +36 -0
  133. package/dist/utils/quote-metadata/to-quote-metadata-v1.mjs.map +1 -0
  134. package/dist/utils/quote-metadata/to-quote-metadata-v2.cjs +90 -0
  135. package/dist/utils/quote-metadata/to-quote-metadata-v2.cjs.map +1 -0
  136. package/dist/utils/quote-metadata/to-quote-metadata-v2.d.cts +12 -0
  137. package/dist/utils/quote-metadata/to-quote-metadata-v2.d.cts.map +1 -0
  138. package/dist/utils/quote-metadata/to-quote-metadata-v2.d.mts +12 -0
  139. package/dist/utils/quote-metadata/to-quote-metadata-v2.d.mts.map +1 -0
  140. package/dist/utils/quote-metadata/to-quote-metadata-v2.mjs +86 -0
  141. package/dist/utils/quote-metadata/to-quote-metadata-v2.mjs.map +1 -0
  142. package/dist/utils/slippage.d.cts +1 -1
  143. package/dist/utils/slippage.d.mts +1 -1
  144. package/dist/validators/amount-and-asset.cjs +27 -0
  145. package/dist/validators/amount-and-asset.cjs.map +1 -0
  146. package/dist/validators/amount-and-asset.d.cts +62 -0
  147. package/dist/validators/amount-and-asset.d.cts.map +1 -0
  148. package/dist/validators/amount-and-asset.d.mts +62 -0
  149. package/dist/validators/amount-and-asset.d.mts.map +1 -0
  150. package/dist/validators/amount-and-asset.mjs +24 -0
  151. package/dist/validators/amount-and-asset.mjs.map +1 -0
  152. package/dist/validators/batch-sell.d.cts +8 -8
  153. package/dist/validators/batch-sell.d.mts +8 -8
  154. package/dist/validators/bridge-asset.cjs +65 -1
  155. package/dist/validators/bridge-asset.cjs.map +1 -1
  156. package/dist/validators/bridge-asset.d.cts +99 -5
  157. package/dist/validators/bridge-asset.d.cts.map +1 -1
  158. package/dist/validators/bridge-asset.d.mts +99 -5
  159. package/dist/validators/bridge-asset.d.mts.map +1 -1
  160. package/dist/validators/bridge-asset.mjs +64 -1
  161. package/dist/validators/bridge-asset.mjs.map +1 -1
  162. package/dist/validators/feature-flags.d.cts +5 -5
  163. package/dist/validators/feature-flags.d.mts +5 -5
  164. package/dist/validators/intent.d.cts +3 -3
  165. package/dist/validators/intent.d.mts +3 -3
  166. package/dist/validators/quote-response-v1.d.cts +179 -179
  167. package/dist/validators/quote-response-v1.d.mts +179 -179
  168. package/dist/validators/quote-response.cjs +116 -0
  169. package/dist/validators/quote-response.cjs.map +1 -0
  170. package/dist/validators/quote-response.d.cts +1959 -0
  171. package/dist/validators/quote-response.d.cts.map +1 -0
  172. package/dist/validators/quote-response.d.mts +1959 -0
  173. package/dist/validators/quote-response.d.mts.map +1 -0
  174. package/dist/validators/quote-response.mjs +112 -0
  175. package/dist/validators/quote-response.mjs.map +1 -0
  176. package/dist/validators/quote.cjs +69 -3
  177. package/dist/validators/quote.cjs.map +1 -1
  178. package/dist/validators/quote.d.cts +403 -45
  179. package/dist/validators/quote.d.cts.map +1 -1
  180. package/dist/validators/quote.d.mts +403 -45
  181. package/dist/validators/quote.d.mts.map +1 -1
  182. package/dist/validators/quote.mjs +70 -4
  183. package/dist/validators/quote.mjs.map +1 -1
  184. package/dist/validators/step.cjs +7 -1
  185. package/dist/validators/step.cjs.map +1 -1
  186. package/dist/validators/step.d.cts +197 -26
  187. package/dist/validators/step.d.cts.map +1 -1
  188. package/dist/validators/step.d.mts +197 -26
  189. package/dist/validators/step.d.mts.map +1 -1
  190. package/dist/validators/step.mjs +7 -1
  191. package/dist/validators/step.mjs.map +1 -1
  192. package/dist/validators/token-feature.d.cts +2 -2
  193. package/dist/validators/token-feature.d.mts +2 -2
  194. package/dist/validators/trade.d.cts +2 -2
  195. package/dist/validators/trade.d.mts +2 -2
  196. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -9,17 +9,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Added
11
11
 
12
+ - Define `QuoteResponse` v2 ([#9085](https://github.com/MetaMask/core/pull/9085))
13
+ - `validateQuoteResponse` validates data
14
+ - `toQuoteResponseV2` and `toQuoteResponseV1` convert quote responses to required schema when needed
15
+ - Export `BridgeAsset` and `validateBridgeAsset`, used by QuoteResponse v2, and token endpoints ([#9085](https://github.com/MetaMask/core/pull/9085))
12
16
  - Return `priceImpact` and `relayerFee` as part of `QuoteMetadata` ([#9507](https://github.com/MetaMask/core/pull/9507))
13
17
 
14
18
  ### Changed
15
19
 
20
+ - **BREAKING:** Use QuoteResponse V2 within the BridgeController; this affects the batch-sell, unified swap/bridge and quickBuy experiences ([#9085](https://github.com/MetaMask/core/pull/9085))
21
+ - convert quotes to QuoteResponse v2 in `fetchBridgeQuoteStream`
22
+ - store quotes as QuoteResponse v2 in the BridgeController
23
+ - `QuoteResponse` export now means v2; v1 is still exported as `QuoteResponseV1`
24
+ - `fetchBridgeQuoteStream` now returns `QuoteResponse` v2
25
+ - `appendFeesToQuotes` interface now requires a chainId parameter, but still accepts both V1 and V2 quotes
16
26
  - **BREAKING:** Make `QuoteMetadata` fields optional and remove unused values
17
27
  - Remove falsy (`0` and `null`) fallbacks; missing values are now `undefined`
18
28
  - Replace `gasFee.effective`, `gasFee.max`, and `totalMaxNetworkFee` usages with `gasFee.total` and `totalNetworkFee`.
19
29
  - Extract quote-metadata calculation into `utils/quote-metadata/` ([#9507](https://github.com/MetaMask/core/pull/9507))
20
30
  - Implement `mergeQuoteMetadata` util which appends QuoteMetadata to QuoteResponse ([#9507](https://github.com/MetaMask/core/pull/9507))
21
- - Bump `@metamask/assets-controller` from `^11.1.1` to `^11.2.0` ([#9629](https://github.com/MetaMask/core/pull/9629))
22
- - Bump `@metamask/gas-fee-controller` from `^26.2.4` to `^26.3.0` ([#9629](https://github.com/MetaMask/core/pull/9629))
31
+ - Extend `mergeQuoteMetadata` to handle merging metadata and normalizedAmounts into the V2 QuoteResponse ([#9085](https://github.com/MetaMask/core/pull/9085))
32
+ - Update legacy quote metadata calculators, selectors and meterics to use V2 paths (quote.src / quote.dest, etc.) ([#9085](https://github.com/MetaMask/core/pull/9085))
23
33
 
24
34
  ## [77.8.0]
25
35
 
@@ -19,6 +19,7 @@ const contracts_1 = require("@ethersproject/contracts");
19
19
  const providers_1 = require("@ethersproject/providers");
20
20
  const metamask_eth_abis_1 = require("@metamask/metamask-eth-abis");
21
21
  const polling_controller_1 = require("@metamask/polling-controller");
22
+ const quote_response_v1_to_v2_1 = require("./coercers/quote-response-v1-to-v2.cjs");
22
23
  const bridge_1 = require("./constants/bridge.cjs");
23
24
  const chains_1 = require("./constants/chains.cjs");
24
25
  const swaps_1 = require("./constants/swaps.cjs");
@@ -247,7 +248,11 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
247
248
  ? { ...quoteRequest, ...quoteRequestOverrides, resetApproval }
248
249
  : { ...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"));
249
250
  __classPrivateFieldGet(this, _BridgeController_trackQuoteValidationFailures, "f").call(this, validationFailures, featureId);
250
- 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));
251
+ const srcChainIds = Array.from(new Set(baseQuotes.map((quote) => quote.quote.srcChainId))).filter(Boolean);
252
+ const quotesWithFees = srcChainIds.length > 1 || srcChainIds.length === 0
253
+ ? // Don't append fees if there are multiple srcChainIds
254
+ baseQuotes
255
+ : await (0, quote_fees_1.appendFeesToQuotes)((0, caip_formatters_1.formatChainIdToCaip)(srcChainIds[0]), baseQuotes, this.messenger, __classPrivateFieldGet(this, _BridgeController_getLayer1GasFee, "f"), __classPrivateFieldGet(this, _BridgeController_instances, "m", _BridgeController_getMultichainSelectedAccount).call(this, quoteRequest.walletAddress));
251
256
  return (0, sort_quotes_1.sortQuotes)(quotesWithFees, featureId);
252
257
  };
253
258
  /**
@@ -570,7 +575,7 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
570
575
  state.quotesInitialLoadTime =
571
576
  Date.now() - __classPrivateFieldGet(this, _BridgeController_quotesFirstFetched, "f");
572
577
  }
573
- state.quotes = quotes;
578
+ state.quotes = quotes.map(quote_response_v1_to_v2_1.toQuoteResponseV2);
574
579
  state.quotesLoadingStatus = types_1.RequestStatus.FETCHED;
575
580
  });
576
581
  });
@@ -642,7 +647,7 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
642
647
  onQuoteValidationFailure: (validationFailures) => __classPrivateFieldGet(this, _BridgeController_trackQuoteValidationFailures, "f").call(this, validationFailures, featureId),
643
648
  onValidQuoteReceived: async (quote) => {
644
649
  const feeAppendPromise = (async () => {
645
- const quotesWithFees = await (0, quote_fees_1.appendFeesToQuotes)([quote], this.messenger, __classPrivateFieldGet(this, _BridgeController_getLayer1GasFee, "f"), selectedAccount);
650
+ const quotesWithFees = await (0, quote_fees_1.appendFeesToQuotes)(quote.chainId, [quote], this.messenger, __classPrivateFieldGet(this, _BridgeController_getLayer1GasFee, "f"), selectedAccount);
646
651
  if (quotesWithFees.length > 0) {
647
652
  validQuotesCounter += 1;
648
653
  }
@@ -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,6DAMmC;AAKnC,+DAQoC;AAOpC,uDAAwD;AACxD,6CAA4E;AAC5E,yDAAiD;AAEjD,kEAGoC;AAGpC,MAAM,QAAQ,GAAyC;IACrD,YAAY,EAAE;QACZ,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,Q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AAI,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 BridgeControllerState,\n BridgeControllerMessenger,\n FetchFunction,\n InputPrimaryDenomination,\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 BatchSellMetricsEventName,\n MetaMetricsSwapsEventSource,\n MetricsActionType,\n UnifiedSwapBridgeEventName,\n} from './utils/metrics/constants';\nimport type {\n BridgeControllerMetricsEventName,\n BridgeControllerMetricsLocation,\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 { appendFeesToQuotes } from './utils/quote-fees';\nimport { getMinimumBalanceForRentExemptionInLamports } from './utils/snaps';\nimport { sortQuotes } from './utils/sort-quotes';\nimport type { FeatureId } from './validators/feature-flags';\nimport {\n isValidQuoteRequest,\n isValidBatchSellQuoteRequest,\n} from './validators/quote-request';\nimport type { QuoteResponseV1 } from './validators/quote-response-v1';\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 inputPrimaryDenomination: {\n includeInStateLogs: true,\n persist: true,\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 'getLocation',\n 'setInputPrimaryDenomination',\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: BridgeControllerMetricsLocation =\n MetaMetricsSwapsEventSource.Unknown;\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 BridgeControllerMetricsEventName,\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: <EventName extends BridgeControllerMetricsEventName>(\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<(QuoteResponseV1 & 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: (QuoteResponseV1 | 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 ...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: BridgeControllerMetricsLocation) => {\n this.#location = location;\n };\n\n /**\n * Returns the location/entry point for the current swap or bridge flow.\n *\n * @returns The entry point from which the user initiated the flow\n */\n getLocation = (): BridgeControllerMetricsLocation => {\n return this.#location;\n };\n\n setInputPrimaryDenomination = (\n inputPrimaryDenomination: InputPrimaryDenomination,\n ) => {\n this.update((state) => {\n state.inputPrimaryDenomination = inputPrimaryDenomination;\n });\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: QuoteResponseV1) => {\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 BridgeControllerMetricsEventName,\n >(\n eventName: EventName,\n propertiesFromClient: Pick<\n RequiredEventContextFromClient,\n EventName\n >[EventName],\n quoteRequestIndex: number = 0,\n ) => {\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 inputPrimaryDenominationProperties = {\n input_primary_denomination: this.state.inputPrimaryDenomination,\n };\n const batchSellClientChainProperties = propertiesFromClient as Pick<\n RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellTokenPageViewed],\n 'chain_id_source' | 'chain_id_destination'\n >;\n const batchSellBaseProperties = {\n chain_id_source: batchSellClientChainProperties.chain_id_source,\n chain_id_destination: batchSellClientChainProperties.chain_id_destination,\n location: clientProps?.location ?? this.#location,\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 ...inputPrimaryDenominationProperties,\n ...baseProperties,\n };\n case BatchSellMetricsEventName.BatchSellTokenPageViewed:\n return batchSellBaseProperties;\n case BatchSellMetricsEventName.BatchSellTokenPageContinueClicked: {\n const propsFromClient =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellTokenPageContinueClicked];\n return {\n ...batchSellBaseProperties,\n source_token_count: propsFromClient.source_token_addresses.length,\n source_token_symbols: propsFromClient.source_token_symbols,\n source_token_addresses: propsFromClient.source_token_addresses,\n };\n }\n case BatchSellMetricsEventName.BatchSellQuotePageViewed:\n case BatchSellMetricsEventName.BatchSellQuotePageReviewClicked: {\n const propsFromClient =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellQuotePageViewed];\n return {\n ...batchSellBaseProperties,\n source_token_count: propsFromClient.source_token_addresses.length,\n source_token_symbols: propsFromClient.source_token_symbols,\n source_token_addresses: propsFromClient.source_token_addresses,\n destination_token_symbol: propsFromClient.destination_token_symbol,\n destination_token_address: propsFromClient.destination_token_address,\n usd_amount_source_tokens: propsFromClient.usd_amount_source_tokens,\n usd_amount_source_total: propsFromClient.usd_amount_source_total,\n source_token_slippages: propsFromClient.source_token_slippages,\n };\n }\n case BatchSellMetricsEventName.BatchSellReviewModalSubmitted: {\n const reviewModalProperties =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellReviewModalSubmitted];\n return {\n ...batchSellBaseProperties,\n source_token_count:\n reviewModalProperties.source_token_addresses.length,\n source_token_symbols: reviewModalProperties.source_token_symbols,\n source_token_addresses: reviewModalProperties.source_token_addresses,\n destination_token_symbol:\n reviewModalProperties.destination_token_symbol,\n destination_token_address:\n reviewModalProperties.destination_token_address,\n usd_amount_source_tokens:\n reviewModalProperties.usd_amount_source_tokens,\n usd_amount_source_total:\n reviewModalProperties.usd_amount_source_total,\n source_token_slippages: reviewModalProperties.source_token_slippages,\n usd_quoted_gas: reviewModalProperties.usd_quoted_gas,\n usd_quoted_return: reviewModalProperties.usd_quoted_return,\n };\n }\n case UnifiedSwapBridgeEventName.FiatCryptoToggleClicked:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n swap_type: getSwapTypeFromQuote(quoteRequest),\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 ...inputPrimaryDenominationProperties,\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 ...inputPrimaryDenominationProperties,\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 BridgeControllerMetricsEventName,\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(\n eventName,\n combinedPropertiesForEvent as CrossChainSwapsEventProperties<EventName>,\n );\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,wDAAoD;AACpD,wDAAwD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BAAA,IAAI,4BAAW,MAAM,IAAI,EAAE,MAAA,CAAC;QAC5B,uBAAA,IAAI,2BAAU,OAAO,IAAK,CAAC,CAAC,QAAQ,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAmB,MAAA,CAAC;QACvE,uBAAA,IAAI,oDACF,8BAA8B,IAAI,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,MAAA,CAAC;QAElD,IAAI,CAAC,SAAS,CAAC,4BAA4B,CACzC,IAAI,EACJ,yBAAyB,CAC1B,CAAC;IACJ,CAAC;CAgoCF;AA5uCD,4CA4uCC;+lDA7XG,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 { toQuoteResponseV2 } from './coercers/quote-response-v1-to-v2';\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 BridgeControllerState,\n BridgeControllerMessenger,\n FetchFunction,\n InputPrimaryDenomination,\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 BatchSellMetricsEventName,\n MetaMetricsSwapsEventSource,\n MetricsActionType,\n UnifiedSwapBridgeEventName,\n} from './utils/metrics/constants';\nimport type {\n BridgeControllerMetricsEventName,\n BridgeControllerMetricsLocation,\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 { appendFeesToQuotes } from './utils/quote-fees';\nimport { getMinimumBalanceForRentExemptionInLamports } from './utils/snaps';\nimport { sortQuotes } from './utils/sort-quotes';\nimport type { FeatureId } from './validators/feature-flags';\nimport {\n isValidQuoteRequest,\n isValidBatchSellQuoteRequest,\n} from './validators/quote-request';\nimport type { QuoteResponse } from './validators/quote-response';\nimport type { QuoteResponseV1 } from './validators/quote-response-v1';\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 inputPrimaryDenomination: {\n includeInStateLogs: true,\n persist: true,\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 'getLocation',\n 'setInputPrimaryDenomination',\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: BridgeControllerMetricsLocation =\n MetaMetricsSwapsEventSource.Unknown;\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 BridgeControllerMetricsEventName,\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: <EventName extends BridgeControllerMetricsEventName>(\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<(QuoteResponseV1 & 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 const srcChainIds = Array.from(\n new Set(baseQuotes.map((quote) => quote.quote.srcChainId)),\n ).filter(Boolean);\n\n const quotesWithFees =\n srcChainIds.length > 1 || srcChainIds.length === 0\n ? // Don't append fees if there are multiple srcChainIds\n baseQuotes\n : await appendFeesToQuotes(\n formatChainIdToCaip(srcChainIds[0]),\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 ...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: BridgeControllerMetricsLocation) => {\n this.#location = location;\n };\n\n /**\n * Returns the location/entry point for the current swap or bridge flow.\n *\n * @returns The entry point from which the user initiated the flow\n */\n getLocation = (): BridgeControllerMetricsLocation => {\n return this.#location;\n };\n\n setInputPrimaryDenomination = (\n inputPrimaryDenomination: InputPrimaryDenomination,\n ) => {\n this.update((state) => {\n state.inputPrimaryDenomination = inputPrimaryDenomination;\n });\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.map(toQuoteResponseV2);\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.chainId,\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 BridgeControllerMetricsEventName,\n >(\n eventName: EventName,\n propertiesFromClient: Pick<\n RequiredEventContextFromClient,\n EventName\n >[EventName],\n quoteRequestIndex: number = 0,\n ) => {\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 inputPrimaryDenominationProperties = {\n input_primary_denomination: this.state.inputPrimaryDenomination,\n };\n const batchSellClientChainProperties = propertiesFromClient as Pick<\n RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellTokenPageViewed],\n 'chain_id_source' | 'chain_id_destination'\n >;\n const batchSellBaseProperties = {\n chain_id_source: batchSellClientChainProperties.chain_id_source,\n chain_id_destination: batchSellClientChainProperties.chain_id_destination,\n location: clientProps?.location ?? this.#location,\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 ...inputPrimaryDenominationProperties,\n ...baseProperties,\n };\n case BatchSellMetricsEventName.BatchSellTokenPageViewed:\n return batchSellBaseProperties;\n case BatchSellMetricsEventName.BatchSellTokenPageContinueClicked: {\n const propsFromClient =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellTokenPageContinueClicked];\n return {\n ...batchSellBaseProperties,\n source_token_count: propsFromClient.source_token_addresses.length,\n source_token_symbols: propsFromClient.source_token_symbols,\n source_token_addresses: propsFromClient.source_token_addresses,\n };\n }\n case BatchSellMetricsEventName.BatchSellQuotePageViewed:\n case BatchSellMetricsEventName.BatchSellQuotePageReviewClicked: {\n const propsFromClient =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellQuotePageViewed];\n return {\n ...batchSellBaseProperties,\n source_token_count: propsFromClient.source_token_addresses.length,\n source_token_symbols: propsFromClient.source_token_symbols,\n source_token_addresses: propsFromClient.source_token_addresses,\n destination_token_symbol: propsFromClient.destination_token_symbol,\n destination_token_address: propsFromClient.destination_token_address,\n usd_amount_source_tokens: propsFromClient.usd_amount_source_tokens,\n usd_amount_source_total: propsFromClient.usd_amount_source_total,\n source_token_slippages: propsFromClient.source_token_slippages,\n };\n }\n case BatchSellMetricsEventName.BatchSellReviewModalSubmitted: {\n const reviewModalProperties =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellReviewModalSubmitted];\n return {\n ...batchSellBaseProperties,\n source_token_count:\n reviewModalProperties.source_token_addresses.length,\n source_token_symbols: reviewModalProperties.source_token_symbols,\n source_token_addresses: reviewModalProperties.source_token_addresses,\n destination_token_symbol:\n reviewModalProperties.destination_token_symbol,\n destination_token_address:\n reviewModalProperties.destination_token_address,\n usd_amount_source_tokens:\n reviewModalProperties.usd_amount_source_tokens,\n usd_amount_source_total:\n reviewModalProperties.usd_amount_source_total,\n source_token_slippages: reviewModalProperties.source_token_slippages,\n usd_quoted_gas: reviewModalProperties.usd_quoted_gas,\n usd_quoted_return: reviewModalProperties.usd_quoted_return,\n };\n }\n case UnifiedSwapBridgeEventName.FiatCryptoToggleClicked:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n swap_type: getSwapTypeFromQuote(quoteRequest),\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 ...inputPrimaryDenominationProperties,\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 ...inputPrimaryDenominationProperties,\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 BridgeControllerMetricsEventName,\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(\n eventName,\n combinedPropertiesForEvent as CrossChainSwapsEventProperties<EventName>,\n );\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"]}
@@ -8,6 +8,7 @@ import type { BridgeControllerMetricsEventName, BridgeControllerMetricsLocation
8
8
  import type { RequiredEventContextFromClient } from "./utils/metrics/types.cjs";
9
9
  import type { CrossChainSwapsEventProperties } from "./utils/metrics/types.cjs";
10
10
  import type { FeatureId } from "./validators/feature-flags.cjs";
11
+ import type { QuoteResponse } from "./validators/quote-response.cjs";
11
12
  import type { QuoteResponseV1 } from "./validators/quote-response-v1.cjs";
12
13
  /**
13
14
  * The input to start polling for the {@link BridgeController}
@@ -87,7 +88,7 @@ export declare class BridgeController extends BridgeController_base<typeof BRIDG
87
88
  * @param quotes - The quotes to fetch the gasless transaction data and fees for
88
89
  * @param stxEnabled - Flag to estimate gas cost more precisely for the batch sell feature.
89
90
  */
90
- updateBatchSellTrades: (quotes: (QuoteResponseV1 | null)[], stxEnabled: boolean) => Promise<void>;
91
+ updateBatchSellTrades: (quotes: (QuoteResponse | null)[], stxEnabled: boolean) => Promise<void>;
91
92
  stopPollingForQuotes: (reason?: AbortReason, context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived]) => void;
92
93
  /**
93
94
  * Sets the location/entry point for the current swap or bridge flow.
@@ -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,qBAAqB,EACrB,yBAAyB,EACzB,aAAa,EACb,wBAAwB,EACzB,oBAAgB;AAyBjB,OAAO,EACL,WAAW,EAIX,0BAA0B,EAC3B,sCAAkC;AACnC,OAAO,KAAK,EACV,gCAAgC,EAChC,+BAA+B,EAChC,sCAAkC;AAUnC,OAAO,KAAK,EAGV,8BAA8B,EAC/B,kCAA8B;AAC/B,OAAO,KAAK,EAAE,8BAA8B,EAAE,kCAA8B;AAI5E,OAAO,KAAK,EAAE,SAAS,EAAE,uCAAmC;AAK5D,OAAO,KAAK,EAAE,eAAe,EAAE,2CAAuC;AA+FtE;;;;;;GAMG;AACH,KAAK,kBAA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AmB,CAAC,GAAG;QAC7C,aAAa,EAAE,mBAAmB,CAAC,eAAe,CAAC,CAAC;KACrD,WACQ,kBAAkB,CAAC,SAAS,CAAC,sBACnB,MAAM,sBACN,MAAM,mBAgDzB;IAEF;;;;;;;;OAQG;IACH,WAAW,iBACK,mBAAmB,aACtB,SAAS,gBACP,WAAW,GAAG,IAAI,KAC9B,QAAQ,CAAC,eAAe,GAAG,SAAS,GAAG,UAAU,CAAC,EAAE,CAAC,CAyCtD;IAEF;;;;;;;OAOG;IACH,qBAAqB,WACX,CAAC,aAAa,GAAG,IAAI,CAAC,EAAE,cACpB,OAAO,KAClB,QAAQ,IAAI,CAAC,CAsDd;IA2LF,oBAAoB,YACT,WAAW,YACV,8BAA8B,CAAC,2BAA2B,cAAc,CAAC,UAanF;IAEF;;;;;;OAMG;IACH,WAAW,aAAc,+BAA+B,UAEtD;IAEF;;;;OAIG;IACH,WAAW,QAAO,+BAA+B,CAE/C;IAEF,2BAA2B,6BACC,wBAAwB,UAKlD;IAEF,UAAU,6CAEW,MAAM,GAAG,IAAI,YACtB,8BAA8B,CAAC,2BAA2B,cAAc,CAAC,UAsCnF;IAEF;;OAEG;IACH,sBAAsB,aAYpB;IAylBF;;;;;;;;;;OAUG;IACH,2BAA2B,mLAQN,MAAM,UAmBzB;CA+BH"}
@@ -8,6 +8,7 @@ import type { BridgeControllerMetricsEventName, BridgeControllerMetricsLocation
8
8
  import type { RequiredEventContextFromClient } from "./utils/metrics/types.mjs";
9
9
  import type { CrossChainSwapsEventProperties } from "./utils/metrics/types.mjs";
10
10
  import type { FeatureId } from "./validators/feature-flags.mjs";
11
+ import type { QuoteResponse } from "./validators/quote-response.mjs";
11
12
  import type { QuoteResponseV1 } from "./validators/quote-response-v1.mjs";
12
13
  /**
13
14
  * The input to start polling for the {@link BridgeController}
@@ -87,7 +88,7 @@ export declare class BridgeController extends BridgeController_base<typeof BRIDG
87
88
  * @param quotes - The quotes to fetch the gasless transaction data and fees for
88
89
  * @param stxEnabled - Flag to estimate gas cost more precisely for the batch sell feature.
89
90
  */
90
- updateBatchSellTrades: (quotes: (QuoteResponseV1 | null)[], stxEnabled: boolean) => Promise<void>;
91
+ updateBatchSellTrades: (quotes: (QuoteResponse | null)[], stxEnabled: boolean) => Promise<void>;
91
92
  stopPollingForQuotes: (reason?: AbortReason, context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived]) => void;
92
93
  /**
93
94
  * Sets the location/entry point for the current swap or bridge flow.
@@ -1 +1 @@
1
- {"version":3,"file":"bridge-controller.d.mts","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,qBAAqB,EACrB,yBAAyB,EACzB,aAAa,EACb,wBAAwB,EACzB,oBAAgB;AAyBjB,OAAO,EACL,WAAW,EAIX,0BAA0B,EAC3B,sCAAkC;AACnC,OAAO,KAAK,EACV,gCAAgC,EAChC,+BAA+B,EAChC,sCAAkC;AAUnC,OAAO,KAAK,EAGV,8BAA8B,EAC/B,kCAA8B;AAC/B,OAAO,KAAK,EAAE,8BAA8B,EAAE,kCAA8B;AAI5E,OAAO,KAAK,EAAE,SAAS,EAAE,uCAAmC;AAK5D,OAAO,KAAK,EAAE,eAAe,EAAE,2CAAuC;AA+FtE;;;;;;GAMG;AACH,KAAK,kBAAkB,GAAG;IACxB,aAAa,EAAE,mBAAmB,EAAE,CAAC;IACrC,OAAO,EAAE,8BAA8B,CAAC,0BAA0B,CAAC,WAAW,CAAC,GAC7E,8BAA8B,CAAC,0BAA0B,CAAC,eAAe,CAAC,CAAC;CAC9E,CAAC;;;;;;;;;;;;;;;;AA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AAS,gBACP,WAAW,GAAG,IAAI,KAC9B,QAAQ,CAAC,eAAe,GAAG,SAAS,GAAG,UAAU,CAAC,EAAE,CAAC,CAyCtD;IAEF;;;;;;;OAOG;IACH,qBAAqB,WACX,CAAC,aAAa,GAAG,IAAI,CAAC,EAAE,cACpB,OAAO,KAClB,QAAQ,IAAI,CAAC,CAsDd;IA2LF,oBAAoB,YACT,WAAW,YACV,8BAA8B,CAAC,2BAA2B,cAAc,CAAC,UAanF;IAEF;;;;;;OAMG;IACH,WAAW,aAAc,+BAA+B,UAEtD;IAEF;;;;OAIG;IACH,WAAW,QAAO,+BAA+B,CAE/C;IAEF,2BAA2B,6BACC,wBAAwB,UAKlD;IAEF,UAAU,6CAEW,MAAM,GAAG,IAAI,YACtB,8BAA8B,CAAC,2BAA2B,cAAc,CAAC,UAsCnF;IAEF;;OAEG;IACH,sBAAsB,aAYpB;IAylBF;;;;;;;;;;OAUG;IACH,2BAA2B,mLAQN,MAAM,UAmBzB;CA+BH"}
@@ -16,6 +16,7 @@ import { Contract } from "@ethersproject/contracts";
16
16
  import { Web3Provider } from "@ethersproject/providers";
17
17
  import { abiERC20 } from "@metamask/metamask-eth-abis";
18
18
  import { StaticIntervalPollingController } from "@metamask/polling-controller";
19
+ import { toQuoteResponseV2 } from "./coercers/quote-response-v1-to-v2.mjs";
19
20
  import { BRIDGE_CONTROLLER_NAME, BRIDGE_PROD_API_BASE_URL, DEFAULT_BRIDGE_CONTROLLER_STATE, METABRIDGE_ETHEREUM_ADDRESS, REFRESH_INTERVAL_MS } from "./constants/bridge.mjs";
20
21
  import { CHAIN_IDS } from "./constants/chains.mjs";
21
22
  import { SWAPS_CONTRACT_ADDRESSES } from "./constants/swaps.mjs";
@@ -244,7 +245,11 @@ export class BridgeController extends StaticIntervalPollingController() {
244
245
  ? { ...quoteRequest, ...quoteRequestOverrides, resetApproval }
245
246
  : { ...quoteRequest, resetApproval }, abortSignal, __classPrivateFieldGet(this, _BridgeController_clientId, "f"), jwt, __classPrivateFieldGet(this, _BridgeController_fetchFn, "f"), __classPrivateFieldGet(this, _BridgeController_config, "f").customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL, featureId, __classPrivateFieldGet(this, _BridgeController_clientVersion, "f"));
246
247
  __classPrivateFieldGet(this, _BridgeController_trackQuoteValidationFailures, "f").call(this, validationFailures, featureId);
247
- const quotesWithFees = await appendFeesToQuotes(baseQuotes, this.messenger, __classPrivateFieldGet(this, _BridgeController_getLayer1GasFee, "f"), __classPrivateFieldGet(this, _BridgeController_instances, "m", _BridgeController_getMultichainSelectedAccount).call(this, quoteRequest.walletAddress));
248
+ const srcChainIds = Array.from(new Set(baseQuotes.map((quote) => quote.quote.srcChainId))).filter(Boolean);
249
+ const quotesWithFees = srcChainIds.length > 1 || srcChainIds.length === 0
250
+ ? // Don't append fees if there are multiple srcChainIds
251
+ baseQuotes
252
+ : await appendFeesToQuotes(formatChainIdToCaip(srcChainIds[0]), baseQuotes, this.messenger, __classPrivateFieldGet(this, _BridgeController_getLayer1GasFee, "f"), __classPrivateFieldGet(this, _BridgeController_instances, "m", _BridgeController_getMultichainSelectedAccount).call(this, quoteRequest.walletAddress));
248
253
  return sortQuotes(quotesWithFees, featureId);
249
254
  };
250
255
  /**
@@ -567,7 +572,7 @@ export class BridgeController extends StaticIntervalPollingController() {
567
572
  state.quotesInitialLoadTime =
568
573
  Date.now() - __classPrivateFieldGet(this, _BridgeController_quotesFirstFetched, "f");
569
574
  }
570
- state.quotes = quotes;
575
+ state.quotes = quotes.map(toQuoteResponseV2);
571
576
  state.quotesLoadingStatus = RequestStatus.FETCHED;
572
577
  });
573
578
  });
@@ -639,7 +644,7 @@ export class BridgeController extends StaticIntervalPollingController() {
639
644
  onQuoteValidationFailure: (validationFailures) => __classPrivateFieldGet(this, _BridgeController_trackQuoteValidationFailures, "f").call(this, validationFailures, featureId),
640
645
  onValidQuoteReceived: async (quote) => {
641
646
  const feeAppendPromise = (async () => {
642
- const quotesWithFees = await appendFeesToQuotes([quote], this.messenger, __classPrivateFieldGet(this, _BridgeController_getLayer1GasFee, "f"), selectedAccount);
647
+ const quotesWithFees = await appendFeesToQuotes(quote.chainId, [quote], this.messenger, __classPrivateFieldGet(this, _BridgeController_getLayer1GasFee, "f"), selectedAccount);
643
648
  if (quotesWithFees.length > 0) {
644
649
  validQuotesCounter += 1;
645
650
  }