@metamask-previews/bridge-controller 77.6.0-preview-68ba7f84e → 77.8.0-preview-5959fe813

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 (246) hide show
  1. package/CHANGELOG.md +42 -7
  2. package/dist/bridge-controller.cjs +13 -8
  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 +10 -5
  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/constants/bridge.cjs +2 -1
  27. package/dist/constants/bridge.cjs.map +1 -1
  28. package/dist/constants/bridge.d.cts +1 -0
  29. package/dist/constants/bridge.d.cts.map +1 -1
  30. package/dist/constants/bridge.d.mts +1 -0
  31. package/dist/constants/bridge.d.mts.map +1 -1
  32. package/dist/constants/bridge.mjs +1 -0
  33. package/dist/constants/bridge.mjs.map +1 -1
  34. package/dist/index.cjs +32 -7
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +17 -5
  37. package/dist/index.d.cts.map +1 -1
  38. package/dist/index.d.mts +17 -5
  39. package/dist/index.d.mts.map +1 -1
  40. package/dist/index.mjs +12 -3
  41. package/dist/index.mjs.map +1 -1
  42. package/dist/selectors.cjs +52 -100
  43. package/dist/selectors.cjs.map +1 -1
  44. package/dist/selectors.d.cts +11198 -31552
  45. package/dist/selectors.d.cts.map +1 -1
  46. package/dist/selectors.d.mts +11198 -31552
  47. package/dist/selectors.d.mts.map +1 -1
  48. package/dist/selectors.mjs +52 -100
  49. package/dist/selectors.mjs.map +1 -1
  50. package/dist/types.cjs.map +1 -1
  51. package/dist/types.d.cts +4 -87
  52. package/dist/types.d.cts.map +1 -1
  53. package/dist/types.d.mts +4 -87
  54. package/dist/types.d.mts.map +1 -1
  55. package/dist/types.mjs.map +1 -1
  56. package/dist/utils/bridge.cjs +2 -6
  57. package/dist/utils/bridge.cjs.map +1 -1
  58. package/dist/utils/bridge.d.cts +2 -19
  59. package/dist/utils/bridge.d.cts.map +1 -1
  60. package/dist/utils/bridge.d.mts +2 -19
  61. package/dist/utils/bridge.d.mts.map +1 -1
  62. package/dist/utils/bridge.mjs +1 -4
  63. package/dist/utils/bridge.mjs.map +1 -1
  64. package/dist/utils/caip-formatters.cjs +0 -3
  65. package/dist/utils/caip-formatters.cjs.map +1 -1
  66. package/dist/utils/caip-formatters.d.cts.map +1 -1
  67. package/dist/utils/caip-formatters.d.mts.map +1 -1
  68. package/dist/utils/caip-formatters.mjs +0 -3
  69. package/dist/utils/caip-formatters.mjs.map +1 -1
  70. package/dist/utils/feature-flags.d.cts +2 -2
  71. package/dist/utils/feature-flags.d.mts +2 -2
  72. package/dist/utils/fetch.cjs +37 -40
  73. package/dist/utils/fetch.cjs.map +1 -1
  74. package/dist/utils/fetch.d.cts +10 -4
  75. package/dist/utils/fetch.d.cts.map +1 -1
  76. package/dist/utils/fetch.d.mts +10 -4
  77. package/dist/utils/fetch.d.mts.map +1 -1
  78. package/dist/utils/fetch.mjs +37 -40
  79. package/dist/utils/fetch.mjs.map +1 -1
  80. package/dist/utils/metrics/constants.cjs +1 -0
  81. package/dist/utils/metrics/constants.cjs.map +1 -1
  82. package/dist/utils/metrics/constants.d.cts +2 -1
  83. package/dist/utils/metrics/constants.d.cts.map +1 -1
  84. package/dist/utils/metrics/constants.d.mts +2 -1
  85. package/dist/utils/metrics/constants.d.mts.map +1 -1
  86. package/dist/utils/metrics/constants.mjs +1 -0
  87. package/dist/utils/metrics/constants.mjs.map +1 -1
  88. package/dist/utils/metrics/properties.cjs +6 -6
  89. package/dist/utils/metrics/properties.cjs.map +1 -1
  90. package/dist/utils/metrics/properties.d.cts +9 -5
  91. package/dist/utils/metrics/properties.d.cts.map +1 -1
  92. package/dist/utils/metrics/properties.d.mts +9 -5
  93. package/dist/utils/metrics/properties.d.mts.map +1 -1
  94. package/dist/utils/metrics/properties.mjs +6 -6
  95. package/dist/utils/metrics/properties.mjs.map +1 -1
  96. package/dist/utils/metrics/types.cjs.map +1 -1
  97. package/dist/utils/metrics/types.d.cts +1 -1
  98. package/dist/utils/metrics/types.d.cts.map +1 -1
  99. package/dist/utils/metrics/types.d.mts +1 -1
  100. package/dist/utils/metrics/types.d.mts.map +1 -1
  101. package/dist/utils/metrics/types.mjs.map +1 -1
  102. package/dist/utils/number-formatters.cjs +106 -0
  103. package/dist/utils/number-formatters.cjs.map +1 -0
  104. package/dist/utils/number-formatters.d.cts +34 -0
  105. package/dist/utils/number-formatters.d.cts.map +1 -0
  106. package/dist/utils/number-formatters.d.mts +34 -0
  107. package/dist/utils/number-formatters.d.mts.map +1 -0
  108. package/dist/utils/number-formatters.mjs +99 -0
  109. package/dist/utils/number-formatters.mjs.map +1 -0
  110. package/dist/utils/quote-fees.cjs +23 -22
  111. package/dist/utils/quote-fees.cjs.map +1 -1
  112. package/dist/utils/quote-fees.d.cts +4 -2
  113. package/dist/utils/quote-fees.d.cts.map +1 -1
  114. package/dist/utils/quote-fees.d.mts +4 -2
  115. package/dist/utils/quote-fees.d.mts.map +1 -1
  116. package/dist/utils/quote-fees.mjs +24 -23
  117. package/dist/utils/quote-fees.mjs.map +1 -1
  118. package/dist/utils/quote-metadata/calculators.cjs +340 -0
  119. package/dist/utils/quote-metadata/calculators.cjs.map +1 -0
  120. package/dist/utils/quote-metadata/calculators.d.cts +125 -0
  121. package/dist/utils/quote-metadata/calculators.d.cts.map +1 -0
  122. package/dist/utils/quote-metadata/calculators.d.mts +125 -0
  123. package/dist/utils/quote-metadata/calculators.d.mts.map +1 -0
  124. package/dist/utils/quote-metadata/calculators.mjs +323 -0
  125. package/dist/utils/quote-metadata/calculators.mjs.map +1 -0
  126. package/dist/utils/quote-metadata/merge.cjs +38 -0
  127. package/dist/utils/quote-metadata/merge.cjs.map +1 -0
  128. package/dist/utils/quote-metadata/merge.d.cts +12 -0
  129. package/dist/utils/quote-metadata/merge.d.cts.map +1 -0
  130. package/dist/utils/quote-metadata/merge.d.mts +12 -0
  131. package/dist/utils/quote-metadata/merge.d.mts.map +1 -0
  132. package/dist/utils/quote-metadata/merge.mjs +35 -0
  133. package/dist/utils/quote-metadata/merge.mjs.map +1 -0
  134. package/dist/utils/quote-metadata/to-normalized-amounts.cjs +38 -0
  135. package/dist/utils/quote-metadata/to-normalized-amounts.cjs.map +1 -0
  136. package/dist/utils/quote-metadata/to-normalized-amounts.d.cts +10 -0
  137. package/dist/utils/quote-metadata/to-normalized-amounts.d.cts.map +1 -0
  138. package/dist/utils/quote-metadata/to-normalized-amounts.d.mts +10 -0
  139. package/dist/utils/quote-metadata/to-normalized-amounts.d.mts.map +1 -0
  140. package/dist/utils/quote-metadata/to-normalized-amounts.mjs +34 -0
  141. package/dist/utils/quote-metadata/to-normalized-amounts.mjs.map +1 -0
  142. package/dist/utils/quote-metadata/to-quote-metadata-v1.cjs +39 -0
  143. package/dist/utils/quote-metadata/to-quote-metadata-v1.cjs.map +1 -0
  144. package/dist/utils/quote-metadata/to-quote-metadata-v1.d.cts +13 -0
  145. package/dist/utils/quote-metadata/to-quote-metadata-v1.d.cts.map +1 -0
  146. package/dist/utils/quote-metadata/to-quote-metadata-v1.d.mts +13 -0
  147. package/dist/utils/quote-metadata/to-quote-metadata-v1.d.mts.map +1 -0
  148. package/dist/utils/quote-metadata/to-quote-metadata-v1.mjs +36 -0
  149. package/dist/utils/quote-metadata/to-quote-metadata-v1.mjs.map +1 -0
  150. package/dist/utils/quote-metadata/to-quote-metadata-v2.cjs +94 -0
  151. package/dist/utils/quote-metadata/to-quote-metadata-v2.cjs.map +1 -0
  152. package/dist/utils/quote-metadata/to-quote-metadata-v2.d.cts +12 -0
  153. package/dist/utils/quote-metadata/to-quote-metadata-v2.d.cts.map +1 -0
  154. package/dist/utils/quote-metadata/to-quote-metadata-v2.d.mts +12 -0
  155. package/dist/utils/quote-metadata/to-quote-metadata-v2.d.mts.map +1 -0
  156. package/dist/utils/quote-metadata/to-quote-metadata-v2.mjs +90 -0
  157. package/dist/utils/quote-metadata/to-quote-metadata-v2.mjs.map +1 -0
  158. package/dist/utils/quote-metadata/types.cjs +3 -0
  159. package/dist/utils/quote-metadata/types.cjs.map +1 -0
  160. package/dist/utils/quote-metadata/types.d.cts +87 -0
  161. package/dist/utils/quote-metadata/types.d.cts.map +1 -0
  162. package/dist/utils/quote-metadata/types.d.mts +87 -0
  163. package/dist/utils/quote-metadata/types.d.mts.map +1 -0
  164. package/dist/utils/quote-metadata/types.mjs +2 -0
  165. package/dist/utils/quote-metadata/types.mjs.map +1 -0
  166. package/dist/utils/slippage.d.cts +1 -1
  167. package/dist/utils/slippage.d.mts +1 -1
  168. package/dist/utils/sort-quotes.cjs +16 -0
  169. package/dist/utils/sort-quotes.cjs.map +1 -0
  170. package/dist/utils/sort-quotes.d.cts +4 -0
  171. package/dist/utils/sort-quotes.d.cts.map +1 -0
  172. package/dist/utils/sort-quotes.d.mts +4 -0
  173. package/dist/utils/sort-quotes.d.mts.map +1 -0
  174. package/dist/utils/sort-quotes.mjs +12 -0
  175. package/dist/utils/sort-quotes.mjs.map +1 -0
  176. package/dist/validators/amount-and-asset.cjs +27 -0
  177. package/dist/validators/amount-and-asset.cjs.map +1 -0
  178. package/dist/validators/amount-and-asset.d.cts +62 -0
  179. package/dist/validators/amount-and-asset.d.cts.map +1 -0
  180. package/dist/validators/amount-and-asset.d.mts +62 -0
  181. package/dist/validators/amount-and-asset.d.mts.map +1 -0
  182. package/dist/validators/amount-and-asset.mjs +24 -0
  183. package/dist/validators/amount-and-asset.mjs.map +1 -0
  184. package/dist/validators/batch-sell.d.cts +8 -8
  185. package/dist/validators/batch-sell.d.mts +8 -8
  186. package/dist/validators/bridge-asset.cjs +65 -1
  187. package/dist/validators/bridge-asset.cjs.map +1 -1
  188. package/dist/validators/bridge-asset.d.cts +99 -5
  189. package/dist/validators/bridge-asset.d.cts.map +1 -1
  190. package/dist/validators/bridge-asset.d.mts +99 -5
  191. package/dist/validators/bridge-asset.d.mts.map +1 -1
  192. package/dist/validators/bridge-asset.mjs +64 -1
  193. package/dist/validators/bridge-asset.mjs.map +1 -1
  194. package/dist/validators/feature-flags.d.cts +5 -5
  195. package/dist/validators/feature-flags.d.mts +5 -5
  196. package/dist/validators/intent.d.cts +3 -3
  197. package/dist/validators/intent.d.mts +3 -3
  198. package/dist/validators/quote-request.cjs +57 -0
  199. package/dist/validators/quote-request.cjs.map +1 -0
  200. package/dist/validators/quote-request.d.cts +4 -0
  201. package/dist/validators/quote-request.d.cts.map +1 -0
  202. package/dist/validators/quote-request.d.mts +4 -0
  203. package/dist/validators/quote-request.d.mts.map +1 -0
  204. package/dist/validators/quote-request.mjs +52 -0
  205. package/dist/validators/quote-request.mjs.map +1 -0
  206. package/dist/validators/quote-response-v1.d.cts +179 -176
  207. package/dist/validators/quote-response-v1.d.cts.map +1 -1
  208. package/dist/validators/quote-response-v1.d.mts +179 -176
  209. package/dist/validators/quote-response-v1.d.mts.map +1 -1
  210. package/dist/validators/quote-response.cjs +116 -0
  211. package/dist/validators/quote-response.cjs.map +1 -0
  212. package/dist/validators/quote-response.d.cts +1979 -0
  213. package/dist/validators/quote-response.d.cts.map +1 -0
  214. package/dist/validators/quote-response.d.mts +1979 -0
  215. package/dist/validators/quote-response.d.mts.map +1 -0
  216. package/dist/validators/quote-response.mjs +112 -0
  217. package/dist/validators/quote-response.mjs.map +1 -0
  218. package/dist/validators/quote.cjs +75 -2
  219. package/dist/validators/quote.cjs.map +1 -1
  220. package/dist/validators/quote.d.cts +407 -44
  221. package/dist/validators/quote.d.cts.map +1 -1
  222. package/dist/validators/quote.d.mts +407 -44
  223. package/dist/validators/quote.d.mts.map +1 -1
  224. package/dist/validators/quote.mjs +76 -3
  225. package/dist/validators/quote.mjs.map +1 -1
  226. package/dist/validators/step.cjs +7 -1
  227. package/dist/validators/step.cjs.map +1 -1
  228. package/dist/validators/step.d.cts +197 -26
  229. package/dist/validators/step.d.cts.map +1 -1
  230. package/dist/validators/step.d.mts +197 -26
  231. package/dist/validators/step.d.mts.map +1 -1
  232. package/dist/validators/step.mjs +7 -1
  233. package/dist/validators/step.mjs.map +1 -1
  234. package/dist/validators/token-feature.d.cts +2 -2
  235. package/dist/validators/token-feature.d.mts +2 -2
  236. package/dist/validators/trade.d.cts +2 -2
  237. package/dist/validators/trade.d.mts +2 -2
  238. package/package.json +8 -8
  239. package/dist/utils/quote.cjs +0 -368
  240. package/dist/utils/quote.cjs.map +0 -1
  241. package/dist/utils/quote.d.cts +0 -98
  242. package/dist/utils/quote.d.cts.map +0 -1
  243. package/dist/utils/quote.d.mts +0 -98
  244. package/dist/utils/quote.d.mts.map +0 -1
  245. package/dist/utils/quote.mjs +0 -347
  246. package/dist/utils/quote.mjs.map +0 -1
@@ -12,7 +12,10 @@ const types_1 = require("./types.cjs");
12
12
  const bridge_2 = require("./utils/bridge.cjs");
13
13
  const caip_formatters_1 = require("./utils/caip-formatters.cjs");
14
14
  const feature_flags_1 = require("./utils/feature-flags.cjs");
15
- const quote_1 = require("./utils/quote.cjs");
15
+ const number_formatters_1 = require("./utils/number-formatters.cjs");
16
+ const calculators_1 = require("./utils/quote-metadata/calculators.cjs");
17
+ const calculators_2 = require("./utils/quote-metadata/calculators.cjs");
18
+ const merge_1 = require("./utils/quote-metadata/merge.cjs");
16
19
  const slippage_1 = require("./utils/slippage.cjs");
17
20
  /**
18
21
  * Creates a structured selector for the bridge controller
@@ -169,7 +172,7 @@ exports.selectIsAssetExchangeRateInState = selectIsAssetExchangeRateInState;
169
172
  */
170
173
  const selectBridgeFeesPerGas = createBridgeSelector([
171
174
  (state) => state.gasFeeEstimatesByChainId,
172
- (state) => state.quotes?.[0]?.quote.srcChainId,
175
+ (state) => state.quotes?.[0]?.chainId,
173
176
  ], (gasFeeEstimatesByChainId, srcChainId) => {
174
177
  if (!srcChainId) {
175
178
  return null;
@@ -188,82 +191,29 @@ const selectBridgeFeesPerGas = createBridgeSelector([
188
191
  maxFeePerGasInDecGwei: gasFeeEstimates.high?.suggestedMaxFeePerGas,
189
192
  };
190
193
  });
191
- // Selects cross-chain swap quotes including their metadata
192
- const selectBridgeQuotesWithMetadata = createBridgeSelector([
194
+ const selectExchangeRateSources = createStructuredBridgeSelector({
195
+ currencyRates: (state) => state.currencyRates,
196
+ marketData: (state) => state.marketData,
197
+ conversionRates: (state) => state.conversionRates,
198
+ assetExchangeRates: (state) => state.assetExchangeRates,
199
+ });
200
+ // Selects metadata for cross-chain swap quotes
201
+ const selectMetadata = createBridgeSelector([
193
202
  ({ quotes }) => quotes,
194
203
  selectBridgeFeesPerGas,
195
- (state) => state,
196
- createBridgeSelector([
197
- (state) => state,
198
- ({ quoteRequest: [{ destChainId, destTokenAddress }] }) => destTokenAddress
199
- ? (0, caip_formatters_1.formatAddressToAssetId)(destTokenAddress, destChainId)
200
- : undefined,
201
- ], exports.selectExchangeRateByAssetId),
202
- createBridgeSelector([
203
- (state) => state,
204
- ({ quoteRequest: [{ srcChainId }] }) => srcChainId
205
- ? (0, bridge_2.getNativeAssetForChainId)(srcChainId)?.assetId
206
- : undefined,
207
- ], exports.selectExchangeRateByAssetId),
208
- ], (quotes, bridgeFeesPerGas, exchangeRateSources, destTokenExchangeRate, nativeExchangeRate) => {
209
- const newQuotes = quotes.map((quote) => {
210
- const sourceAssetId = (0, caip_formatters_1.formatAddressToAssetId)(quote.quote.srcAsset.address, quote.quote.srcChainId) ?? quote.quote.srcAsset.assetId;
211
- const srcTokenExchangeRate = (0, exports.selectExchangeRateByAssetId)(exchangeRateSources, sourceAssetId);
212
- const sentAmount = (0, quote_1.calcSentAmount)(quote.quote, srcTokenExchangeRate);
213
- const toTokenAmount = (0, quote_1.calcToAmount)(quote.quote.destTokenAmount, quote.quote.destAsset, destTokenExchangeRate);
214
- const minToTokenAmount = (0, quote_1.calcToAmount)(quote.quote.minDestTokenAmount, quote.quote.destAsset, destTokenExchangeRate);
215
- const includedTxFees = (0, quote_1.calcIncludedTxFees)(quote.quote, srcTokenExchangeRate, destTokenExchangeRate);
216
- let totalEstimatedNetworkFee, totalMaxNetworkFee, relayerFee, gasFee;
217
- if ((0, bridge_2.isEvmQuoteResponse)(quote)) {
218
- relayerFee = (0, quote_1.calcRelayerFee)(quote, nativeExchangeRate);
219
- gasFee = (0, quote_1.calcEstimatedAndMaxTotalGasFee)({
220
- bridgeQuote: quote,
221
- ...bridgeFeesPerGas,
222
- ...nativeExchangeRate,
223
- });
224
- // Uses effectiveGasFee to calculate the total estimated network fee
225
- totalEstimatedNetworkFee = (0, quote_1.calcTotalEstimatedNetworkFee)(gasFee, relayerFee);
226
- totalMaxNetworkFee = (0, quote_1.calcTotalMaxNetworkFee)(gasFee, relayerFee);
227
- }
228
- else {
229
- // Use the new generic function for all non-EVM chains
230
- totalEstimatedNetworkFee = (0, quote_1.calcNonEvmTotalNetworkFee)(quote, nativeExchangeRate);
231
- gasFee = {
232
- effective: totalEstimatedNetworkFee,
233
- total: totalEstimatedNetworkFee,
234
- max: totalEstimatedNetworkFee,
235
- };
236
- totalMaxNetworkFee = totalEstimatedNetworkFee;
237
- }
238
- const adjustedReturn = (0, quote_1.calcAdjustedReturn)(toTokenAmount, totalEstimatedNetworkFee, quote.quote);
239
- const cost = (0, quote_1.calcCost)(adjustedReturn, sentAmount);
240
- return {
241
- ...quote,
242
- // QuoteMetadata fields
243
- sentAmount,
244
- toTokenAmount,
245
- minToTokenAmount,
246
- swapRate: (0, quote_1.calcSwapRate)(sentAmount.amount, toTokenAmount.amount),
247
- /**
248
- This is the amount required to submit all the transactions.
249
- Includes the relayer fee or other native fees.
250
- Should be used for balance checks and tx submission.
251
- */
252
- totalNetworkFee: totalEstimatedNetworkFee,
253
- totalMaxNetworkFee,
254
- /**
255
- This contains gas fee estimates for the bridge transaction
256
- Does not include the relayer fee (if needed), just the gasLimit and effectiveGas returned by the bridge API.
257
- Should only be used for display purposes.
258
- */
259
- gasFee,
260
- adjustedReturn,
261
- cost,
262
- includedTxFees,
263
- };
264
- });
265
- return newQuotes;
204
+ selectExchangeRateSources,
205
+ ({ quoteRequest }) => quoteRequest,
206
+ ], (quotes, bridgeFeesPerGas, exchangeRateSources, quoteRequest) => {
207
+ const { destTokenAddress, srcChainId, destChainId } = quoteRequest[0] ?? {};
208
+ return quotes.map((quote) => (0, calculators_2.calcQuoteMetadata)(quote, {
209
+ srcTokenExchangeRate: (0, exports.selectExchangeRateByAssetId)(exchangeRateSources, quote.quote.src.asset.assetId),
210
+ bridgeFeesPerGas,
211
+ destTokenExchangeRate: (0, exports.selectExchangeRateByAssetId)(exchangeRateSources, (0, caip_formatters_1.formatAddressToAssetId)(destTokenAddress ?? quote.quote.dest.asset.assetId, destChainId)),
212
+ nativeExchangeRate: (0, exports.selectExchangeRateByAssetId)(exchangeRateSources, (0, bridge_2.getNativeAssetForChainId)(srcChainId ?? quote.chainId)?.assetId),
213
+ }));
266
214
  });
215
+ // Selects cross-chain swap quotes including their metadata
216
+ const selectBridgeQuotesWithMetadata = createBridgeSelector([selectMetadata, ({ quotes }) => quotes], (quoteMetadata, quotes) => quotes.map((quote, index) => (0, merge_1.mergeQuoteMetadata)(quote, quoteMetadata[index])));
267
217
  const selectSortedBridgeQuotes = createBridgeSelector([
268
218
  selectBridgeQuotesWithMetadata,
269
219
  (_, { sortOrder }) => sortOrder,
@@ -272,21 +222,22 @@ const selectSortedBridgeQuotes = createBridgeSelector([
272
222
  case types_1.SortOrder.ETA_ASC:
273
223
  return (0, lodash_1.orderBy)(quotesWithMetadata, (quote) => quote.estimatedProcessingTimeInSeconds, 'asc');
274
224
  default:
275
- if (quotesWithMetadata.every((quote) => quote.cost.valueInCurrency)) {
276
- return (0, lodash_1.orderBy)(quotesWithMetadata, ({ cost }) => Number(cost.valueInCurrency), 'asc');
225
+ if (quotesWithMetadata.every((quote) => quote.quote.priceData?.cost?.valueInCurrency)) {
226
+ return (0, lodash_1.orderBy)(quotesWithMetadata, ({ quote: { priceData } }) => Number(priceData?.cost?.valueInCurrency), 'asc');
277
227
  }
278
- if (quotesWithMetadata.every((quote) => quote.quote.priceData?.priceImpact)) {
279
- return (0, lodash_1.orderBy)(quotesWithMetadata, ({ quote }) => Number(quote.priceData?.priceImpact), 'asc');
228
+ if (quotesWithMetadata.every((quote) => quote.quote.priceData?.priceImpact?.amount)) {
229
+ return (0, lodash_1.orderBy)(quotesWithMetadata, ({ quote }) => Number(quote.priceData?.priceImpact?.amount), 'asc');
280
230
  }
281
- return (0, lodash_1.orderBy)(quotesWithMetadata, ({ quote }) => Number(quote.destTokenAmount), 'desc');
231
+ return (0, lodash_1.orderBy)(quotesWithMetadata, ({ quote }) => Number(quote.dest.amount), 'desc');
282
232
  }
283
233
  });
284
234
  const selectRecommendedQuote = createBridgeSelector([selectSortedBridgeQuotes], (quotes) => (quotes.length > 0 ? quotes[0] : null));
285
235
  const selectActiveQuote = createBridgeSelector([
286
236
  selectRecommendedQuote,
287
237
  selectSortedBridgeQuotes,
288
- (_, { selectedQuote }) => selectedQuote,
289
- ], (recommendedQuote, sortedQuotes, selectedQuote) => sortedQuotes.find((quote) => quote.quote.requestId === selectedQuote?.quote.requestId) ?? recommendedQuote);
238
+ (_, { selectedQuote }) => selectedQuote?.quote.requestId,
239
+ ], (recommendedQuote, sortedQuotes, requestId) => sortedQuotes.find((quote) => quote.quote.requestId === requestId) ??
240
+ recommendedQuote);
290
241
  const selectIsQuoteGoingToRefresh = createBridgeSelector([
291
242
  exports.selectBridgeFeatureFlags,
292
243
  // If at least one quote request is sufficiently funded, continue polling until max refresh count is reached
@@ -342,21 +293,22 @@ const selectRecommendedQuotes = createBridgeSelector([
342
293
  acc[requestIndex] ?? (acc[requestIndex] = quote);
343
294
  return acc;
344
295
  }, Array(requestCount).fill(null)));
345
- const selectMetadataSum = createBridgeSelector([
346
- selectRecommendedQuotes,
347
- (_, { key, }) => key,
348
- ], (recommendedQuotes, key) => recommendedQuotes.reduce((acc, quote) => {
349
- acc.usd = new bignumber_js_1.BigNumber(acc.usd ?? 0)
350
- .plus(quote?.[key]?.usd ?? 0)
351
- .toString();
352
- acc.valueInCurrency = new bignumber_js_1.BigNumber(acc.valueInCurrency ?? 0)
353
- .plus(quote?.[key]?.valueInCurrency ?? 0)
354
- .toString();
355
- acc.amount = new bignumber_js_1.BigNumber(acc.amount ?? 0)
356
- .plus(quote?.[key]?.amount ?? 0)
357
- .toString();
358
- return acc;
359
- }, { usd: null, valueInCurrency: null, amount: '0' }));
296
+ const selectDestAmountSum = createBridgeSelector([selectRecommendedQuotes], (recommendedQuotes) => {
297
+ return (0, number_formatters_1.sumAmounts)(recommendedQuotes.map((quote) => quote?.quote.dest));
298
+ });
299
+ const selectMinDestAmountSum = createBridgeSelector([selectDestAmountSum], (destAmountSum) => {
300
+ if (!destAmountSum) {
301
+ return undefined;
302
+ }
303
+ const { minAmount, minAmountNormalized, minAmountValueInCurrency, minAmountUsd, asset, } = destAmountSum;
304
+ return {
305
+ amount: minAmount,
306
+ normalizedAmount: minAmountNormalized,
307
+ valueInCurrency: minAmountValueInCurrency,
308
+ usd: minAmountUsd,
309
+ asset,
310
+ };
311
+ });
360
312
  /**
361
313
  * Selects the recommended swap quotes for a batch of quote requests.
362
314
  *
@@ -379,8 +331,8 @@ const selectMetadataSum = createBridgeSelector([
379
331
  */
380
332
  exports.selectBatchSellQuotes = createStructuredBridgeSelector({
381
333
  recommendedQuotes: selectRecommendedQuotes,
382
- totalReceived: (state, opts) => selectMetadataSum(state, { ...opts, key: 'toTokenAmount' }),
383
- minimumReceived: (state, opts) => selectMetadataSum(state, { ...opts, key: 'minToTokenAmount' }),
334
+ totalReceived: selectDestAmountSum,
335
+ minimumReceived: selectMinDestAmountSum,
384
336
  quotesLastFetchedMs: (state) => state.quotesLastFetched,
385
337
  isLoading: (state) => state.quotesLoadingStatus === types_1.RequestStatus.LOADING,
386
338
  quoteFetchError: (state) => state.quoteFetchError,
@@ -394,7 +346,7 @@ const selectBatchSellFees = createBridgeSelector([
394
346
  (state) => (0, exports.selectExchangeRateByAssetId)(state, state.batchSellTrades?.fee?.asset?.assetId),
395
347
  ], (feeAmount, feeAsset, exchangeRate) => {
396
348
  return feeAmount && feeAsset && exchangeRate
397
- ? (0, quote_1.calcBatchFees)(feeAmount, feeAsset, exchangeRate)
349
+ ? (0, calculators_1.calcBatchFees)(feeAmount, feeAsset, exchangeRate)
398
350
  : undefined;
399
351
  });
400
352
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"selectors.cjs","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":";;;AAAA,qEAAqE;AACrE,oDAAoD;AAWpD,2CAAwE;AACxE,+CAAyC;AACzC,mCAAiC;AACjC,uCAGkB;AAElB,mDAAmE;AAOnE,uCAAmD;AACnD,+CAKwB;AACxB,iEAKiC;AACjC,6DAA4D;AAC5D,6CAauB;AACvB,mDAAgE;AA0ChE;;GA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,WAAW,CAAC,CAAC,CAAC,mBAAmB,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,SAAS,CACxE,CAAC;AACJ,CAAC,CACF,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport { getAddress } from '@ethersproject/address';\nimport type {\n CurrencyRateState,\n MultichainAssetsRatesControllerState,\n TokenRatesControllerState,\n} from '@metamask/assets-controllers';\nimport type {\n GasFeeEstimates,\n GasFeeEstimatesByChainId,\n} from '@metamask/gas-fee-controller';\nimport type { CaipAssetType } from '@metamask/utils';\nimport { isStrictHexString, parseCaipAssetType } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\nimport { orderBy } from 'lodash';\nimport {\n createSelector as createSelector_,\n createStructuredSelector as createStructuredSelector_,\n} from 'reselect';\n\nimport { BRIDGE_PREFERRED_GAS_ESTIMATE } from './constants/bridge';\nimport type {\n BridgeControllerState,\n ExchangeRate,\n QuoteMetadata,\n TokenAmountValues,\n} from './types';\nimport { RequestStatus, SortOrder } from './types';\nimport {\n getNativeAssetForChainId,\n isEvmQuoteResponse,\n isNativeAddress,\n isNonEvmChainId,\n} from './utils/bridge';\nimport {\n formatAddressToAssetId,\n formatAddressToCaipReference,\n formatChainIdToCaip,\n formatChainIdToHex,\n} from './utils/caip-formatters';\nimport { processFeatureFlags } from './utils/feature-flags';\nimport {\n calcAdjustedReturn,\n calcCost,\n calcEstimatedAndMaxTotalGasFee,\n calcIncludedTxFees,\n calcRelayerFee,\n calcSentAmount,\n calcNonEvmTotalNetworkFee,\n calcSwapRate,\n calcToAmount,\n calcTotalEstimatedNetworkFee,\n calcTotalMaxNetworkFee,\n calcBatchFees,\n} from './utils/quote';\nimport { getDefaultSlippagePercentage } from './utils/slippage';\nimport type { QuoteResponseV1 } from './validators/quote-response-v1';\n\n/**\n * The controller states that provide exchange rates\n */\ntype ExchangeRateControllerState = MultichainAssetsRatesControllerState &\n TokenRatesControllerState &\n CurrencyRateState &\n Pick<BridgeControllerState, 'assetExchangeRates'>;\n/**\n * The state of the bridge controller and all its dependency controllers\n */\ntype RemoteFeatureFlagControllerState = {\n remoteFeatureFlags: {\n bridgeConfig: unknown;\n };\n};\n\n/**\n * Minimal shape required for exchange-rate lookups (used by getExchangeRateByChainIdAndAddress).\n * Uses types from assets-controllers; marketData and conversionRates also accept the bridge format.\n */\nexport type ExchangeRateSourcesForLookup = Pick<\n BridgeControllerState,\n 'assetExchangeRates'\n> &\n Partial<Pick<CurrencyRateState, 'currencyRates'>> &\n Partial<Pick<MultichainAssetsRatesControllerState, 'historicalPrices'>> & {\n marketData?:\n | TokenRatesControllerState['marketData']\n | Record<string, Record<string, { price?: number; currency?: string }>>;\n conversionRates?:\n | MultichainAssetsRatesControllerState['conversionRates']\n | Record<string, { rate: string }>;\n };\n\nexport type BridgeAppState = BridgeControllerState & {\n gasFeeEstimatesByChainId: GasFeeEstimatesByChainId;\n} & ExchangeRateControllerState & {\n participateInMetaMetrics: boolean;\n } & RemoteFeatureFlagControllerState;\n/**\n * Creates a structured selector for the bridge controller\n */\nconst createStructuredBridgeSelector =\n createStructuredSelector_.withTypes<BridgeAppState>();\n/**\n * Creates a typed selector for the bridge controller\n */\nconst createBridgeSelector = createSelector_.withTypes<BridgeAppState>();\n/**\n * Required parameters that clients must provide for the bridge quotes selector\n */\ntype BridgeQuotesClientParams = {\n sortOrder: SortOrder;\n selectedQuote: (QuoteResponseV1 & QuoteMetadata) | null;\n};\n\ntype EvmTokenExchangeRate = { price?: number; currency?: string };\ntype EvmTokenExchangeRates = Record<string, EvmTokenExchangeRate>;\n\nconst createFeatureFlagsSelector =\n createSelector_.withTypes<RemoteFeatureFlagControllerState>();\n\n/**\n * Selects the bridge feature flags\n *\n * @param state - The state of the bridge controller\n * @returns The bridge feature flags\n *\n * @example\n * ```ts\n * const featureFlags = useSelector(state => selectBridgeFeatureFlags(state));\n *\n * Or\n *\n * export const selectBridgeFeatureFlags = createSelector(\n * selectRemoteFeatureFlags,\n * (remoteFeatureFlags) =>\n * selectBridgeFeatureFlagsBase({\n * bridgeConfig: remoteFeatureFlags.bridgeConfig,\n * }),\n * );\n * ```\n */\nexport const selectBridgeFeatureFlags = createFeatureFlagsSelector(\n [(state) => state.remoteFeatureFlags.bridgeConfig],\n (bridgeConfig: unknown) => processFeatureFlags(bridgeConfig),\n);\n\nconst getEvmTokenExchangeRateForAddress = (\n evmTokenExchangeRates: EvmTokenExchangeRates | undefined,\n address: string,\n): EvmTokenExchangeRate | null | undefined => {\n try {\n return isStrictHexString(address)\n ? (evmTokenExchangeRates?.[getAddress(address)] ??\n evmTokenExchangeRates?.[address.toLowerCase()])\n : null;\n } catch {\n return null;\n }\n};\n\n/**\n * Selects the asset exchange rate for a given chain and address\n *\n * @param exchangeRateSources - the controller states containing the exchange rates\n * @param assetId - the assetId to get the exchange rate for\n * @returns The asset exchange rate for the given assetId\n */\nexport const selectExchangeRateByAssetId = (\n exchangeRateSources: ExchangeRateSourcesForLookup,\n assetId?: CaipAssetType,\n): ExchangeRate => {\n if (!assetId) {\n return {};\n }\n\n const { assetExchangeRates, currencyRates, marketData, conversionRates } =\n exchangeRateSources;\n\n // If the asset exchange rate is available in the bridge controller, use it\n // This is defined if the token's rate is not available from the assets controllers\n const bridgeControllerRate =\n assetExchangeRates?.[assetId.toLowerCase() as CaipAssetType] ??\n assetExchangeRates?.[assetId];\n if (\n bridgeControllerRate?.exchangeRate &&\n bridgeControllerRate?.usdExchangeRate\n ) {\n return bridgeControllerRate;\n }\n\n const { chainId } = parseCaipAssetType(assetId);\n\n // If the chain is a non-EVM chain, use the conversion rate from the multichain assets controller\n if (isNonEvmChainId(chainId)) {\n const conversionRatesByKey = conversionRates as\n | Record<string, { rate?: string }>\n | undefined;\n const multichainAssetExchangeRate = conversionRatesByKey?.[assetId];\n const rate = multichainAssetExchangeRate?.rate;\n if (rate) {\n // The multichain rate is denominated in the user's selected currency.\n // To get a USD rate, find the user's-currency-to-USD conversion factor from any EVM native currency rate.\n const nativeCurrencyRate = Object.values(currencyRates ?? {}).find(\n (rateEntry) =>\n rateEntry?.conversionRate !== undefined &&\n rateEntry?.conversionRate !== null &&\n rateEntry?.usdConversionRate !== undefined &&\n rateEntry?.usdConversionRate !== null,\n );\n const usersCurrencyToUsdRate =\n nativeCurrencyRate?.conversionRate !== undefined &&\n nativeCurrencyRate?.conversionRate !== null &&\n nativeCurrencyRate?.usdConversionRate !== undefined &&\n nativeCurrencyRate?.usdConversionRate !== null\n ? new BigNumber(nativeCurrencyRate.usdConversionRate).div(\n nativeCurrencyRate.conversionRate,\n )\n : undefined;\n const usdExchangeRate = usersCurrencyToUsdRate\n ? new BigNumber(rate).times(usersCurrencyToUsdRate).toString()\n : undefined;\n return {\n exchangeRate: rate,\n usdExchangeRate,\n };\n }\n return {};\n }\n\n const address = formatAddressToCaipReference(assetId);\n\n // If the chain is an EVM chain, use the conversion rate from the currency rates controller\n if (isNativeAddress(address)) {\n const { symbol } = getNativeAssetForChainId(chainId);\n const evmNativeExchangeRate = currencyRates?.[symbol];\n if (evmNativeExchangeRate) {\n return {\n exchangeRate: evmNativeExchangeRate.conversionRate?.toString(),\n usdExchangeRate: evmNativeExchangeRate.usdConversionRate?.toString(),\n };\n }\n return {};\n }\n // If the chain is an EVM chain and the asset is not the native asset, use the conversion rate from the token rates controller\n if (!isNonEvmChainId(chainId)) {\n const marketDataByChain =\n (marketData as Record<string, EvmTokenExchangeRates> | undefined) ?? {};\n const evmTokenExchangeRates =\n marketDataByChain[formatChainIdToHex(chainId)];\n const evmTokenExchangeRateForAddress = getEvmTokenExchangeRateForAddress(\n evmTokenExchangeRates,\n address,\n );\n const currencyKey = evmTokenExchangeRateForAddress?.currency;\n const nativeCurrencyRate =\n currencyKey !== undefined && currencyKey !== null\n ? currencyRates?.[currencyKey]\n : undefined;\n const price = evmTokenExchangeRateForAddress?.price;\n // A missing or zero price is not a usable exchange rate. Returning a \"0\"\n // rate here is harmful in two ways: it surfaces a $0 fiat value, and it\n // makes `selectIsAssetExchangeRateInState` treat the token as already\n // priced (the non-empty \"0\" string is truthy), which prevents the\n // controller from fetching the real rate. Fall through to `{}` instead so\n // the rate gets fetched from the price API.\n if (price && nativeCurrencyRate) {\n return {\n exchangeRate: new BigNumber(price)\n .multipliedBy(nativeCurrencyRate.conversionRate ?? 0)\n .toString(),\n usdExchangeRate: new BigNumber(price)\n .multipliedBy(nativeCurrencyRate.usdConversionRate ?? 0)\n .toString(),\n };\n }\n }\n\n return {};\n};\n\n/**\n * Checks whether an exchange rate is available for a given assetId\n *\n * @param state The state of the bridge controller and its dependency controllers\n * @param assetId The assetId to check\n * @returns Whether an exchange rate is available for the given chain and address\n */\nexport const selectIsAssetExchangeRateInState = (\n state: ExchangeRateSourcesForLookup,\n assetId?: CaipAssetType,\n) =>\n Boolean(selectExchangeRateByAssetId(state, assetId)?.exchangeRate) &&\n Boolean(selectExchangeRateByAssetId(state, assetId)?.usdExchangeRate);\n\n/**\n * Selects the gas fee estimates from the gas fee controller. All potential networks\n * support EIP1559 gas fees so assume that gasFeeEstimates is of type GasFeeEstimates\n *\n * @param state - The state of the bridge controller and its dependency controllers\n * @param state.gasFeeEstimatesByChainId - gasEstimates by Hex ChainId\n * @param state.quotes - Fetched bridge/swap quotes\n * @returns The gas fee estimates in decGWEI\n */\nconst selectBridgeFeesPerGas = createBridgeSelector(\n [\n (state) => state.gasFeeEstimatesByChainId,\n (state) => state.quotes?.[0]?.quote.srcChainId,\n ],\n (gasFeeEstimatesByChainId, srcChainId) => {\n if (!srcChainId) {\n return null;\n }\n if (isNonEvmChainId(srcChainId)) {\n return null;\n }\n // @ts-expect-error - all supported networks use this type of estimates\n const gasFeeEstimates: GasFeeEstimates | undefined =\n gasFeeEstimatesByChainId?.[\n formatChainIdToHex(srcChainId) as keyof typeof gasFeeEstimatesByChainId\n ]?.gasFeeEstimates;\n if (!gasFeeEstimates) {\n return null;\n }\n return {\n estimatedBaseFeeInDecGwei: gasFeeEstimates.estimatedBaseFee,\n feePerGasInDecGwei:\n gasFeeEstimates[BRIDGE_PREFERRED_GAS_ESTIMATE]?.suggestedMaxFeePerGas,\n maxFeePerGasInDecGwei: gasFeeEstimates.high?.suggestedMaxFeePerGas,\n };\n },\n);\n\n// Selects cross-chain swap quotes including their metadata\nconst selectBridgeQuotesWithMetadata = createBridgeSelector(\n [\n ({ quotes }) => quotes,\n selectBridgeFeesPerGas,\n (state) => state,\n createBridgeSelector(\n [\n (state) => state,\n ({ quoteRequest: [{ destChainId, destTokenAddress }] }) =>\n destTokenAddress\n ? formatAddressToAssetId(destTokenAddress, destChainId)\n : undefined,\n ],\n selectExchangeRateByAssetId,\n ),\n createBridgeSelector(\n [\n (state) => state,\n ({ quoteRequest: [{ srcChainId }] }) =>\n srcChainId\n ? getNativeAssetForChainId(srcChainId)?.assetId\n : undefined,\n ],\n selectExchangeRateByAssetId,\n ),\n ],\n (\n quotes,\n bridgeFeesPerGas,\n exchangeRateSources,\n destTokenExchangeRate,\n nativeExchangeRate,\n ) => {\n const newQuotes = quotes.map((quote) => {\n const sourceAssetId =\n formatAddressToAssetId(\n quote.quote.srcAsset.address,\n quote.quote.srcChainId,\n ) ?? quote.quote.srcAsset.assetId;\n const srcTokenExchangeRate = selectExchangeRateByAssetId(\n exchangeRateSources,\n sourceAssetId,\n );\n const sentAmount = calcSentAmount(quote.quote, srcTokenExchangeRate);\n const toTokenAmount = calcToAmount(\n quote.quote.destTokenAmount,\n quote.quote.destAsset,\n destTokenExchangeRate,\n );\n const minToTokenAmount = calcToAmount(\n quote.quote.minDestTokenAmount,\n quote.quote.destAsset,\n destTokenExchangeRate,\n );\n\n const includedTxFees = calcIncludedTxFees(\n quote.quote,\n srcTokenExchangeRate,\n destTokenExchangeRate,\n );\n\n let totalEstimatedNetworkFee,\n totalMaxNetworkFee,\n relayerFee,\n gasFee: QuoteMetadata['gasFee'];\n\n if (isEvmQuoteResponse(quote)) {\n relayerFee = calcRelayerFee(quote, nativeExchangeRate);\n gasFee = calcEstimatedAndMaxTotalGasFee({\n bridgeQuote: quote,\n ...bridgeFeesPerGas,\n ...nativeExchangeRate,\n });\n // Uses effectiveGasFee to calculate the total estimated network fee\n totalEstimatedNetworkFee = calcTotalEstimatedNetworkFee(\n gasFee,\n relayerFee,\n );\n totalMaxNetworkFee = calcTotalMaxNetworkFee(gasFee, relayerFee);\n } else {\n // Use the new generic function for all non-EVM chains\n totalEstimatedNetworkFee = calcNonEvmTotalNetworkFee(\n quote,\n nativeExchangeRate,\n );\n gasFee = {\n effective: totalEstimatedNetworkFee,\n total: totalEstimatedNetworkFee,\n max: totalEstimatedNetworkFee,\n };\n totalMaxNetworkFee = totalEstimatedNetworkFee;\n }\n\n const adjustedReturn = calcAdjustedReturn(\n toTokenAmount,\n totalEstimatedNetworkFee,\n quote.quote,\n );\n const cost = calcCost(adjustedReturn, sentAmount);\n\n return {\n ...quote,\n // QuoteMetadata fields\n sentAmount,\n toTokenAmount,\n minToTokenAmount,\n swapRate: calcSwapRate(sentAmount.amount, toTokenAmount.amount),\n /**\n This is the amount required to submit all the transactions.\n Includes the relayer fee or other native fees.\n Should be used for balance checks and tx submission.\n */\n totalNetworkFee: totalEstimatedNetworkFee,\n totalMaxNetworkFee,\n /**\n This contains gas fee estimates for the bridge transaction\n Does not include the relayer fee (if needed), just the gasLimit and effectiveGas returned by the bridge API.\n Should only be used for display purposes.\n */\n gasFee,\n adjustedReturn,\n cost,\n includedTxFees,\n };\n });\n\n return newQuotes;\n },\n);\n\nconst selectSortedBridgeQuotes = createBridgeSelector(\n [\n selectBridgeQuotesWithMetadata,\n (_, { sortOrder }: BridgeQuotesClientParams) => sortOrder,\n ],\n (quotesWithMetadata, sortOrder): (QuoteResponseV1 & QuoteMetadata)[] => {\n switch (sortOrder) {\n case SortOrder.ETA_ASC:\n return orderBy(\n quotesWithMetadata,\n (quote) => quote.estimatedProcessingTimeInSeconds,\n 'asc',\n );\n default:\n if (quotesWithMetadata.every((quote) => quote.cost.valueInCurrency)) {\n return orderBy(\n quotesWithMetadata,\n ({ cost }) => Number(cost.valueInCurrency),\n 'asc',\n );\n }\n if (\n quotesWithMetadata.every(\n (quote) => quote.quote.priceData?.priceImpact,\n )\n ) {\n return orderBy(\n quotesWithMetadata,\n ({ quote }) => Number(quote.priceData?.priceImpact),\n 'asc',\n );\n }\n return orderBy(\n quotesWithMetadata,\n ({ quote }) => Number(quote.destTokenAmount),\n 'desc',\n );\n }\n },\n);\n\nconst selectRecommendedQuote = createBridgeSelector(\n [selectSortedBridgeQuotes],\n (quotes) => (quotes.length > 0 ? quotes[0] : null),\n);\n\nconst selectActiveQuote = createBridgeSelector(\n [\n selectRecommendedQuote,\n selectSortedBridgeQuotes,\n (_, { selectedQuote }) => selectedQuote,\n ],\n (recommendedQuote, sortedQuotes, selectedQuote) =>\n sortedQuotes.find(\n (quote) => quote.quote.requestId === selectedQuote?.quote.requestId,\n ) ?? recommendedQuote,\n);\n\nconst selectIsQuoteGoingToRefresh = createBridgeSelector(\n [\n selectBridgeFeatureFlags,\n // If at least one quote request is sufficiently funded, continue polling until max refresh count is reached\n (state) =>\n state.quoteRequest.every((quoteRequest) =>\n Boolean(quoteRequest.insufficientBal),\n ),\n (state) => state.quotesRefreshCount,\n ],\n (featureFlags, insufficientBal, quotesRefreshCount) =>\n insufficientBal ? false : featureFlags.maxRefreshCount > quotesRefreshCount,\n);\n\nconst selectQuoteRefreshRate = createBridgeSelector(\n [selectBridgeFeatureFlags, (state) => state.quoteRequest[0]?.srcChainId],\n (featureFlags, srcChainId) =>\n (srcChainId\n ? featureFlags.chains[formatChainIdToCaip(srcChainId)]?.refreshRate\n : featureFlags.refreshRate) ?? featureFlags.refreshRate,\n);\n\nexport const selectIsQuoteExpired = createBridgeSelector(\n [\n selectIsQuoteGoingToRefresh,\n ({ quotesLastFetched }) => quotesLastFetched,\n selectQuoteRefreshRate,\n (_, _ignoredParam, currentTimeInMs: number) => currentTimeInMs,\n ],\n (isQuoteGoingToRefresh, quotesLastFetched, refreshRate, currentTimeInMs) =>\n Boolean(\n !isQuoteGoingToRefresh &&\n quotesLastFetched &&\n currentTimeInMs - quotesLastFetched > refreshRate,\n ),\n);\n\n/**\n * Selects sorted cross-chain swap quotes. By default, the quotes are sorted by cost in ascending order.\n *\n * @param state - The state of the bridge controller and its dependency controllers\n * @param sortOrder - The sort order of the quotes\n * @param selectedQuote - The quote that is currently selected by the user, should be cleared by clients when the req params change\n * @returns The activeQuote, recommendedQuote, sortedQuotes, and other quote fetching metadata\n *\n * @example\n * ```ts\n * const quotes = useSelector(state => selectBridgeQuotes(\n * { ...state.metamask, bridgeConfig: remoteFeatureFlags.bridgeConfig },\n * {\n * sortOrder: state.bridge.sortOrder,\n * selectedQuote: state.bridge.selectedQuote,\n * }\n * ));\n * ```\n */\nexport const selectBridgeQuotes = createStructuredBridgeSelector({\n sortedQuotes: selectSortedBridgeQuotes,\n recommendedQuote: selectRecommendedQuote,\n activeQuote: selectActiveQuote,\n quotesLastFetchedMs: (state) => state.quotesLastFetched,\n isLoading: (state) => state.quotesLoadingStatus === RequestStatus.LOADING,\n quoteFetchError: (state) => state.quoteFetchError,\n quotesRefreshCount: (state) => state.quotesRefreshCount,\n quotesInitialLoadTimeMs: (state) => state.quotesInitialLoadTime,\n isQuoteGoingToRefresh: selectIsQuoteGoingToRefresh,\n});\n\nconst selectRecommendedQuotes = createBridgeSelector(\n [\n selectSortedBridgeQuotes,\n (_, { requestCount }: { requestCount: number }) => requestCount,\n ],\n (quotes, requestCount) =>\n quotes.reduce((acc, quote) => {\n const requestIndex = quote.quoteRequestIndex ?? 0;\n acc[requestIndex] ??= quote;\n return acc;\n }, Array<(QuoteResponseV1 & QuoteMetadata) | null>(requestCount).fill(null)),\n);\n\nconst selectMetadataSum = createBridgeSelector(\n [\n selectRecommendedQuotes,\n (\n _,\n {\n key,\n }: { key: 'totalNetworkFee' | 'minToTokenAmount' | 'toTokenAmount' },\n ) => key,\n ],\n (recommendedQuotes, key) =>\n recommendedQuotes.reduce<TokenAmountValues>(\n (acc, quote) => {\n acc.usd = new BigNumber(acc.usd ?? 0)\n .plus(quote?.[key]?.usd ?? 0)\n .toString();\n acc.valueInCurrency = new BigNumber(acc.valueInCurrency ?? 0)\n .plus(quote?.[key]?.valueInCurrency ?? 0)\n .toString();\n acc.amount = new BigNumber(acc.amount ?? 0)\n .plus(quote?.[key]?.amount ?? 0)\n .toString();\n return acc;\n },\n { usd: null, valueInCurrency: null, amount: '0' },\n ),\n);\n\n/**\n * Selects the recommended swap quotes for a batch of quote requests.\n *\n * @param state - The state of the bridge controller and its dependency controllers\n * @param sortOrder - The sort order of the quotes\n * @param requestCount - The number of quote requests fetched in the batch\n * @returns The quotes for multiple quote requests, including their recommendedQuotes,\n * totalReceived, minimumReceived, totalNetworkFee, and other quote fetching metadata.\n *\n * @example\n * ```ts\n * const quotes = useSelector(state => selectBatchSellQuotes(\n * { ...state.metamask },\n * {\n * sortOrder: state.bridge.sortOrder,\n * requestCount: 4,\n * }\n * ));\n * ```\n */\nexport const selectBatchSellQuotes = createStructuredBridgeSelector({\n recommendedQuotes: selectRecommendedQuotes,\n totalReceived: (state, opts) =>\n selectMetadataSum(state, { ...opts, key: 'toTokenAmount' }),\n minimumReceived: (state, opts) =>\n selectMetadataSum(state, { ...opts, key: 'minToTokenAmount' }),\n quotesLastFetchedMs: (state) => state.quotesLastFetched,\n isLoading: (state) => state.quotesLoadingStatus === RequestStatus.LOADING,\n quoteFetchError: (state) => state.quoteFetchError,\n quotesRefreshCount: (state) => state.quotesRefreshCount,\n quotesInitialLoadTimeMs: (state) => state.quotesInitialLoadTime,\n isQuoteGoingToRefresh: selectIsQuoteGoingToRefresh,\n});\n\nconst selectBatchSellFees = createBridgeSelector(\n [\n (state) => state.batchSellTrades?.fee?.amount,\n (state) => state.batchSellTrades?.fee?.asset,\n (state) =>\n selectExchangeRateByAssetId(\n state,\n state.batchSellTrades?.fee?.asset?.assetId,\n ),\n ],\n (feeAmount, feeAsset, exchangeRate) => {\n return feeAmount && feeAsset && exchangeRate\n ? calcBatchFees(feeAmount, feeAsset, exchangeRate)\n : undefined;\n },\n);\n\n/**\n * Selects the batch transactions and fees for a batch of quotes\n *\n * @param state - The state of the bridge controller and its dependency controllers\n * @returns The total transaction fees and whether the batch sell trades are submittable.\n *\n * @example\n * ```ts\n * const { totalNetworkFee, isBatchSellTradeAvailable } = useSelector(state => selectBatchSellTrades(state.metamask));\n * ```\n */\nexport const selectBatchSellTrades = createBridgeSelector(\n [\n (state) => state.batchSellTradesLoadingStatus === RequestStatus.FETCHED,\n (state) => state.batchSellTrades,\n selectBatchSellFees,\n (state) => state.batchSellTradesLoadingStatus === RequestStatus.LOADING,\n ],\n (isBatchSellTradeAvailable, batchSellTrades, batchFees, isLoading) => {\n return {\n totalNetworkFee: batchFees,\n /**\n * Whether the batch sell trades have been fetched and transactions are ready to be submitted\n */\n isBatchSellTradeAvailable:\n isBatchSellTradeAvailable &&\n Boolean(batchSellTrades?.transactions?.length),\n isLoading,\n };\n },\n);\n\nexport const selectMinimumBalanceForRentExemptionInSOL = (\n state: BridgeAppState,\n) =>\n new BigNumber(state.minimumBalanceForRentExemptionInLamports ?? 0)\n .div(10 ** 9)\n .toString();\n\nexport const selectTokenWarnings = (state: BridgeAppState) =>\n state.tokenWarnings;\n\nexport const selectDefaultSlippagePercentage = createBridgeSelector(\n [\n (state) => selectBridgeFeatureFlags(state).chains,\n (_, slippageParams: Parameters<typeof getDefaultSlippagePercentage>[0]) =>\n slippageParams.srcTokenAddress,\n (_, slippageParams: Parameters<typeof getDefaultSlippagePercentage>[0]) =>\n slippageParams.destTokenAddress,\n (_, slippageParams: Parameters<typeof getDefaultSlippagePercentage>[0]) =>\n slippageParams.srcChainId\n ? formatChainIdToCaip(slippageParams.srcChainId)\n : undefined,\n (_, slippageParams: Parameters<typeof getDefaultSlippagePercentage>[0]) =>\n slippageParams.destChainId\n ? formatChainIdToCaip(slippageParams.destChainId)\n : undefined,\n ],\n (\n featureFlagsByChain,\n srcTokenAddress,\n destTokenAddress,\n srcChainId,\n destChainId,\n ) => {\n return getDefaultSlippagePercentage(\n {\n srcTokenAddress,\n destTokenAddress,\n srcChainId,\n destChainId,\n },\n srcChainId ? featureFlagsByChain[srcChainId]?.stablecoins : undefined,\n destChainId ? featureFlagsByChain[destChainId]?.stablecoins : undefined,\n );\n },\n);\n"]}
1
+ {"version":3,"file":"selectors.cjs","sourceRoot":"","sources":["../src/selectors.ts"],"names":[],"mappings":";;;AAAA,qEAAqE;AACrE,oDAAoD;AAWpD,2CAAwE;AACxE,+CAAyC;AACzC,mCAAiC;AACjC,uCAGkB;AAElB,mDAAmE;AAEnE,uCAAmD;AACnD,+CAIwB;AACxB,iEAKiC;AACjC,6DAA4D;AAC5D,qEAAuD;AACvD,wEAAmE;AACnE,wEAAuE;AACvE,4DAAkE;AAElE,mDAAgE;AAyChE;;GAEG;AACH,MAAM,8BAA8B,GAClC,mCAAyB,CAAC,SAAS,EAAkB,CAAC;AACxD;;GAEG;AACH,MAAM,oBAAoB,GAAG,yBAAe,CAAC,SAAS,EAAkB,CAAC;AAYzE,MAAM,0BAA0B,GAC9B,yBAAe,CAAC,SAAS,EAAoC,CAAC;AAEhE;;;;;;;;;;;;;;;;;;;;GAoBG;AACU,QAAA,wBAAwB,GAAG,0BAA0B,CAChE,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,kBAAkB,CAAC,YAAY,CAAC,EAClD,CAAC,YAAqB,EAAE,EAAE,CAAC,IAAA,mCAAmB,EAAC,YAAY,CAAC,CAC7D,CAAC;AAEF,MAAM,iCAAiC,GAAG,CACxC,qBAAwD,EACxD,OAAe,EAC0B,EAAE;IAC3C,IAAI,CAAC;QACH,OAAO,IAAA,yBAAiB,EAAC,OAAO,CAAC;YAC/B,CAAC,CAAC,CAAC,qBAAqB,EAAE,CAAC,IAAA,oBAAU,EAAC,OAAO,CAAC,CAAC;gBAC3C,qBAAqB,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;YACnD,CAAC,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C,UAAU,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,SAAS,EACrE,WAAW,CAAC,CAAC,CAAC,mBAAmB,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,SAAS,CACxE,CAAC;AACJ,CAAC,CACF,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport { getAddress } from '@ethersproject/address';\nimport type {\n CurrencyRateState,\n MultichainAssetsRatesControllerState,\n TokenRatesControllerState,\n} from '@metamask/assets-controllers';\nimport type {\n GasFeeEstimates,\n GasFeeEstimatesByChainId,\n} from '@metamask/gas-fee-controller';\nimport type { CaipAssetType } from '@metamask/utils';\nimport { isStrictHexString, parseCaipAssetType } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\nimport { orderBy } from 'lodash';\nimport {\n createSelector as createSelector_,\n createStructuredSelector as createStructuredSelector_,\n} from 'reselect';\n\nimport { BRIDGE_PREFERRED_GAS_ESTIMATE } from './constants/bridge';\nimport type { BridgeControllerState, DeepPartial, ExchangeRate } from './types';\nimport { RequestStatus, SortOrder } from './types';\nimport {\n getNativeAssetForChainId,\n isNativeAddress,\n isNonEvmChainId,\n} from './utils/bridge';\nimport {\n formatAddressToAssetId,\n formatAddressToCaipReference,\n formatChainIdToCaip,\n formatChainIdToHex,\n} from './utils/caip-formatters';\nimport { processFeatureFlags } from './utils/feature-flags';\nimport { sumAmounts } from './utils/number-formatters';\nimport { calcBatchFees } from './utils/quote-metadata/calculators';\nimport { calcQuoteMetadata } from './utils/quote-metadata/calculators';\nimport { mergeQuoteMetadata } from './utils/quote-metadata/merge';\nimport type { QuoteMetadata } from './utils/quote-metadata/types';\nimport { getDefaultSlippagePercentage } from './utils/slippage';\nimport type { QuoteResponse } from './validators/quote-response';\n\n/**\n * The controller states that provide exchange rates\n */\ntype ExchangeRateControllerState = MultichainAssetsRatesControllerState &\n TokenRatesControllerState &\n CurrencyRateState &\n Pick<BridgeControllerState, 'assetExchangeRates'>;\n/**\n * The state of the bridge controller and all its dependency controllers\n */\ntype RemoteFeatureFlagControllerState = {\n remoteFeatureFlags: {\n bridgeConfig: unknown;\n };\n};\n\n/**\n * Minimal shape required for exchange-rate lookups (used by getExchangeRateByChainIdAndAddress).\n * Uses types from assets-controllers; marketData and conversionRates also accept the bridge format.\n */\nexport type ExchangeRateSourcesForLookup = Pick<\n BridgeControllerState,\n 'assetExchangeRates'\n> &\n Partial<Pick<CurrencyRateState, 'currencyRates'>> & {\n marketData?:\n | TokenRatesControllerState['marketData']\n | Record<string, Record<string, { price?: number; currency?: string }>>;\n conversionRates?:\n | MultichainAssetsRatesControllerState['conversionRates']\n | Record<string, { rate: string }>;\n };\n\nexport type BridgeAppState = BridgeControllerState & {\n gasFeeEstimatesByChainId: GasFeeEstimatesByChainId;\n} & ExchangeRateControllerState & {\n participateInMetaMetrics: boolean;\n } & RemoteFeatureFlagControllerState;\n/**\n * Creates a structured selector for the bridge controller\n */\nconst createStructuredBridgeSelector =\n createStructuredSelector_.withTypes<BridgeAppState>();\n/**\n * Creates a typed selector for the bridge controller\n */\nconst createBridgeSelector = createSelector_.withTypes<BridgeAppState>();\n/**\n * Required parameters that clients must provide for the bridge quotes selector\n */\ntype BridgeQuotesClientParams = {\n sortOrder: SortOrder;\n selectedQuote: (QuoteResponse & QuoteMetadata) | null;\n};\n\ntype EvmTokenExchangeRate = { price?: number; currency?: string };\ntype EvmTokenExchangeRates = Record<string, EvmTokenExchangeRate>;\n\nconst createFeatureFlagsSelector =\n createSelector_.withTypes<RemoteFeatureFlagControllerState>();\n\n/**\n * Selects the bridge feature flags\n *\n * @param state - The state of the bridge controller\n * @returns The bridge feature flags\n *\n * @example\n * ```ts\n * const featureFlags = useSelector(state => selectBridgeFeatureFlags(state));\n *\n * Or\n *\n * export const selectBridgeFeatureFlags = createSelector(\n * selectRemoteFeatureFlags,\n * (remoteFeatureFlags) =>\n * selectBridgeFeatureFlagsBase({\n * bridgeConfig: remoteFeatureFlags.bridgeConfig,\n * }),\n * );\n * ```\n */\nexport const selectBridgeFeatureFlags = createFeatureFlagsSelector(\n [(state) => state.remoteFeatureFlags.bridgeConfig],\n (bridgeConfig: unknown) => processFeatureFlags(bridgeConfig),\n);\n\nconst getEvmTokenExchangeRateForAddress = (\n evmTokenExchangeRates: EvmTokenExchangeRates | undefined,\n address: string,\n): EvmTokenExchangeRate | null | undefined => {\n try {\n return isStrictHexString(address)\n ? (evmTokenExchangeRates?.[getAddress(address)] ??\n evmTokenExchangeRates?.[address.toLowerCase()])\n : null;\n } catch {\n return null;\n }\n};\n\n/**\n * Selects the asset exchange rate for a given chain and address\n *\n * @param exchangeRateSources - the controller states containing the exchange rates\n * @param assetId - the assetId to get the exchange rate for\n * @returns The asset exchange rate for the given assetId\n */\nexport const selectExchangeRateByAssetId = (\n exchangeRateSources: ExchangeRateSourcesForLookup,\n assetId?: CaipAssetType,\n): ExchangeRate => {\n if (!assetId) {\n return {};\n }\n\n const { assetExchangeRates, currencyRates, marketData, conversionRates } =\n exchangeRateSources;\n\n // If the asset exchange rate is available in the bridge controller, use it\n // This is defined if the token's rate is not available from the assets controllers\n const bridgeControllerRate =\n assetExchangeRates?.[assetId.toLowerCase() as CaipAssetType] ??\n assetExchangeRates?.[assetId];\n if (\n bridgeControllerRate?.exchangeRate &&\n bridgeControllerRate?.usdExchangeRate\n ) {\n return bridgeControllerRate;\n }\n\n const { chainId } = parseCaipAssetType(assetId);\n\n // If the chain is a non-EVM chain, use the conversion rate from the multichain assets controller\n if (isNonEvmChainId(chainId)) {\n const conversionRatesByKey = conversionRates as\n | Record<string, { rate?: string }>\n | undefined;\n const multichainAssetExchangeRate = conversionRatesByKey?.[assetId];\n const rate = multichainAssetExchangeRate?.rate;\n if (rate) {\n // The multichain rate is denominated in the user's selected currency.\n // To get a USD rate, find the user's-currency-to-USD conversion factor from any EVM native currency rate.\n const nativeCurrencyRate = Object.values(currencyRates ?? {}).find(\n (rateEntry) =>\n rateEntry?.conversionRate !== undefined &&\n rateEntry?.conversionRate !== null &&\n rateEntry?.usdConversionRate !== undefined &&\n rateEntry?.usdConversionRate !== null,\n );\n const usersCurrencyToUsdRate =\n nativeCurrencyRate?.conversionRate !== undefined &&\n nativeCurrencyRate?.conversionRate !== null &&\n nativeCurrencyRate?.usdConversionRate !== undefined &&\n nativeCurrencyRate?.usdConversionRate !== null\n ? new BigNumber(nativeCurrencyRate.usdConversionRate).div(\n nativeCurrencyRate.conversionRate,\n )\n : undefined;\n const usdExchangeRate = usersCurrencyToUsdRate\n ? new BigNumber(rate).times(usersCurrencyToUsdRate).toString()\n : undefined;\n return {\n exchangeRate: rate,\n usdExchangeRate,\n };\n }\n return {};\n }\n\n const address = formatAddressToCaipReference(assetId);\n\n // If the chain is an EVM chain, use the conversion rate from the currency rates controller\n if (isNativeAddress(address)) {\n const { symbol } = getNativeAssetForChainId(chainId);\n const evmNativeExchangeRate = currencyRates?.[symbol];\n if (evmNativeExchangeRate) {\n return {\n exchangeRate: evmNativeExchangeRate.conversionRate?.toString(),\n usdExchangeRate: evmNativeExchangeRate.usdConversionRate?.toString(),\n };\n }\n return {};\n }\n // If the chain is an EVM chain and the asset is not the native asset, use the conversion rate from the token rates controller\n if (!isNonEvmChainId(chainId)) {\n const marketDataByChain =\n (marketData as Record<string, EvmTokenExchangeRates> | undefined) ?? {};\n const evmTokenExchangeRates =\n marketDataByChain[formatChainIdToHex(chainId)];\n const evmTokenExchangeRateForAddress = getEvmTokenExchangeRateForAddress(\n evmTokenExchangeRates,\n address,\n );\n const currencyKey = evmTokenExchangeRateForAddress?.currency;\n const nativeCurrencyRate =\n currencyKey !== undefined && currencyKey !== null\n ? currencyRates?.[currencyKey]\n : undefined;\n const price = evmTokenExchangeRateForAddress?.price;\n // A missing or zero price is not a usable exchange rate. Returning a \"0\"\n // rate here is harmful in two ways: it surfaces a $0 fiat value, and it\n // makes `selectIsAssetExchangeRateInState` treat the token as already\n // priced (the non-empty \"0\" string is truthy), which prevents the\n // controller from fetching the real rate. Fall through to `{}` instead so\n // the rate gets fetched from the price API.\n if (price && nativeCurrencyRate) {\n return {\n exchangeRate: new BigNumber(price)\n .multipliedBy(nativeCurrencyRate.conversionRate ?? 0)\n .toString(),\n usdExchangeRate: new BigNumber(price)\n .multipliedBy(nativeCurrencyRate.usdConversionRate ?? 0)\n .toString(),\n };\n }\n }\n\n return {};\n};\n\n/**\n * Checks whether an exchange rate is available for a given assetId\n *\n * @param state The state of the bridge controller and its dependency controllers\n * @param assetId The assetId to check\n * @returns Whether an exchange rate is available for the given chain and address\n */\nexport const selectIsAssetExchangeRateInState = (\n state: ExchangeRateSourcesForLookup,\n assetId?: CaipAssetType,\n) =>\n Boolean(selectExchangeRateByAssetId(state, assetId)?.exchangeRate) &&\n Boolean(selectExchangeRateByAssetId(state, assetId)?.usdExchangeRate);\n\n/**\n * Selects the gas fee estimates from the gas fee controller. All potential networks\n * support EIP1559 gas fees so assume that gasFeeEstimates is of type GasFeeEstimates\n *\n * @param state - The state of the bridge controller and its dependency controllers\n * @param state.gasFeeEstimatesByChainId - gasEstimates by Hex ChainId\n * @param state.quotes - Fetched bridge/swap quotes\n * @returns The gas fee estimates in decGWEI\n */\nconst selectBridgeFeesPerGas = createBridgeSelector(\n [\n (state) => state.gasFeeEstimatesByChainId,\n (state) => state.quotes?.[0]?.chainId,\n ],\n (gasFeeEstimatesByChainId, srcChainId) => {\n if (!srcChainId) {\n return null;\n }\n if (isNonEvmChainId(srcChainId)) {\n return null;\n }\n // @ts-expect-error - all supported networks use this type of estimates\n const gasFeeEstimates: GasFeeEstimates | undefined =\n gasFeeEstimatesByChainId?.[\n formatChainIdToHex(srcChainId) as keyof typeof gasFeeEstimatesByChainId\n ]?.gasFeeEstimates;\n if (!gasFeeEstimates) {\n return null;\n }\n return {\n estimatedBaseFeeInDecGwei: gasFeeEstimates.estimatedBaseFee,\n feePerGasInDecGwei:\n gasFeeEstimates[BRIDGE_PREFERRED_GAS_ESTIMATE]?.suggestedMaxFeePerGas,\n maxFeePerGasInDecGwei: gasFeeEstimates.high?.suggestedMaxFeePerGas,\n };\n },\n);\n\nconst selectExchangeRateSources = createStructuredBridgeSelector({\n currencyRates: (state) => state.currencyRates,\n marketData: (state) => state.marketData,\n conversionRates: (state) => state.conversionRates,\n assetExchangeRates: (state) => state.assetExchangeRates,\n});\n\n// Selects metadata for cross-chain swap quotes\nconst selectMetadata = createBridgeSelector(\n [\n ({ quotes }) => quotes,\n selectBridgeFeesPerGas,\n selectExchangeRateSources,\n ({ quoteRequest }) => quoteRequest,\n ],\n (quotes, bridgeFeesPerGas, exchangeRateSources, quoteRequest) => {\n const { destTokenAddress, srcChainId, destChainId } = quoteRequest[0] ?? {};\n\n return quotes.map((quote) =>\n calcQuoteMetadata(quote, {\n srcTokenExchangeRate: selectExchangeRateByAssetId(\n exchangeRateSources,\n quote.quote.src.asset.assetId,\n ),\n bridgeFeesPerGas,\n destTokenExchangeRate: selectExchangeRateByAssetId(\n exchangeRateSources,\n formatAddressToAssetId(\n destTokenAddress ?? quote.quote.dest.asset.assetId,\n destChainId,\n ),\n ),\n nativeExchangeRate: selectExchangeRateByAssetId(\n exchangeRateSources,\n getNativeAssetForChainId(srcChainId ?? quote.chainId)?.assetId,\n ),\n }),\n );\n },\n);\n\n// Selects cross-chain swap quotes including their metadata\nconst selectBridgeQuotesWithMetadata = createBridgeSelector(\n [selectMetadata, ({ quotes }) => quotes],\n (quoteMetadata, quotes) =>\n quotes.map((quote, index) =>\n mergeQuoteMetadata(quote, quoteMetadata[index]),\n ),\n);\n\nconst selectSortedBridgeQuotes = createBridgeSelector(\n [\n selectBridgeQuotesWithMetadata,\n (_, { sortOrder }: BridgeQuotesClientParams) => sortOrder,\n ],\n (quotesWithMetadata, sortOrder): (QuoteResponse & QuoteMetadata)[] => {\n switch (sortOrder) {\n case SortOrder.ETA_ASC:\n return orderBy(\n quotesWithMetadata,\n (quote) => quote.estimatedProcessingTimeInSeconds,\n 'asc',\n );\n default:\n if (\n quotesWithMetadata.every(\n (quote) => quote.quote.priceData?.cost?.valueInCurrency,\n )\n ) {\n return orderBy(\n quotesWithMetadata,\n ({ quote: { priceData } }) =>\n Number(priceData?.cost?.valueInCurrency),\n 'asc',\n );\n }\n if (\n quotesWithMetadata.every(\n (quote) => quote.quote.priceData?.priceImpact?.amount,\n )\n ) {\n return orderBy(\n quotesWithMetadata,\n ({ quote }) => Number(quote.priceData?.priceImpact?.amount),\n 'asc',\n );\n }\n return orderBy(\n quotesWithMetadata,\n ({ quote }) => Number(quote.dest.amount),\n 'desc',\n );\n }\n },\n);\n\nconst selectRecommendedQuote = createBridgeSelector(\n [selectSortedBridgeQuotes],\n (quotes) => (quotes.length > 0 ? quotes[0] : null),\n);\n\nconst selectActiveQuote = createBridgeSelector(\n [\n selectRecommendedQuote,\n selectSortedBridgeQuotes,\n (_, { selectedQuote }) => selectedQuote?.quote.requestId,\n ],\n (recommendedQuote, sortedQuotes, requestId) =>\n sortedQuotes.find((quote) => quote.quote.requestId === requestId) ??\n recommendedQuote,\n);\n\nconst selectIsQuoteGoingToRefresh = createBridgeSelector(\n [\n selectBridgeFeatureFlags,\n // If at least one quote request is sufficiently funded, continue polling until max refresh count is reached\n (state) =>\n state.quoteRequest.every((quoteRequest) =>\n Boolean(quoteRequest.insufficientBal),\n ),\n (state) => state.quotesRefreshCount,\n ],\n (featureFlags, insufficientBal, quotesRefreshCount) =>\n insufficientBal ? false : featureFlags.maxRefreshCount > quotesRefreshCount,\n);\n\nconst selectQuoteRefreshRate = createBridgeSelector(\n [selectBridgeFeatureFlags, (state) => state.quoteRequest[0]?.srcChainId],\n (featureFlags, srcChainId) =>\n (srcChainId\n ? featureFlags.chains[formatChainIdToCaip(srcChainId)]?.refreshRate\n : featureFlags.refreshRate) ?? featureFlags.refreshRate,\n);\n\nexport const selectIsQuoteExpired = createBridgeSelector(\n [\n selectIsQuoteGoingToRefresh,\n ({ quotesLastFetched }) => quotesLastFetched,\n selectQuoteRefreshRate,\n (_, _ignoredParam, currentTimeInMs: number) => currentTimeInMs,\n ],\n (isQuoteGoingToRefresh, quotesLastFetched, refreshRate, currentTimeInMs) =>\n Boolean(\n !isQuoteGoingToRefresh &&\n quotesLastFetched &&\n currentTimeInMs - quotesLastFetched > refreshRate,\n ),\n);\n\n/**\n * Selects sorted cross-chain swap quotes. By default, the quotes are sorted by cost in ascending order.\n *\n * @param state - The state of the bridge controller and its dependency controllers\n * @param sortOrder - The sort order of the quotes\n * @param selectedQuote - The quote that is currently selected by the user, should be cleared by clients when the req params change\n * @returns The activeQuote, recommendedQuote, sortedQuotes, and other quote fetching metadata\n *\n * @example\n * ```ts\n * const quotes = useSelector(state => selectBridgeQuotes(\n * { ...state.metamask, bridgeConfig: remoteFeatureFlags.bridgeConfig },\n * {\n * sortOrder: state.bridge.sortOrder,\n * selectedQuote: state.bridge.selectedQuote,\n * }\n * ));\n * ```\n */\nexport const selectBridgeQuotes = createStructuredBridgeSelector({\n sortedQuotes: selectSortedBridgeQuotes,\n recommendedQuote: selectRecommendedQuote,\n activeQuote: selectActiveQuote,\n quotesLastFetchedMs: (state) => state.quotesLastFetched,\n isLoading: (state) => state.quotesLoadingStatus === RequestStatus.LOADING,\n quoteFetchError: (state) => state.quoteFetchError,\n quotesRefreshCount: (state) => state.quotesRefreshCount,\n quotesInitialLoadTimeMs: (state) => state.quotesInitialLoadTime,\n isQuoteGoingToRefresh: selectIsQuoteGoingToRefresh,\n});\n\nconst selectRecommendedQuotes = createBridgeSelector(\n [\n selectSortedBridgeQuotes,\n (_, { requestCount }: { requestCount: number }) => requestCount,\n ],\n (quotes, requestCount) =>\n quotes.reduce((acc, quote) => {\n const requestIndex = quote.quoteRequestIndex ?? 0;\n acc[requestIndex] ??= quote;\n return acc;\n }, Array<QuoteResponse | null>(requestCount).fill(null)),\n);\nconst selectDestAmountSum = createBridgeSelector(\n [selectRecommendedQuotes],\n (recommendedQuotes) => {\n return sumAmounts(recommendedQuotes.map((quote) => quote?.quote.dest));\n },\n);\n\nconst selectMinDestAmountSum = createBridgeSelector(\n [selectDestAmountSum],\n (destAmountSum): DeepPartial<QuoteResponse['quote']['dest']> | undefined => {\n if (!destAmountSum) {\n return undefined;\n }\n\n const {\n minAmount,\n minAmountNormalized,\n minAmountValueInCurrency,\n minAmountUsd,\n asset,\n } = destAmountSum;\n\n return {\n amount: minAmount,\n normalizedAmount: minAmountNormalized,\n valueInCurrency: minAmountValueInCurrency,\n usd: minAmountUsd,\n asset,\n };\n },\n);\n\n/**\n * Selects the recommended swap quotes for a batch of quote requests.\n *\n * @param state - The state of the bridge controller and its dependency controllers\n * @param sortOrder - The sort order of the quotes\n * @param requestCount - The number of quote requests fetched in the batch\n * @returns The quotes for multiple quote requests, including their recommendedQuotes,\n * totalReceived, minimumReceived, totalNetworkFee, and other quote fetching metadata.\n *\n * @example\n * ```ts\n * const quotes = useSelector(state => selectBatchSellQuotes(\n * { ...state.metamask },\n * {\n * sortOrder: state.bridge.sortOrder,\n * requestCount: 4,\n * }\n * ));\n * ```\n */\nexport const selectBatchSellQuotes = createStructuredBridgeSelector({\n recommendedQuotes: selectRecommendedQuotes,\n totalReceived: selectDestAmountSum,\n minimumReceived: selectMinDestAmountSum,\n quotesLastFetchedMs: (state) => state.quotesLastFetched,\n isLoading: (state) => state.quotesLoadingStatus === RequestStatus.LOADING,\n quoteFetchError: (state) => state.quoteFetchError,\n quotesRefreshCount: (state) => state.quotesRefreshCount,\n quotesInitialLoadTimeMs: (state) => state.quotesInitialLoadTime,\n isQuoteGoingToRefresh: selectIsQuoteGoingToRefresh,\n});\n\nconst selectBatchSellFees = createBridgeSelector(\n [\n (state) => state.batchSellTrades?.fee?.amount,\n (state) => state.batchSellTrades?.fee?.asset,\n (state) =>\n selectExchangeRateByAssetId(\n state,\n state.batchSellTrades?.fee?.asset?.assetId,\n ),\n ],\n (feeAmount, feeAsset, exchangeRate) => {\n return feeAmount && feeAsset && exchangeRate\n ? calcBatchFees(feeAmount, feeAsset, exchangeRate)\n : undefined;\n },\n);\n\n/**\n * Selects the batch transactions and fees for a batch of quotes\n *\n * @param state - The state of the bridge controller and its dependency controllers\n * @returns The total transaction fees and whether the batch sell trades are submittable.\n *\n * @example\n * ```ts\n * const { totalNetworkFee, isBatchSellTradeAvailable } = useSelector(state => selectBatchSellTrades(state.metamask));\n * ```\n */\nexport const selectBatchSellTrades = createBridgeSelector(\n [\n (state) => state.batchSellTradesLoadingStatus === RequestStatus.FETCHED,\n (state) => state.batchSellTrades,\n selectBatchSellFees,\n (state) => state.batchSellTradesLoadingStatus === RequestStatus.LOADING,\n ],\n (isBatchSellTradeAvailable, batchSellTrades, batchFees, isLoading) => {\n return {\n totalNetworkFee: batchFees,\n /**\n * Whether the batch sell trades have been fetched and transactions are ready to be submitted\n */\n isBatchSellTradeAvailable:\n isBatchSellTradeAvailable &&\n Boolean(batchSellTrades?.transactions?.length),\n isLoading,\n };\n },\n);\n\nexport const selectMinimumBalanceForRentExemptionInSOL = (\n state: BridgeAppState,\n) =>\n new BigNumber(state.minimumBalanceForRentExemptionInLamports ?? 0)\n .div(10 ** 9)\n .toString();\n\nexport const selectTokenWarnings = (state: BridgeAppState) =>\n state.tokenWarnings;\n\nexport const selectDefaultSlippagePercentage = createBridgeSelector(\n [\n (state) => selectBridgeFeatureFlags(state).chains,\n (_, slippageParams: Parameters<typeof getDefaultSlippagePercentage>[0]) =>\n slippageParams.srcTokenAddress,\n (_, slippageParams: Parameters<typeof getDefaultSlippagePercentage>[0]) =>\n slippageParams.destTokenAddress,\n (_, slippageParams: Parameters<typeof getDefaultSlippagePercentage>[0]) =>\n slippageParams.srcChainId\n ? formatChainIdToCaip(slippageParams.srcChainId)\n : undefined,\n (_, slippageParams: Parameters<typeof getDefaultSlippagePercentage>[0]) =>\n slippageParams.destChainId\n ? formatChainIdToCaip(slippageParams.destChainId)\n : undefined,\n ],\n (\n featureFlagsByChain,\n srcTokenAddress,\n destTokenAddress,\n srcChainId,\n destChainId,\n ) => {\n return getDefaultSlippagePercentage(\n {\n srcTokenAddress,\n destTokenAddress,\n srcChainId,\n destChainId,\n },\n srcChainId ? featureFlagsByChain[srcChainId]?.stablecoins : undefined,\n destChainId ? featureFlagsByChain[destChainId]?.stablecoins : undefined,\n );\n },\n);\n"]}