@metamask/bridge-controller 41.2.0 → 41.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"bridge-controller.mjs","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,QAAQ,EAAE,iCAAiC;AACpD,OAAO,EAAE,YAAY,EAAE,iCAAiC;AAGxD,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AAEvD,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAG/E,OAAO,EAAE,WAAW,EAAY,wBAAwB;AAExD,OAAO,EAEL,sBAAsB,EACtB,wBAAwB,EACxB,+BAA+B,EAC/B,+BAA+B,EAC/B,mBAAmB,EACpB,+BAA2B;AAC5B,OAAO,EAAE,SAAS,EAAE,+BAA2B;AAC/C,OAAO,EAAE,SAAS,EAAE,+BAA2B;AAC/C,OAAO,EAAE,gCAAgC,EAAE,wBAAoB;AAE/D,OAAO,EASL,aAAa,EACd,oBAAgB;AACjB,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,2BAAuB;AACtE,OAAO,EAAE,oBAAoB,EAAE,4BAAwB;AACvD,OAAO,EACL,+BAA+B,EAC/B,YAAY,EACZ,eAAe,EACf,QAAQ,EACT,2BAAuB;AACxB,OAAO,EACL,4BAA4B,EAC5B,mBAAmB,EACnB,kBAAkB,EACnB,oCAAgC;AACjC,OAAO,EAAE,qBAAqB,EAAE,kCAA8B;AAC9D,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,0BAAsB;AACpE,OAAO,EACL,WAAW,EACX,iBAAiB,EACjB,0BAA0B,EAC3B,sCAAkC;AACnC,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,EACpB,gBAAgB,EAChB,gBAAgB,EAChB,yBAAyB,EACzB,2BAA2B,EAC5B,uCAAmC;AAQpC,OAAO,EAAE,mBAAm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IAAI,CAC9B,iDAAiD,CAClD,CAAC;AACJ,CAAC;IAGC,MAAM,EAAE,uBAAuB,EAAE,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC3D,4BAA4B,CAC7B,CAAC;IACF,sEAAsE;IACtE,OAAO,uBAAuB,CAAC;AACjC,CAAC;IAGC,MAAM,uBAAuB,GAAG,uBAAA,IAAI,iFAA4B,MAAhC,IAAI,CAA8B,CAAC;IACnE,MAAM,aAAa,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,wCAAwC,EACxC,uBAAuB,CACxB,CAAC;IACF,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import type { 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 { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type { NetworkClientId } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { TransactionController } from '@metamask/transaction-controller';\nimport type { CaipAssetType } from '@metamask/utils';\nimport { numberToHex, type Hex } from '@metamask/utils';\n\nimport {\n type BridgeClientId,\n BRIDGE_CONTROLLER_NAME,\n BRIDGE_PROD_API_BASE_URL,\n DEFAULT_BRIDGE_CONTROLLER_STATE,\n METABRIDGE_CHAIN_TO_ADDRESS_MAP,\n REFRESH_INTERVAL_MS,\n} from './constants/bridge';\nimport { CHAIN_IDS } from './constants/chains';\nimport { TraceName } from './constants/traces';\nimport { selectIsAssetExchangeRateInState } from './selectors';\nimport type { QuoteRequest } from './types';\nimport {\n type L1GasFees,\n type GenericQuoteRequest,\n type SolanaFees,\n type QuoteResponse,\n type TxData,\n type BridgeControllerState,\n type BridgeControllerMessenger,\n type FetchFunction,\n RequestStatus,\n} from './types';\nimport { getAssetIdsForToken, toExchangeRates } from './utils/assets';\nimport { hasSufficientBalance } from './utils/balance';\nimport {\n getDefaultBridgeControllerState,\n isCrossChain,\n isSolanaChainId,\n sumHexes,\n} from './utils/bridge';\nimport {\n formatAddressToCaipReference,\n formatChainIdToCaip,\n formatChainIdToHex,\n} from './utils/caip-formatters';\nimport { getBridgeFeatureFlags } from './utils/feature-flags';\nimport { fetchAssetPrices, fetchBridgeQuotes } from './utils/fetch';\nimport {\n AbortReason,\n MetricsActionType,\n UnifiedSwapBridgeEventName,\n} from './utils/metrics/constants';\nimport {\n formatProviderLabel,\n getRequestParams,\n getSwapTypeFromQuote,\n isCustomSlippage,\n isHardwareWallet,\n toInputChangedPropertyKey,\n toInputChangedPropertyValue,\n} from './utils/metrics/properties';\nimport type {\n QuoteFetchData,\n RequestMetadata,\n RequestParams,\n RequiredEventContextFromClient,\n} from './utils/metrics/types';\nimport { type CrossChainSwapsEventProperties } from './utils/metrics/types';\nimport { isValidQuoteRequest } from './utils/quote';\nimport {\n getFeeForTransactionRequest,\n getMinimumBalanceForRentExemptionRequest,\n} from './utils/snaps';\nimport { FeatureId } from './utils/validators';\n\nconst metadata: StateMetadata<BridgeControllerState> = {\n quoteRequest: {\n persist: false,\n anonymous: false,\n },\n quotes: {\n persist: false,\n anonymous: false,\n },\n quotesInitialLoadTime: {\n persist: false,\n anonymous: false,\n },\n quotesLastFetched: {\n persist: false,\n anonymous: false,\n },\n quotesLoadingStatus: {\n persist: false,\n anonymous: false,\n },\n quoteFetchError: {\n persist: false,\n anonymous: false,\n },\n quotesRefreshCount: {\n persist: false,\n anonymous: false,\n },\n assetExchangeRates: {\n persist: false,\n anonymous: false,\n },\n minimumBalanceForRentExemptionInLamports: {\n persist: false,\n anonymous: false,\n },\n};\n\n/**\n * The input to start polling for the {@link BridgeController}\n *\n * @param networkClientId - The network client ID of the selected network\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 networkClientId: NetworkClientId;\n updatedQuoteRequest: GenericQuoteRequest;\n context: Pick<\n RequiredEventContextFromClient,\n UnifiedSwapBridgeEventName.QuoteError\n >[UnifiedSwapBridgeEventName.QuoteError] &\n Pick<\n RequiredEventContextFromClient,\n UnifiedSwapBridgeEventName.QuotesRequested\n >[UnifiedSwapBridgeEventName.QuotesRequested];\n};\n\nexport class BridgeController extends StaticIntervalPollingController<BridgePollingInput>()<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState,\n BridgeControllerMessenger\n> {\n #abortController: AbortController | undefined;\n\n #quotesFirstFetched: number | undefined;\n\n readonly #clientId: string;\n\n readonly #getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n\n readonly #fetchFn: FetchFunction;\n\n readonly #trackMetaMetricsFn: <\n T extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: T,\n properties: CrossChainSwapsEventProperties<T>,\n ) => void;\n\n readonly #trace: TraceCallback;\n\n readonly #config: {\n customBridgeApiBaseUrl?: string;\n };\n\n constructor({\n messenger,\n state,\n clientId,\n getLayer1GasFee,\n fetchFn,\n config,\n trackMetaMetricsFn,\n traceFn,\n }: {\n messenger: BridgeControllerMessenger;\n state?: Partial<BridgeControllerState>;\n clientId: BridgeClientId;\n getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n fetchFn: FetchFunction;\n config?: {\n customBridgeApiBaseUrl?: string;\n };\n trackMetaMetricsFn: <\n T extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: T,\n properties: CrossChainSwapsEventProperties<T>,\n ) => void;\n traceFn?: TraceCallback;\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.#fetchFn = fetchFn;\n this.#trackMetaMetricsFn = trackMetaMetricsFn;\n this.#config = config ?? {};\n this.#trace = traceFn ?? (((_request, fn) => fn?.()) as TraceCallback);\n\n // Register action handlers\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:setChainIntervalLength`,\n this.setChainIntervalLength.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:updateBridgeQuoteRequestParams`,\n this.updateBridgeQuoteRequestParams.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:resetState`,\n this.resetState.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:getBridgeERC20Allowance`,\n this.getBridgeERC20Allowance.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:trackUnifiedSwapBridgeEvent`,\n this.trackUnifiedSwapBridgeEvent.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:stopPollingForQuotes`,\n this.stopPollingForQuotes.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:fetchQuotes`,\n this.fetchQuotes.bind(this),\n );\n }\n\n _executePoll = async (pollingInput: BridgePollingInput) => {\n await this.#fetchBridgeQuotes(pollingInput);\n };\n\n updateBridgeQuoteRequestParams = async (\n paramsToUpdate: Partial<GenericQuoteRequest>,\n context: BridgePollingInput['context'],\n ) => {\n this.stopAllPolling();\n this.#abortController?.abort(AbortReason.QuoteRequestUpdated);\n\n this.#trackInputChangedEvents(paramsToUpdate);\n\n const updatedQuoteRequest = {\n ...DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest,\n ...paramsToUpdate,\n };\n\n this.update((state) => {\n state.quoteRequest = updatedQuoteRequest;\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.quotesInitialLoadTime =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesInitialLoadTime;\n // Reset required minimum balance if the source chain is not Solana\n if (\n updatedQuoteRequest.srcChainId &&\n !isSolanaChainId(updatedQuoteRequest.srcChainId)\n ) {\n state.minimumBalanceForRentExemptionInLamports =\n DEFAULT_BRIDGE_CONTROLLER_STATE.minimumBalanceForRentExemptionInLamports;\n }\n });\n\n await this.#fetchAssetExchangeRates(updatedQuoteRequest).catch((error) =>\n console.warn('Failed to fetch asset exchange rates', error),\n );\n\n if (isValidQuoteRequest(updatedQuoteRequest)) {\n this.#quotesFirstFetched = Date.now();\n const providerConfig = this.#getSelectedNetworkClient()?.configuration;\n\n let insufficientBal: boolean | undefined;\n if (isSolanaChainId(updatedQuoteRequest.srcChainId)) {\n // If the source chain is not an EVM network, use value from params\n insufficientBal = paramsToUpdate.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 // Otherwise query the src token balance from the RPC provider\n insufficientBal =\n paramsToUpdate.insufficientBal ??\n !(await this.#hasSufficientBalance(updatedQuoteRequest));\n }\n\n const networkClientId = this.#getSelectedNetworkClientId();\n // Set refresh rate based on the source chain before starting polling\n this.setChainIntervalLength();\n this.startPolling({\n networkClientId,\n updatedQuoteRequest: {\n ...updatedQuoteRequest,\n insufficientBal,\n },\n context,\n });\n }\n };\n\n /**\n * Fetches quotes for specified request without updating the controller state\n * This method does not start polling for quotes and does not emit UnifiedSwapBridge events\n *\n * @param quoteRequest - The parameters for quote requests to fetch\n * @param abortSignal - The abort signal to cancel all the requests\n * @param featureId - The feature ID that maps to quoteParam overrides from LD\n * @returns A list of validated quotes\n */\n fetchQuotes = async (\n quoteRequest: GenericQuoteRequest,\n abortSignal: AbortSignal | null = null,\n featureId: FeatureId | null = null,\n ): Promise<QuoteResponse[]> => {\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messagingSystem);\n // If featureId is specified, retrieve the quoteRequestOverrides for that featureId\n const quoteRequestOverrides = featureId\n ? bridgeFeatureFlags.quoteRequestOverrides?.[featureId]\n : undefined;\n\n // If quoteRequestOverrides is specified, merge it with the quoteRequest\n const baseQuotes = await fetchBridgeQuotes(\n quoteRequestOverrides\n ? { ...quoteRequest, ...quoteRequestOverrides }\n : quoteRequest,\n abortSignal,\n this.#clientId,\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n );\n const quotesWithL1GasFees = await this.#appendL1GasFees(baseQuotes);\n const quotesWithSolanaFees = await this.#appendSolanaFees(baseQuotes);\n const quotesWithFees =\n quotesWithL1GasFees ?? quotesWithSolanaFees ?? baseQuotes;\n // Sort perps quotes by increasing estimated processing time (fastest first)\n if (featureId === FeatureId.PERPS) {\n return quotesWithFees.sort((a, b) => {\n return (\n a.estimatedProcessingTimeInSeconds -\n b.estimatedProcessingTimeInSeconds\n );\n });\n }\n return quotesWithFees;\n };\n\n readonly #getExchangeRateSources = () => {\n return {\n ...this.messagingSystem.call('MultichainAssetsRatesController:getState'),\n ...this.messagingSystem.call('CurrencyRateController:getState'),\n ...this.messagingSystem.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 quoteRequest - The quote request\n * @param quoteRequest.srcChainId - The source chain ID\n * @param quoteRequest.srcTokenAddress - The source token address\n * @param quoteRequest.destChainId - The destination chain ID\n * @param quoteRequest.destTokenAddress - The destination token address\n */\n readonly #fetchAssetExchangeRates = async ({\n srcChainId,\n srcTokenAddress,\n destChainId,\n destTokenAddress,\n }: Partial<GenericQuoteRequest>) => {\n const assetIds: Set<CaipAssetType> = new Set([]);\n const exchangeRateSources = this.#getExchangeRateSources();\n if (\n srcTokenAddress &&\n srcChainId &&\n !selectIsAssetExchangeRateInState(\n exchangeRateSources,\n srcChainId,\n srcTokenAddress,\n )\n ) {\n getAssetIdsForToken(srcTokenAddress, srcChainId).forEach((assetId) =>\n assetIds.add(assetId),\n );\n }\n if (\n destTokenAddress &&\n destChainId &&\n !selectIsAssetExchangeRateInState(\n exchangeRateSources,\n destChainId,\n destTokenAddress,\n )\n ) {\n getAssetIdsForToken(destTokenAddress, destChainId).forEach((assetId) =>\n assetIds.add(assetId),\n );\n }\n\n const currency = this.messagingSystem.call(\n 'CurrencyRateController:getState',\n ).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 fetchFn: this.#fetchFn,\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 #hasSufficientBalance = async (\n quoteRequest: GenericQuoteRequest,\n ) => {\n const walletAddress = this.#getMultichainSelectedAccount()?.address;\n const srcChainIdInHex = formatChainIdToHex(quoteRequest.srcChainId);\n const provider = this.#getSelectedNetworkClient()?.provider;\n const normalizedSrcTokenAddress = formatAddressToCaipReference(\n quoteRequest.srcTokenAddress,\n );\n\n return (\n provider &&\n walletAddress &&\n normalizedSrcTokenAddress &&\n quoteRequest.srcTokenAmount &&\n srcChainIdInHex &&\n (await hasSufficientBalance(\n provider,\n walletAddress,\n normalizedSrcTokenAddress,\n quoteRequest.srcTokenAmount,\n srcChainIdInHex,\n ))\n );\n };\n\n stopPollingForQuotes = (reason?: AbortReason) => {\n this.stopAllPolling();\n this.#abortController?.abort(reason);\n };\n\n resetState = () => {\n this.stopPollingForQuotes(AbortReason.ResetState);\n\n this.update((state) => {\n // Cannot do direct assignment to state, i.e. state = {... }, need to manually assign each field\n state.quoteRequest = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest;\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 });\n };\n\n /**\n * Sets the interval length based on the source chain\n */\n setChainIntervalLength = () => {\n const { state } = this;\n const { srcChainId } = state.quoteRequest;\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messagingSystem);\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 networkClientId: _networkClientId,\n updatedQuoteRequest,\n context,\n }: BridgePollingInput) => {\n this.#abortController?.abort('New quote request');\n this.#abortController = new AbortController();\n\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesRequested,\n context,\n );\n this.update((state) => {\n state.quotesLoadingStatus = RequestStatus.LOADING;\n state.quoteRequest = updatedQuoteRequest;\n state.quoteFetchError = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteFetchError;\n });\n\n try {\n await this.#trace(\n {\n name: isCrossChain(\n updatedQuoteRequest.srcChainId,\n updatedQuoteRequest.destChainId,\n )\n ? TraceName.BridgeQuotesFetched\n : TraceName.SwapQuotesFetched,\n data: {\n srcChainId: formatChainIdToCaip(updatedQuoteRequest.srcChainId),\n destChainId: formatChainIdToCaip(updatedQuoteRequest.destChainId),\n },\n },\n async () => {\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 updatedQuoteRequest.srcChainId,\n );\n const quotes = await this.fetchQuotes(\n updatedQuoteRequest,\n // AbortController is always defined by this line, because we assign it a few lines above,\n // not sure why Jest thinks it's not\n // Linters accurately say that it's defined\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.#abortController!.signal as AbortSignal,\n );\n\n this.update((state) => {\n state.quotes = quotes;\n state.quotesLoadingStatus = RequestStatus.FETCHED;\n });\n },\n );\n } catch (error) {\n const isAbortError = (error as Error).name === 'AbortError';\n if (\n isAbortError ||\n [\n AbortReason.ResetState,\n AbortReason.NewQuoteRequest,\n AbortReason.QuoteRequestUpdated,\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 state.quoteFetchError =\n error instanceof Error ? error.message : (error?.toString() ?? null);\n state.quotesLoadingStatus = RequestStatus.ERROR;\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n });\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuoteError,\n context,\n );\n console.log('Failed to fetch bridge quotes', error);\n }\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messagingSystem);\n const { maxRefreshCount } = bridgeFeatureFlags;\n\n // Stop polling if the maximum number of refreshes has been reached\n if (\n updatedQuoteRequest.insufficientBal ||\n (!updatedQuoteRequest.insufficientBal &&\n this.state.quotesRefreshCount >= maxRefreshCount)\n ) {\n this.stopAllPolling();\n }\n\n // Update quote fetching stats\n const quotesLastFetched = Date.now();\n this.update((state) => {\n state.quotesInitialLoadTime =\n state.quotesRefreshCount === 0 && this.#quotesFirstFetched\n ? quotesLastFetched - this.#quotesFirstFetched\n : this.state.quotesInitialLoadTime;\n state.quotesLastFetched = quotesLastFetched;\n state.quotesRefreshCount += 1;\n });\n };\n\n readonly #appendL1GasFees = async (\n quotes: QuoteResponse[],\n ): Promise<(QuoteResponse & L1GasFees)[] | undefined> => {\n // Indicates whether some of the quotes are not for optimism or base\n const hasInvalidQuotes = quotes.some(({ quote }) => {\n const chainId = formatChainIdToCaip(quote.srcChainId);\n return ![CHAIN_IDS.OPTIMISM, CHAIN_IDS.BASE]\n .map(formatChainIdToCaip)\n .includes(chainId);\n });\n\n // Only append L1 gas fees if all quotes are for either optimism or base\n if (hasInvalidQuotes) {\n return undefined;\n }\n\n const l1GasFeePromises = Promise.allSettled(\n quotes.map(async (quoteResponse) => {\n const { quote, trade, approval } = quoteResponse;\n const chainId = numberToHex(quote.srcChainId);\n\n const getTxParams = (txData: TxData) => ({\n from: txData.from,\n to: txData.to,\n value: txData.value,\n data: txData.data,\n gasLimit: txData.gasLimit?.toString(),\n });\n const approvalL1GasFees = approval\n ? await this.#getLayer1GasFee({\n transactionParams: getTxParams(approval),\n chainId,\n })\n : '0x0';\n const tradeL1GasFees = await this.#getLayer1GasFee({\n transactionParams: getTxParams(trade),\n chainId,\n });\n\n if (approvalL1GasFees === undefined || tradeL1GasFees === undefined) {\n return undefined;\n }\n\n return {\n ...quoteResponse,\n l1GasFeesInHexWei: sumHexes(approvalL1GasFees, tradeL1GasFees),\n };\n }),\n );\n\n const quotesWithL1GasFees = (await l1GasFeePromises).reduce<\n (QuoteResponse & L1GasFees)[]\n >((acc, result) => {\n if (result.status === 'fulfilled' && result.value) {\n acc.push(result.value);\n } else if (result.status === 'rejected') {\n console.error('Error calculating L1 gas fees for quote', result.reason);\n }\n return acc;\n }, []);\n\n return quotesWithL1GasFees;\n };\n\n readonly #setMinimumBalanceForRentExemptionInLamports = (\n srcChainId: GenericQuoteRequest['srcChainId'],\n ): Promise<void> | undefined => {\n const selectedAccount = this.#getMultichainSelectedAccount();\n\n return isSolanaChainId(srcChainId) && selectedAccount?.metadata?.snap?.id\n ? this.messagingSystem\n .call(\n 'SnapController:handleRequest',\n getMinimumBalanceForRentExemptionRequest(\n selectedAccount.metadata.snap?.id,\n ),\n ) // eslint-disable-next-line promise/always-return\n .then((result) => {\n this.update((state) => {\n state.minimumBalanceForRentExemptionInLamports = String(result);\n });\n })\n .catch((error) => {\n console.error(\n 'Error setting minimum balance for rent exemption',\n error,\n );\n this.update((state) => {\n state.minimumBalanceForRentExemptionInLamports =\n DEFAULT_BRIDGE_CONTROLLER_STATE.minimumBalanceForRentExemptionInLamports;\n });\n })\n : undefined;\n };\n\n readonly #appendSolanaFees = async (\n quotes: QuoteResponse[],\n ): Promise<(QuoteResponse & SolanaFees)[] | undefined> => {\n // Return early if some of the quotes are not for solana\n if (\n quotes.some(({ quote: { srcChainId } }) => !isSolanaChainId(srcChainId))\n ) {\n return undefined;\n }\n\n const solanaFeePromises = Promise.allSettled(\n quotes.map(async (quoteResponse) => {\n const { trade } = quoteResponse;\n const selectedAccount = this.#getMultichainSelectedAccount();\n\n if (selectedAccount?.metadata?.snap?.id && typeof trade === 'string') {\n const { value: fees } = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n getFeeForTransactionRequest(\n selectedAccount.metadata.snap?.id,\n trade,\n ),\n )) as { value: string };\n\n return {\n ...quoteResponse,\n solanaFeesInLamports: fees,\n };\n }\n return quoteResponse;\n }),\n );\n\n const quotesWithSolanaFees = (await solanaFeePromises).reduce<\n (QuoteResponse & SolanaFees)[]\n >((acc, result) => {\n if (result.status === 'fulfilled' && result.value) {\n acc.push(result.value);\n } else if (result.status === 'rejected') {\n console.error('Error calculating solana fees for quote', result.reason);\n }\n return acc;\n }, []);\n\n return quotesWithSolanaFees;\n };\n\n #getMultichainSelectedAccount() {\n return this.messagingSystem.call(\n 'AccountsController:getSelectedMultichainAccount',\n );\n }\n\n #getSelectedNetworkClientId() {\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n // console.log('===selectedNetworkClientId', selectedNetworkClientId);\n return selectedNetworkClientId;\n }\n\n #getSelectedNetworkClient() {\n const selectedNetworkClientId = this.#getSelectedNetworkClientId();\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n return networkClient;\n }\n\n readonly #getRequestParams = (): Omit<\n RequestParams,\n 'token_symbol_source' | 'token_symbol_destination'\n > => {\n const srcChainIdCaip = formatChainIdToCaip(\n this.state.quoteRequest.srcChainId ||\n this.#getSelectedNetworkClient().configuration.chainId,\n );\n return getRequestParams(this.state.quoteRequest, srcChainIdCaip);\n };\n\n readonly #getRequestMetadata = (): Omit<\n RequestMetadata,\n 'stx_enabled' | 'usd_amount_source' | 'security_warnings'\n > => {\n return {\n slippage_limit: this.state.quoteRequest.slippage,\n swap_type: getSwapTypeFromQuote(this.state.quoteRequest),\n is_hardware_wallet: isHardwareWallet(\n this.#getMultichainSelectedAccount(),\n ),\n custom_slippage: isCustomSlippage(this.state.quoteRequest.slippage),\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 };\n };\n\n readonly #getEventProperties = <\n T extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: T,\n propertiesFromClient: Pick<RequiredEventContextFromClient, T>[T],\n ): CrossChainSwapsEventProperties<T> => {\n const baseProperties = {\n ...propertiesFromClient,\n action_type: MetricsActionType.SWAPBRIDGE_V1,\n };\n switch (eventName) {\n case UnifiedSwapBridgeEventName.ButtonClicked:\n case UnifiedSwapBridgeEventName.PageViewed:\n return {\n ...this.#getRequestParams(),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesReceived:\n return {\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n refresh_count: this.state.quotesRefreshCount,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesRequested:\n return {\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n has_sufficient_funds: !this.state.quoteRequest.insufficientBal,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuoteError:\n return {\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n error_message: this.state.quoteFetchError,\n has_sufficient_funds: !this.state.quoteRequest.insufficientBal,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.AllQuotesOpened:\n case UnifiedSwapBridgeEventName.AllQuotesSorted:\n case UnifiedSwapBridgeEventName.QuoteSelected:\n return {\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.SnapConfirmationViewed:\n return {\n ...baseProperties,\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n };\n case UnifiedSwapBridgeEventName.Failed: {\n // Populate the properties that the error occurred before the tx was submitted\n return {\n ...baseProperties,\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n ...propertiesFromClient,\n };\n }\n case UnifiedSwapBridgeEventName.AssetDetailTooltipClicked:\n return baseProperties;\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 ) => {\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 value !== this.state.quoteRequest[key as keyof GenericQuoteRequest]\n ) {\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.InputChanged,\n {\n input: inputKey,\n input_value: inputValue,\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 * @example\n * this.trackUnifiedSwapBridgeEvent(UnifiedSwapBridgeEventName.ActionOpened, {\n * location: MetaMetricsSwapsEventSource.MainView,\n * });\n */\n trackUnifiedSwapBridgeEvent = <\n T extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: T,\n propertiesFromClient: Pick<RequiredEventContextFromClient, T>[T],\n ) => {\n try {\n const combinedPropertiesForEvent = this.#getEventProperties<T>(\n eventName,\n propertiesFromClient,\n );\n\n this.#trackMetaMetricsFn(eventName, combinedPropertiesForEvent);\n } catch (error) {\n console.error(\n 'Error tracking cross-chain swaps MetaMetrics event',\n error,\n );\n }\n };\n\n /**\n *\n * @param contractAddress - The address of the ERC20 token contract\n * @param chainId - The hex chain ID of the bridge network\n * @returns The atomic allowance of the ERC20 token contract\n */\n getBridgeERC20Allowance = async (\n contractAddress: string,\n chainId: Hex,\n ): Promise<string> => {\n const provider = this.#getSelectedNetworkClient()?.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 { address: walletAddress } =\n this.#getMultichainSelectedAccount() ?? {};\n const allowance: BigNumber = await contract.allowance(\n walletAddress,\n METABRIDGE_CHAIN_TO_ADDRESS_MAP[chainId],\n );\n return allowance.toString();\n };\n}\n"]}
1
+ {"version":3,"file":"bridge-controller.mjs","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,QAAQ,EAAE,iCAAiC;AACpD,OAAO,EAAE,YAAY,EAAE,iCAAiC;AAGxD,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AAEvD,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAG/E,OAAO,EAAE,WAAW,EAAY,wBAAwB;AAExD,OAAO,EAEL,sBAAsB,EACtB,wBAAwB,EACxB,+BAA+B,EAC/B,+BAA+B,EAC/B,mBAAmB,EACpB,+BAA2B;AAC5B,OAAO,EAAE,SAAS,EAAE,+BAA2B;AAC/C,OAAO,EAAE,SAAS,EAAE,+BAA2B;AAC/C,OAAO,EAAE,gCAAgC,EAAE,wBAAoB;AAE/D,OAAO,EASL,aAAa,EACd,oBAAgB;AACjB,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,2BAAuB;AACtE,OAAO,EAAE,oBAAoB,EAAE,4BAAwB;AACvD,OAAO,EACL,+BAA+B,EAC/B,YAAY,EACZ,eAAe,EACf,QAAQ,EACT,2BAAuB;AACxB,OAAO,EACL,4BAA4B,EAC5B,mBAAmB,EACnB,kBAAkB,EACnB,oCAAgC;AACjC,OAAO,EAAE,qBAAqB,EAAE,kCAA8B;AAC9D,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,0BAAsB;AACpE,OAAO,EACL,WAAW,EACX,iBAAiB,EACjB,0BAA0B,EAC3B,sCAAkC;AACnC,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,EACpB,gBAAgB,EAChB,gBAAgB,EAChB,yBAAyB,EACzB,2BAA2B,EAC5B,uCAAmC;AAQpC,OAAO,EAAE,mBAAmB,EAAE,0BAAsB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,CAAC,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CACxC,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,sBAAsB,8BAA8B,EACvD,IAAI,CAAC,2BAA2B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC5C,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,sBAAsB,uBAAuB,EAChD,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,CACrC,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,sBAAsB,cAAc,EACvC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAC5B,CAAC;IACJ,CAAC;CAyvBF;;IAnOG,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAC9B,iDAAiD,CAClD,CAAC;AACJ,CAAC;IAGC,MAAM,EAAE,uBAAuB,EAAE,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC3D,4BAA4B,CAC7B,CAAC;IACF,sEAAsE;IACtE,OAAO,uBAAuB,CAAC;AACjC,CAAC;IAGC,MAAM,uBAAuB,GAAG,uBAAA,IAAI,iFAA4B,MAAhC,IAAI,CAA8B,CAAC;IACnE,MAAM,aAAa,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,wCAAwC,EACxC,uBAAuB,CACxB,CAAC;IACF,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import type { 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 { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type { NetworkClientId } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { TransactionController } from '@metamask/transaction-controller';\nimport type { CaipAssetType } from '@metamask/utils';\nimport { numberToHex, type Hex } from '@metamask/utils';\n\nimport {\n type BridgeClientId,\n BRIDGE_CONTROLLER_NAME,\n BRIDGE_PROD_API_BASE_URL,\n DEFAULT_BRIDGE_CONTROLLER_STATE,\n METABRIDGE_CHAIN_TO_ADDRESS_MAP,\n REFRESH_INTERVAL_MS,\n} from './constants/bridge';\nimport { CHAIN_IDS } from './constants/chains';\nimport { TraceName } from './constants/traces';\nimport { selectIsAssetExchangeRateInState } from './selectors';\nimport type { QuoteRequest } from './types';\nimport {\n type L1GasFees,\n type GenericQuoteRequest,\n type SolanaFees,\n type QuoteResponse,\n type TxData,\n type BridgeControllerState,\n type BridgeControllerMessenger,\n type FetchFunction,\n RequestStatus,\n} from './types';\nimport { getAssetIdsForToken, toExchangeRates } from './utils/assets';\nimport { hasSufficientBalance } from './utils/balance';\nimport {\n getDefaultBridgeControllerState,\n isCrossChain,\n isSolanaChainId,\n sumHexes,\n} from './utils/bridge';\nimport {\n formatAddressToCaipReference,\n formatChainIdToCaip,\n formatChainIdToHex,\n} from './utils/caip-formatters';\nimport { getBridgeFeatureFlags } from './utils/feature-flags';\nimport { fetchAssetPrices, fetchBridgeQuotes } from './utils/fetch';\nimport {\n AbortReason,\n MetricsActionType,\n UnifiedSwapBridgeEventName,\n} from './utils/metrics/constants';\nimport {\n formatProviderLabel,\n getRequestParams,\n getSwapTypeFromQuote,\n isCustomSlippage,\n isHardwareWallet,\n toInputChangedPropertyKey,\n toInputChangedPropertyValue,\n} from './utils/metrics/properties';\nimport type {\n QuoteFetchData,\n RequestMetadata,\n RequestParams,\n RequiredEventContextFromClient,\n} from './utils/metrics/types';\nimport { type CrossChainSwapsEventProperties } from './utils/metrics/types';\nimport { isValidQuoteRequest } from './utils/quote';\nimport {\n getFeeForTransactionRequest,\n getMinimumBalanceForRentExemptionRequest,\n} from './utils/snaps';\nimport { FeatureId } from './utils/validators';\n\nconst metadata: StateMetadata<BridgeControllerState> = {\n quoteRequest: {\n persist: false,\n anonymous: false,\n },\n quotes: {\n persist: false,\n anonymous: false,\n },\n quotesInitialLoadTime: {\n persist: false,\n anonymous: false,\n },\n quotesLastFetched: {\n persist: false,\n anonymous: false,\n },\n quotesLoadingStatus: {\n persist: false,\n anonymous: false,\n },\n quoteFetchError: {\n persist: false,\n anonymous: false,\n },\n quotesRefreshCount: {\n persist: false,\n anonymous: false,\n },\n assetExchangeRates: {\n persist: false,\n anonymous: false,\n },\n minimumBalanceForRentExemptionInLamports: {\n persist: false,\n anonymous: false,\n },\n};\n\n/**\n * The input to start polling for the {@link BridgeController}\n *\n * @param networkClientId - The network client ID of the selected network\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 networkClientId: NetworkClientId;\n updatedQuoteRequest: GenericQuoteRequest;\n context: Pick<\n RequiredEventContextFromClient,\n UnifiedSwapBridgeEventName.QuoteError\n >[UnifiedSwapBridgeEventName.QuoteError] &\n Pick<\n RequiredEventContextFromClient,\n UnifiedSwapBridgeEventName.QuotesRequested\n >[UnifiedSwapBridgeEventName.QuotesRequested];\n};\n\nexport class BridgeController extends StaticIntervalPollingController<BridgePollingInput>()<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState,\n BridgeControllerMessenger\n> {\n #abortController: AbortController | undefined;\n\n #quotesFirstFetched: number | undefined;\n\n readonly #clientId: string;\n\n readonly #getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n\n readonly #fetchFn: FetchFunction;\n\n readonly #trackMetaMetricsFn: <\n T extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: T,\n properties: CrossChainSwapsEventProperties<T>,\n ) => void;\n\n readonly #trace: TraceCallback;\n\n readonly #config: {\n customBridgeApiBaseUrl?: string;\n };\n\n constructor({\n messenger,\n state,\n clientId,\n getLayer1GasFee,\n fetchFn,\n config,\n trackMetaMetricsFn,\n traceFn,\n }: {\n messenger: BridgeControllerMessenger;\n state?: Partial<BridgeControllerState>;\n clientId: BridgeClientId;\n getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n fetchFn: FetchFunction;\n config?: {\n customBridgeApiBaseUrl?: string;\n };\n trackMetaMetricsFn: <\n T extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: T,\n properties: CrossChainSwapsEventProperties<T>,\n ) => void;\n traceFn?: TraceCallback;\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.#fetchFn = fetchFn;\n this.#trackMetaMetricsFn = trackMetaMetricsFn;\n this.#config = config ?? {};\n this.#trace = traceFn ?? (((_request, fn) => fn?.()) as TraceCallback);\n\n // Register action handlers\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:setChainIntervalLength`,\n this.setChainIntervalLength.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:updateBridgeQuoteRequestParams`,\n this.updateBridgeQuoteRequestParams.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:resetState`,\n this.resetState.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:getBridgeERC20Allowance`,\n this.getBridgeERC20Allowance.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:trackUnifiedSwapBridgeEvent`,\n this.trackUnifiedSwapBridgeEvent.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:stopPollingForQuotes`,\n this.stopPollingForQuotes.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_CONTROLLER_NAME}:fetchQuotes`,\n this.fetchQuotes.bind(this),\n );\n }\n\n _executePoll = async (pollingInput: BridgePollingInput) => {\n await this.#fetchBridgeQuotes(pollingInput);\n };\n\n updateBridgeQuoteRequestParams = async (\n paramsToUpdate: Partial<GenericQuoteRequest>,\n context: BridgePollingInput['context'],\n ) => {\n this.stopAllPolling();\n this.#abortController?.abort(AbortReason.QuoteRequestUpdated);\n\n this.#trackInputChangedEvents(paramsToUpdate);\n\n const updatedQuoteRequest = {\n ...DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest,\n ...paramsToUpdate,\n };\n\n this.update((state) => {\n state.quoteRequest = updatedQuoteRequest;\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.quotesInitialLoadTime =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesInitialLoadTime;\n // Reset required minimum balance if the source chain is not Solana\n if (\n updatedQuoteRequest.srcChainId &&\n !isSolanaChainId(updatedQuoteRequest.srcChainId)\n ) {\n state.minimumBalanceForRentExemptionInLamports =\n DEFAULT_BRIDGE_CONTROLLER_STATE.minimumBalanceForRentExemptionInLamports;\n }\n });\n\n await this.#fetchAssetExchangeRates(updatedQuoteRequest).catch((error) =>\n console.warn('Failed to fetch asset exchange rates', error),\n );\n\n if (isValidQuoteRequest(updatedQuoteRequest)) {\n this.#quotesFirstFetched = Date.now();\n const providerConfig = this.#getSelectedNetworkClient()?.configuration;\n\n let insufficientBal: boolean | undefined;\n if (isSolanaChainId(updatedQuoteRequest.srcChainId)) {\n // If the source chain is not an EVM network, use value from params\n insufficientBal = paramsToUpdate.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 // Otherwise query the src token balance from the RPC provider\n insufficientBal =\n paramsToUpdate.insufficientBal ??\n !(await this.#hasSufficientBalance(updatedQuoteRequest));\n }\n\n const networkClientId = this.#getSelectedNetworkClientId();\n // Set refresh rate based on the source chain before starting polling\n this.setChainIntervalLength();\n this.startPolling({\n networkClientId,\n updatedQuoteRequest: {\n ...updatedQuoteRequest,\n insufficientBal,\n },\n context,\n });\n }\n };\n\n /**\n * Fetches quotes for specified request without updating the controller state\n * This method does not start polling for quotes and does not emit UnifiedSwapBridge events\n *\n * @param quoteRequest - The parameters for quote requests to fetch\n * @param abortSignal - The abort signal to cancel all the requests\n * @param featureId - The feature ID that maps to quoteParam overrides from LD\n * @returns A list of validated quotes\n */\n fetchQuotes = async (\n quoteRequest: GenericQuoteRequest,\n abortSignal: AbortSignal | null = null,\n featureId: FeatureId | null = null,\n ): Promise<QuoteResponse[]> => {\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messagingSystem);\n // If featureId is specified, retrieve the quoteRequestOverrides for that featureId\n const quoteRequestOverrides = featureId\n ? bridgeFeatureFlags.quoteRequestOverrides?.[featureId]\n : undefined;\n\n // If quoteRequestOverrides is specified, merge it with the quoteRequest\n const { quotes: baseQuotes, validationFailures } = await fetchBridgeQuotes(\n quoteRequestOverrides\n ? { ...quoteRequest, ...quoteRequestOverrides }\n : quoteRequest,\n abortSignal,\n this.#clientId,\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n );\n\n this.#trackResponseValidationFailures(validationFailures);\n\n const quotesWithL1GasFees = await this.#appendL1GasFees(baseQuotes);\n const quotesWithSolanaFees = await this.#appendSolanaFees(baseQuotes);\n const quotesWithFees =\n quotesWithL1GasFees ?? quotesWithSolanaFees ?? baseQuotes;\n // Sort perps quotes by increasing estimated processing time (fastest first)\n if (featureId === FeatureId.PERPS) {\n return quotesWithFees.sort((a, b) => {\n return (\n a.estimatedProcessingTimeInSeconds -\n b.estimatedProcessingTimeInSeconds\n );\n });\n }\n return quotesWithFees;\n };\n\n readonly #trackResponseValidationFailures = (\n validationFailures: string[],\n ) => {\n if (validationFailures.length === 0) {\n return;\n }\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesValidationFailed,\n {\n failures: validationFailures,\n },\n );\n };\n\n readonly #getExchangeRateSources = () => {\n return {\n ...this.messagingSystem.call('MultichainAssetsRatesController:getState'),\n ...this.messagingSystem.call('CurrencyRateController:getState'),\n ...this.messagingSystem.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 quoteRequest - The quote request\n * @param quoteRequest.srcChainId - The source chain ID\n * @param quoteRequest.srcTokenAddress - The source token address\n * @param quoteRequest.destChainId - The destination chain ID\n * @param quoteRequest.destTokenAddress - The destination token address\n */\n readonly #fetchAssetExchangeRates = async ({\n srcChainId,\n srcTokenAddress,\n destChainId,\n destTokenAddress,\n }: Partial<GenericQuoteRequest>) => {\n const assetIds: Set<CaipAssetType> = new Set([]);\n const exchangeRateSources = this.#getExchangeRateSources();\n if (\n srcTokenAddress &&\n srcChainId &&\n !selectIsAssetExchangeRateInState(\n exchangeRateSources,\n srcChainId,\n srcTokenAddress,\n )\n ) {\n getAssetIdsForToken(srcTokenAddress, srcChainId).forEach((assetId) =>\n assetIds.add(assetId),\n );\n }\n if (\n destTokenAddress &&\n destChainId &&\n !selectIsAssetExchangeRateInState(\n exchangeRateSources,\n destChainId,\n destTokenAddress,\n )\n ) {\n getAssetIdsForToken(destTokenAddress, destChainId).forEach((assetId) =>\n assetIds.add(assetId),\n );\n }\n\n const currency = this.messagingSystem.call(\n 'CurrencyRateController:getState',\n ).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 fetchFn: this.#fetchFn,\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 #hasSufficientBalance = async (\n quoteRequest: GenericQuoteRequest,\n ) => {\n const walletAddress = this.#getMultichainSelectedAccount()?.address;\n const srcChainIdInHex = formatChainIdToHex(quoteRequest.srcChainId);\n const provider = this.#getSelectedNetworkClient()?.provider;\n const normalizedSrcTokenAddress = formatAddressToCaipReference(\n quoteRequest.srcTokenAddress,\n );\n\n return (\n provider &&\n walletAddress &&\n normalizedSrcTokenAddress &&\n quoteRequest.srcTokenAmount &&\n srcChainIdInHex &&\n (await hasSufficientBalance(\n provider,\n walletAddress,\n normalizedSrcTokenAddress,\n quoteRequest.srcTokenAmount,\n srcChainIdInHex,\n ))\n );\n };\n\n stopPollingForQuotes = (reason?: AbortReason) => {\n this.stopAllPolling();\n this.#abortController?.abort(reason);\n };\n\n resetState = () => {\n this.stopPollingForQuotes(AbortReason.ResetState);\n\n this.update((state) => {\n // Cannot do direct assignment to state, i.e. state = {... }, need to manually assign each field\n state.quoteRequest = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest;\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 });\n };\n\n /**\n * Sets the interval length based on the source chain\n */\n setChainIntervalLength = () => {\n const { state } = this;\n const { srcChainId } = state.quoteRequest;\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messagingSystem);\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 networkClientId: _networkClientId,\n updatedQuoteRequest,\n context,\n }: BridgePollingInput) => {\n this.#abortController?.abort('New quote request');\n this.#abortController = new AbortController();\n\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesRequested,\n context,\n );\n this.update((state) => {\n state.quotesLoadingStatus = RequestStatus.LOADING;\n state.quoteRequest = updatedQuoteRequest;\n state.quoteFetchError = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteFetchError;\n });\n\n try {\n await this.#trace(\n {\n name: isCrossChain(\n updatedQuoteRequest.srcChainId,\n updatedQuoteRequest.destChainId,\n )\n ? TraceName.BridgeQuotesFetched\n : TraceName.SwapQuotesFetched,\n data: {\n srcChainId: formatChainIdToCaip(updatedQuoteRequest.srcChainId),\n destChainId: formatChainIdToCaip(updatedQuoteRequest.destChainId),\n },\n },\n async () => {\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 updatedQuoteRequest.srcChainId,\n );\n const quotes = await this.fetchQuotes(\n updatedQuoteRequest,\n // AbortController is always defined by this line, because we assign it a few lines above,\n // not sure why Jest thinks it's not\n // Linters accurately say that it's defined\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.#abortController!.signal as AbortSignal,\n );\n\n this.update((state) => {\n state.quotes = quotes;\n state.quotesLoadingStatus = RequestStatus.FETCHED;\n });\n },\n );\n } catch (error) {\n const isAbortError = (error as Error).name === 'AbortError';\n if (\n isAbortError ||\n [\n AbortReason.ResetState,\n AbortReason.NewQuoteRequest,\n AbortReason.QuoteRequestUpdated,\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 state.quoteFetchError =\n error instanceof Error ? error.message : (error?.toString() ?? null);\n state.quotesLoadingStatus = RequestStatus.ERROR;\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n });\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuoteError,\n context,\n );\n console.log('Failed to fetch bridge quotes', error);\n }\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messagingSystem);\n const { maxRefreshCount } = bridgeFeatureFlags;\n\n // Stop polling if the maximum number of refreshes has been reached\n if (\n updatedQuoteRequest.insufficientBal ||\n (!updatedQuoteRequest.insufficientBal &&\n this.state.quotesRefreshCount >= maxRefreshCount)\n ) {\n this.stopAllPolling();\n }\n\n // Update quote fetching stats\n const quotesLastFetched = Date.now();\n this.update((state) => {\n state.quotesInitialLoadTime =\n state.quotesRefreshCount === 0 && this.#quotesFirstFetched\n ? quotesLastFetched - this.#quotesFirstFetched\n : this.state.quotesInitialLoadTime;\n state.quotesLastFetched = quotesLastFetched;\n state.quotesRefreshCount += 1;\n });\n };\n\n readonly #appendL1GasFees = async (\n quotes: QuoteResponse[],\n ): Promise<(QuoteResponse & L1GasFees)[] | undefined> => {\n // Indicates whether some of the quotes are not for optimism or base\n const hasInvalidQuotes = quotes.some(({ quote }) => {\n const chainId = formatChainIdToCaip(quote.srcChainId);\n return ![CHAIN_IDS.OPTIMISM, CHAIN_IDS.BASE]\n .map(formatChainIdToCaip)\n .includes(chainId);\n });\n\n // Only append L1 gas fees if all quotes are for either optimism or base\n if (hasInvalidQuotes) {\n return undefined;\n }\n\n const l1GasFeePromises = Promise.allSettled(\n quotes.map(async (quoteResponse) => {\n const { quote, trade, approval } = quoteResponse;\n const chainId = numberToHex(quote.srcChainId);\n\n const getTxParams = (txData: TxData) => ({\n from: txData.from,\n to: txData.to,\n value: txData.value,\n data: txData.data,\n gasLimit: txData.gasLimit?.toString(),\n });\n const approvalL1GasFees = approval\n ? await this.#getLayer1GasFee({\n transactionParams: getTxParams(approval),\n chainId,\n })\n : '0x0';\n const tradeL1GasFees = await this.#getLayer1GasFee({\n transactionParams: getTxParams(trade),\n chainId,\n });\n\n if (approvalL1GasFees === undefined || tradeL1GasFees === undefined) {\n return undefined;\n }\n\n return {\n ...quoteResponse,\n l1GasFeesInHexWei: sumHexes(approvalL1GasFees, tradeL1GasFees),\n };\n }),\n );\n\n const quotesWithL1GasFees = (await l1GasFeePromises).reduce<\n (QuoteResponse & L1GasFees)[]\n >((acc, result) => {\n if (result.status === 'fulfilled' && result.value) {\n acc.push(result.value);\n } else if (result.status === 'rejected') {\n console.error('Error calculating L1 gas fees for quote', result.reason);\n }\n return acc;\n }, []);\n\n return quotesWithL1GasFees;\n };\n\n readonly #setMinimumBalanceForRentExemptionInLamports = (\n srcChainId: GenericQuoteRequest['srcChainId'],\n ): Promise<void> | undefined => {\n const selectedAccount = this.#getMultichainSelectedAccount();\n\n return isSolanaChainId(srcChainId) && selectedAccount?.metadata?.snap?.id\n ? this.messagingSystem\n .call(\n 'SnapController:handleRequest',\n getMinimumBalanceForRentExemptionRequest(\n selectedAccount.metadata.snap?.id,\n ),\n ) // eslint-disable-next-line promise/always-return\n .then((result) => {\n this.update((state) => {\n state.minimumBalanceForRentExemptionInLamports = String(result);\n });\n })\n .catch((error) => {\n console.error(\n 'Error setting minimum balance for rent exemption',\n error,\n );\n this.update((state) => {\n state.minimumBalanceForRentExemptionInLamports =\n DEFAULT_BRIDGE_CONTROLLER_STATE.minimumBalanceForRentExemptionInLamports;\n });\n })\n : undefined;\n };\n\n readonly #appendSolanaFees = async (\n quotes: QuoteResponse[],\n ): Promise<(QuoteResponse & SolanaFees)[] | undefined> => {\n // Return early if some of the quotes are not for solana\n if (\n quotes.some(({ quote: { srcChainId } }) => !isSolanaChainId(srcChainId))\n ) {\n return undefined;\n }\n\n const solanaFeePromises = Promise.allSettled(\n quotes.map(async (quoteResponse) => {\n const { trade } = quoteResponse;\n const selectedAccount = this.#getMultichainSelectedAccount();\n\n if (selectedAccount?.metadata?.snap?.id && typeof trade === 'string') {\n const { value: fees } = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n getFeeForTransactionRequest(\n selectedAccount.metadata.snap?.id,\n trade,\n ),\n )) as { value: string };\n\n return {\n ...quoteResponse,\n solanaFeesInLamports: fees,\n };\n }\n return quoteResponse;\n }),\n );\n\n const quotesWithSolanaFees = (await solanaFeePromises).reduce<\n (QuoteResponse & SolanaFees)[]\n >((acc, result) => {\n if (result.status === 'fulfilled' && result.value) {\n acc.push(result.value);\n } else if (result.status === 'rejected') {\n console.error('Error calculating solana fees for quote', result.reason);\n }\n return acc;\n }, []);\n\n return quotesWithSolanaFees;\n };\n\n #getMultichainSelectedAccount() {\n return this.messagingSystem.call(\n 'AccountsController:getSelectedMultichainAccount',\n );\n }\n\n #getSelectedNetworkClientId() {\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n // console.log('===selectedNetworkClientId', selectedNetworkClientId);\n return selectedNetworkClientId;\n }\n\n #getSelectedNetworkClient() {\n const selectedNetworkClientId = this.#getSelectedNetworkClientId();\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n return networkClient;\n }\n\n readonly #getRequestParams = (): Omit<\n RequestParams,\n 'token_symbol_source' | 'token_symbol_destination'\n > => {\n const srcChainIdCaip = formatChainIdToCaip(\n this.state.quoteRequest.srcChainId ||\n this.#getSelectedNetworkClient().configuration.chainId,\n );\n return getRequestParams(this.state.quoteRequest, srcChainIdCaip);\n };\n\n readonly #getRequestMetadata = (): Omit<\n RequestMetadata,\n 'stx_enabled' | 'usd_amount_source' | 'security_warnings'\n > => {\n return {\n slippage_limit: this.state.quoteRequest.slippage,\n swap_type: getSwapTypeFromQuote(this.state.quoteRequest),\n is_hardware_wallet: isHardwareWallet(\n this.#getMultichainSelectedAccount(),\n ),\n custom_slippage: isCustomSlippage(this.state.quoteRequest.slippage),\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 };\n };\n\n readonly #getEventProperties = <\n T extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: T,\n propertiesFromClient: Pick<RequiredEventContextFromClient, T>[T],\n ): CrossChainSwapsEventProperties<T> => {\n const baseProperties = {\n ...propertiesFromClient,\n action_type: MetricsActionType.SWAPBRIDGE_V1,\n };\n switch (eventName) {\n case UnifiedSwapBridgeEventName.ButtonClicked:\n case UnifiedSwapBridgeEventName.PageViewed:\n return {\n ...this.#getRequestParams(),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesValidationFailed:\n return {\n ...this.#getRequestParams(),\n refresh_count: this.state.quotesRefreshCount,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesReceived:\n return {\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n refresh_count: this.state.quotesRefreshCount,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesRequested:\n return {\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n has_sufficient_funds: !this.state.quoteRequest.insufficientBal,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuoteError:\n return {\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n error_message: this.state.quoteFetchError,\n has_sufficient_funds: !this.state.quoteRequest.insufficientBal,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.AllQuotesOpened:\n case UnifiedSwapBridgeEventName.AllQuotesSorted:\n case UnifiedSwapBridgeEventName.QuoteSelected:\n return {\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.SnapConfirmationViewed:\n return {\n ...baseProperties,\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n };\n case UnifiedSwapBridgeEventName.Failed: {\n // Populate the properties that the error occurred before the tx was submitted\n return {\n ...baseProperties,\n ...this.#getRequestParams(),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n ...propertiesFromClient,\n };\n }\n case UnifiedSwapBridgeEventName.AssetDetailTooltipClicked:\n return baseProperties;\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 ) => {\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 value !== this.state.quoteRequest[key as keyof GenericQuoteRequest]\n ) {\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.InputChanged,\n {\n input: inputKey,\n input_value: inputValue,\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 * @example\n * this.trackUnifiedSwapBridgeEvent(UnifiedSwapBridgeEventName.ActionOpened, {\n * location: MetaMetricsSwapsEventSource.MainView,\n * });\n */\n trackUnifiedSwapBridgeEvent = <\n T extends\n (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n >(\n eventName: T,\n propertiesFromClient: Pick<RequiredEventContextFromClient, T>[T],\n ) => {\n try {\n const combinedPropertiesForEvent = this.#getEventProperties<T>(\n eventName,\n propertiesFromClient,\n );\n\n this.#trackMetaMetricsFn(eventName, combinedPropertiesForEvent);\n } catch (error) {\n console.error(\n 'Error tracking cross-chain swaps MetaMetrics event',\n error,\n );\n }\n };\n\n /**\n *\n * @param contractAddress - The address of the ERC20 token contract\n * @param chainId - The hex chain ID of the bridge network\n * @returns The atomic allowance of the ERC20 token contract\n */\n getBridgeERC20Allowance = async (\n contractAddress: string,\n chainId: Hex,\n ): Promise<string> => {\n const provider = this.#getSelectedNetworkClient()?.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 { address: walletAddress } =\n this.#getMultichainSelectedAccount() ?? {};\n const allowance: BigNumber = await contract.allowance(\n walletAddress,\n METABRIDGE_CHAIN_TO_ADDRESS_MAP[chainId],\n );\n return allowance.toString();\n };\n}\n"]}
@@ -89,7 +89,7 @@ async function fetchBridgeQuotes(request, signal, clientId, fetchFn, bridgeApiBa
89
89
  cacheOptions: { cacheRefreshTime: 0 },
90
90
  functionName: 'fetchBridgeQuotes',
91
91
  });
92
- const validationFailuresByAggregator = {};
92
+ const uniqueValidationFailures = new Set([]);
93
93
  const filteredQuotes = quotes.filter((quoteResponse) => {
94
94
  try {
95
95
  return (0, validators_1.validateQuoteResponse)(quoteResponse);
@@ -97,21 +97,26 @@ async function fetchBridgeQuotes(request, signal, clientId, fetchFn, bridgeApiBa
97
97
  catch (error) {
98
98
  if (error instanceof superstruct_1.StructError) {
99
99
  error.failures().forEach(({ branch, path }) => {
100
- const aggregatorId = branch?.[0]?.quote?.bridgeId;
101
- if (!validationFailuresByAggregator[aggregatorId]) {
102
- validationFailuresByAggregator[aggregatorId] = new Set([]);
103
- }
100
+ const aggregatorId = branch?.[0]?.quote?.bridgeId ||
101
+ branch?.[0]?.quote?.bridges?.[0] ||
102
+ quoteResponse?.quote?.bridgeId ||
103
+ quoteResponse?.quote?.bridges?.[0] ||
104
+ 'unknown';
104
105
  const pathString = path?.join('.') || 'unknown';
105
- validationFailuresByAggregator[aggregatorId].add(pathString);
106
+ uniqueValidationFailures.add([aggregatorId, pathString].join('|'));
106
107
  });
107
108
  }
108
109
  return false;
109
110
  }
110
111
  });
111
- if (Object.keys(validationFailuresByAggregator).length > 0) {
112
- console.error('Quote validation failed', validationFailuresByAggregator);
112
+ const validationFailures = Array.from(uniqueValidationFailures);
113
+ if (uniqueValidationFailures.size > 0) {
114
+ console.warn('Quote validation failed', validationFailures);
113
115
  }
114
- return filteredQuotes;
116
+ return {
117
+ quotes: filteredQuotes,
118
+ validationFailures,
119
+ };
115
120
  }
116
121
  exports.fetchBridgeQuotes = fetchBridgeQuotes;
117
122
  const fetchAssetPricesForCurrency = async (request) => {
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":";;;AAAA,uDAAoD;AAEpD,2CAA2C;AAE3C,2DAG2B;AAC3B,iDAA+E;AAS/E,MAAM,yBAAyB,GAAG,EAAE,GAAG,gBAAQ,CAAC,MAAM,CAAC;AAEhD,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC;IACtD,aAAa,EAAE,QAAQ;CACxB,CAAC,CAAC;AAFU,QAAA,iBAAiB,qBAE3B;AAEH;;;;;;;;GAQG;AACI,KAA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EAA2D,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAnCW,QAAA,gBAAgB,oBAmC3B","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { validateQuoteResponse, validateSwapsTokenObject } from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal | null,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<QuoteResponse[]> {\n const destWalletAddress = request.destWalletAddress ?? request.walletAddress;\n // Transform the generic quote request into QuoteRequest\n const normalizedRequest: QuoteRequest = {\n walletAddress: formatAddressToCaipReference(request.walletAddress),\n destWalletAddress: formatAddressToCaipReference(destWalletAddress),\n srcChainId: formatChainIdToDec(request.srcChainId),\n destChainId: formatChainIdToDec(request.destChainId),\n srcTokenAddress: formatAddressToCaipReference(request.srcTokenAddress),\n destTokenAddress: formatAddressToCaipReference(request.destTokenAddress),\n srcTokenAmount: request.srcTokenAmount,\n insufficientBal: Boolean(request.insufficientBal),\n resetApproval: Boolean(request.resetApproval),\n gasIncluded: Boolean(request.gasIncluded),\n gasless7702: Boolean(request.gasless7702),\n };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n if (request.noFee !== undefined) {\n normalizedRequest.noFee = request.noFee;\n }\n if (request.aggIds && request.aggIds.length > 0) {\n normalizedRequest.aggIds = request.aggIds;\n }\n if (request.bridgeIds && request.bridgeIds.length > 0) {\n normalizedRequest.bridgeIds = request.bridgeIds;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const validationFailuresByAggregator: {\n [aggregator: string]: Set<string>;\n } = {};\n const filteredQuotes = quotes.filter((quoteResponse: unknown) => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId = branch?.[0]?.quote?.bridgeId;\n if (!validationFailuresByAggregator[aggregatorId]) {\n validationFailuresByAggregator[aggregatorId] = new Set([]);\n }\n const pathString = path?.join('.') || 'unknown';\n validationFailuresByAggregator[aggregatorId].add(pathString);\n });\n }\n return false;\n }\n });\n\n if (Object.keys(validationFailuresByAggregator).length > 0) {\n console.error('Quote validation failed', validationFailuresByAggregator);\n }\n return filteredQuotes as QuoteResponse[];\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
1
+ {"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":";;;AAAA,uDAAoD;AAEpD,2CAA2C;AAE3C,2DAG2B;AAC3B,iDAA+E;AAS/E,MAAM,yBAAyB,GAAG,EAAE,GAAG,gBAAQ,CAAC,MAAM,CAAC;AAEhD,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC;IACtD,aAAa,EAAE,QAAQ;CACxB,CAAC,CAAC;AAFU,QAAA,iBAAiB,qBAE3B;AAEH;;;;;;;;GAQG;AACI,KAAK,UAAU,iBAAiB,CACrC,OAA0B,EAC1B,QAAgB,EAChB,OAAsB,EACtB,gBAAwB;IAExB,8BAA8B;IAC9B,MAAM,GAAG,GAAG,GAAG,gBAAgB,sBAAsB,IAAA,oCAAkB,EAAC,OAAO,CAAC,EAAE,CAAC;IAEnF,uGAAuG;IACvG,uEAAuE;IACvE,6IAA6I;IAC7I,MAAM,MAAM,GAAG,MAAM,OAAO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,cAAc,CAAC;AACxB,CAAC,CAAC;AAnCW,QAAA,gBAAgB,oBAmC3B","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { validateQuoteResponse, validateSwapsTokenObject } from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal | null,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<{\n quotes: QuoteResponse[];\n validationFailures: string[];\n}> {\n const destWalletAddress = request.destWalletAddress ?? request.walletAddress;\n // Transform the generic quote request into QuoteRequest\n const normalizedRequest: QuoteRequest = {\n walletAddress: formatAddressToCaipReference(request.walletAddress),\n destWalletAddress: formatAddressToCaipReference(destWalletAddress),\n srcChainId: formatChainIdToDec(request.srcChainId),\n destChainId: formatChainIdToDec(request.destChainId),\n srcTokenAddress: formatAddressToCaipReference(request.srcTokenAddress),\n destTokenAddress: formatAddressToCaipReference(request.destTokenAddress),\n srcTokenAmount: request.srcTokenAmount,\n insufficientBal: Boolean(request.insufficientBal),\n resetApproval: Boolean(request.resetApproval),\n gasIncluded: Boolean(request.gasIncluded),\n gasless7702: Boolean(request.gasless7702),\n };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n if (request.noFee !== undefined) {\n normalizedRequest.noFee = request.noFee;\n }\n if (request.aggIds && request.aggIds.length > 0) {\n normalizedRequest.aggIds = request.aggIds;\n }\n if (request.bridgeIds && request.bridgeIds.length > 0) {\n normalizedRequest.bridgeIds = request.bridgeIds;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n const filteredQuotes = quotes.filter(\n (quoteResponse: unknown): quoteResponse is QuoteResponse => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId =\n branch?.[0]?.quote?.bridgeId ||\n branch?.[0]?.quote?.bridges?.[0] ||\n (quoteResponse as QuoteResponse)?.quote?.bridgeId ||\n (quoteResponse as QuoteResponse)?.quote?.bridges?.[0] ||\n 'unknown';\n const pathString = path?.join('.') || 'unknown';\n uniqueValidationFailures.add([aggregatorId, pathString].join('|'));\n });\n }\n return false;\n }\n },\n );\n\n const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n }\n\n return {\n quotes: filteredQuotes,\n validationFailures,\n };\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
@@ -24,7 +24,10 @@ export declare function fetchBridgeTokens(chainId: Hex | CaipChainId, clientId:
24
24
  * @param bridgeApiBaseUrl - The base URL for the bridge API
25
25
  * @returns A list of bridge tx quotes
26
26
  */
27
- export declare function fetchBridgeQuotes(request: GenericQuoteRequest, signal: AbortSignal | null, clientId: string, fetchFn: FetchFunction, bridgeApiBaseUrl: string): Promise<QuoteResponse[]>;
27
+ export declare function fetchBridgeQuotes(request: GenericQuoteRequest, signal: AbortSignal | null, clientId: string, fetchFn: FetchFunction, bridgeApiBaseUrl: string): Promise<{
28
+ quotes: QuoteResponse[];
29
+ validationFailures: string[];
30
+ }>;
28
31
  declare const fetchAssetPricesForCurrency: (request: {
29
32
  currency: string;
30
33
  assetIds: Set<CaipAssetType>;
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.cts","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"A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AW,EACZ,qBAAiB;AAIlB,eAAO,MAAM,iBAAiB,aAAc,MAAM;;CAEhD,CAAC;AAEH;;;;;;;;GAQG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,GAAG,GAAG,WAAW,EAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAoBtC;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,mBAAmB,EAC5B,MAAM,EAAE,WAAW,GAAG,IAAI,EAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC;IACT,MAAM,EAAE,aAAa,EAAE,CAAC;IACxB,kBAAkB,EAAE,MAAM,EAAE,CAAC;CAC9B,CAAC,CAyED;AAED,QAAA,MAAM,2BAA2B,YAAmB;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,IAAI,aAAa,CAAC,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,aAAa,CAAC;CACxB;;GAsCA,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,YAClB;IACP,UAAU,EAAE,IAAI,MAAM,CAAC,CAAC;CACzB,GAAG,KAAK,WAAW,kCAAkC,CAAC,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC;;eAgCxE,CAAC"}
@@ -24,7 +24,10 @@ export declare function fetchBridgeTokens(chainId: Hex | CaipChainId, clientId:
24
24
  * @param bridgeApiBaseUrl - The base URL for the bridge API
25
25
  * @returns A list of bridge tx quotes
26
26
  */
27
- export declare function fetchBridgeQuotes(request: GenericQuoteRequest, signal: AbortSignal | null, clientId: string, fetchFn: FetchFunction, bridgeApiBaseUrl: string): Promise<QuoteResponse[]>;
27
+ export declare function fetchBridgeQuotes(request: GenericQuoteRequest, signal: AbortSignal | null, clientId: string, fetchFn: FetchFunction, bridgeApiBaseUrl: string): Promise<{
28
+ quotes: QuoteResponse[];
29
+ validationFailures: string[];
30
+ }>;
28
31
  declare const fetchAssetPricesForCurrency: (request: {
29
32
  currency: string;
30
33
  assetIds: Set<CaipAssetType>;
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.mts","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;AAQvE,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,mBAAmB,EAEnB,WAAW,EACZ,qBAAiB;AAIlB,eAAO,MAAM,iBAAiB,aAAc,MAAM;;CAEhD,CAAC;AAEH;;;;;;;;GAQG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,GAAG,GAAG,WAAW,EAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAoBtC;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,mBAAmB,EAC5B,MAAM,EAAE,WAAW,GAAG,IAAI,EAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,aAAa,EAAE,CAAC,CAkE1B;AAED,QAAA,MAAM,2BAA2B,YAAmB;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,IAAI,aAAa,CAAC,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,aAAa,CAAC;CACxB;;GAsCA,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,YAClB;IACP,UAAU,EAAE,IAAI,MAAM,CAAC,CAAC;CACzB,G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AC;;eAgCxE,CAAC"}
@@ -84,7 +84,7 @@ export async function fetchBridgeQuotes(request, signal, clientId, fetchFn, brid
84
84
  cacheOptions: { cacheRefreshTime: 0 },
85
85
  functionName: 'fetchBridgeQuotes',
86
86
  });
87
- const validationFailuresByAggregator = {};
87
+ const uniqueValidationFailures = new Set([]);
88
88
  const filteredQuotes = quotes.filter((quoteResponse) => {
89
89
  try {
90
90
  return validateQuoteResponse(quoteResponse);
@@ -92,21 +92,26 @@ export async function fetchBridgeQuotes(request, signal, clientId, fetchFn, brid
92
92
  catch (error) {
93
93
  if (error instanceof StructError) {
94
94
  error.failures().forEach(({ branch, path }) => {
95
- const aggregatorId = branch?.[0]?.quote?.bridgeId;
96
- if (!validationFailuresByAggregator[aggregatorId]) {
97
- validationFailuresByAggregator[aggregatorId] = new Set([]);
98
- }
95
+ const aggregatorId = branch?.[0]?.quote?.bridgeId ||
96
+ branch?.[0]?.quote?.bridges?.[0] ||
97
+ quoteResponse?.quote?.bridgeId ||
98
+ quoteResponse?.quote?.bridges?.[0] ||
99
+ 'unknown';
99
100
  const pathString = path?.join('.') || 'unknown';
100
- validationFailuresByAggregator[aggregatorId].add(pathString);
101
+ uniqueValidationFailures.add([aggregatorId, pathString].join('|'));
101
102
  });
102
103
  }
103
104
  return false;
104
105
  }
105
106
  });
106
- if (Object.keys(validationFailuresByAggregator).length > 0) {
107
- console.error('Quote validation failed', validationFailuresByAggregator);
107
+ const validationFailures = Array.from(uniqueValidationFailures);
108
+ if (uniqueValidationFailures.size > 0) {
109
+ console.warn('Quote validation failed', validationFailures);
108
110
  }
109
- return filteredQuotes;
111
+ return {
112
+ quotes: filteredQuotes,
113
+ validationFailures,
114
+ };
110
115
  }
111
116
  const fetchAssetPricesForCurrency = async (request) => {
112
117
  const { currency, assetIds, clientId, fetchFn } = request;
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.mjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,W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CAAC,OAAwB,CAAC,GAAG,EAAE,CAAC;qBACpC;oBACD,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAAE;wBAC5D,GAAG,CAAC,OAAwB,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;oBAClD,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;aACJ;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAA2D,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { validateQuoteResponse, validateSwapsTokenObject } from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal | null,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<QuoteResponse[]> {\n const destWalletAddress = request.destWalletAddress ?? request.walletAddress;\n // Transform the generic quote request into QuoteRequest\n const normalizedRequest: QuoteRequest = {\n walletAddress: formatAddressToCaipReference(request.walletAddress),\n destWalletAddress: formatAddressToCaipReference(destWalletAddress),\n srcChainId: formatChainIdToDec(request.srcChainId),\n destChainId: formatChainIdToDec(request.destChainId),\n srcTokenAddress: formatAddressToCaipReference(request.srcTokenAddress),\n destTokenAddress: formatAddressToCaipReference(request.destTokenAddress),\n srcTokenAmount: request.srcTokenAmount,\n insufficientBal: Boolean(request.insufficientBal),\n resetApproval: Boolean(request.resetApproval),\n gasIncluded: Boolean(request.gasIncluded),\n gasless7702: Boolean(request.gasless7702),\n };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n if (request.noFee !== undefined) {\n normalizedRequest.noFee = request.noFee;\n }\n if (request.aggIds && request.aggIds.length > 0) {\n normalizedRequest.aggIds = request.aggIds;\n }\n if (request.bridgeIds && request.bridgeIds.length > 0) {\n normalizedRequest.bridgeIds = request.bridgeIds;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const validationFailuresByAggregator: {\n [aggregator: string]: Set<string>;\n } = {};\n const filteredQuotes = quotes.filter((quoteResponse: unknown) => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId = branch?.[0]?.quote?.bridgeId;\n if (!validationFailuresByAggregator[aggregatorId]) {\n validationFailuresByAggregator[aggregatorId] = new Set([]);\n }\n const pathString = path?.join('.') || 'unknown';\n validationFailuresByAggregator[aggregatorId].add(pathString);\n });\n }\n return false;\n }\n });\n\n if (Object.keys(validationFailuresByAggregator).length > 0) {\n console.error('Quote validation failed', validationFailuresByAggregator);\n }\n return filteredQuotes as QuoteResponse[];\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
1
+ {"version":3,"file":"fetch.mjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,8BAA8B;AAEpD,OAAO,EAAE,QAAQ,EAAE,wBAAwB;AAE3C,OAAO,EACL,4BAA4B,EAC5B,kBAAkB,EACnB,8BAA0B;AAC3B,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,yBAAqB;AAS/E,MAAM,yBAAyB,GAAG,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC;AAEvD,MAA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BACD,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAAE;wBAC5D,GAAG,CAAC,OAAwB,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;oBAClD,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;aACJ;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAA2D,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { validateQuoteResponse, validateSwapsTokenObject } from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal | null,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<{\n quotes: QuoteResponse[];\n validationFailures: string[];\n}> {\n const destWalletAddress = request.destWalletAddress ?? request.walletAddress;\n // Transform the generic quote request into QuoteRequest\n const normalizedRequest: QuoteRequest = {\n walletAddress: formatAddressToCaipReference(request.walletAddress),\n destWalletAddress: formatAddressToCaipReference(destWalletAddress),\n srcChainId: formatChainIdToDec(request.srcChainId),\n destChainId: formatChainIdToDec(request.destChainId),\n srcTokenAddress: formatAddressToCaipReference(request.srcTokenAddress),\n destTokenAddress: formatAddressToCaipReference(request.destTokenAddress),\n srcTokenAmount: request.srcTokenAmount,\n insufficientBal: Boolean(request.insufficientBal),\n resetApproval: Boolean(request.resetApproval),\n gasIncluded: Boolean(request.gasIncluded),\n gasless7702: Boolean(request.gasless7702),\n };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n if (request.noFee !== undefined) {\n normalizedRequest.noFee = request.noFee;\n }\n if (request.aggIds && request.aggIds.length > 0) {\n normalizedRequest.aggIds = request.aggIds;\n }\n if (request.bridgeIds && request.bridgeIds.length > 0) {\n normalizedRequest.bridgeIds = request.bridgeIds;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n const filteredQuotes = quotes.filter(\n (quoteResponse: unknown): quoteResponse is QuoteResponse => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId =\n branch?.[0]?.quote?.bridgeId ||\n branch?.[0]?.quote?.bridges?.[0] ||\n (quoteResponse as QuoteResponse)?.quote?.bridgeId ||\n (quoteResponse as QuoteResponse)?.quote?.bridges?.[0] ||\n 'unknown';\n const pathString = path?.join('.') || 'unknown';\n uniqueValidationFailures.add([aggregatorId, pathString].join('|'));\n });\n }\n return false;\n }\n },\n );\n\n const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n }\n\n return {\n quotes: filteredQuotes,\n validationFailures,\n };\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
@@ -22,6 +22,8 @@ var UnifiedSwapBridgeEventName;
22
22
  UnifiedSwapBridgeEventName["AllQuotesSorted"] = "Unified SwapBridge All Quotes Sorted";
23
23
  UnifiedSwapBridgeEventName["QuoteSelected"] = "Unified SwapBridge Quote Selected";
24
24
  UnifiedSwapBridgeEventName["AssetDetailTooltipClicked"] = "Unified SwapBridge Asset Detail Tooltip Clicked";
25
+ UnifiedSwapBridgeEventName["QuotesValidationFailed"] = "Unified SwapBridge Quotes Failed Validation";
26
+ UnifiedSwapBridgeEventName["StatusValidationFailed"] = "Unified SwapBridge Status Failed Validation";
25
27
  })(UnifiedSwapBridgeEventName || (exports.UnifiedSwapBridgeEventName = UnifiedSwapBridgeEventName = {}));
26
28
  var AbortReason;
27
29
  (function (AbortReason) {
@@ -1 +1 @@
1
- {"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,kCAAkC,GAAG,oBAAoB,CAAC;AAEvE;;GAEG;AACH,IAAY,0BAgBX;AAhBD,WAAY,0BAA0B;IACpC,iFAAsE,CAAA;IACtE,2EAAgE,CAAA;IAChE,+EAAoE,CAAA;IACpE,6GAAkG,CAAA;IAClG,qFAA0E,CAAA;IAC1E,mFAAwE,CAAA;IACxE,2EAAgE,CAAA;IAChE,yGAA8F,CAAA;IAC9F,wEAA6D,CAAA;IAC7D,wEAA6D,CAAA;IAC7D,kEAAuD,CAAA;IACvD,sFAA2E,CAAA;IAC3E,sFAA2E,CAAA;IAC3E,iFAAsE,CAAA;IACtE,2GAAgG,CAAA;AAClG,CAAC,EAhBW,0BAA0B,0CAA1B,0BAA0B,QAgBrC;AAED,IAAY,WAIX;AAJD,WAAY,WAAW;IACrB,oDAAqC,CAAA;IACrC,4DAA6C,CAAA;IAC7C,oDAAqC,CAAA;AACvC,CAAC,EAJW,WAAW,2BAAX,WAAW,QAItB;AAED;;GAEG;AACH,IAAY,2BAGX;AAHD,WAAY,2BAA2B;IACrC,qDAAsB,CAAA;IACtB,uDAAwB,CAAA;AAC1B,CAAC,EAHW,2BAA2B,2CAA3B,2BAA2B,QAGtC;AAED,IAAY,iBAMX;AAND,WAAY,iBAAiB;IAC3B;;OAEG;IACH,oDAA+B,CAAA;IAC/B,oDAA+B,CAAA;AACjC,CAAC,EANW,iBAAiB,iCAAjB,iBAAiB,QAM5B;AAED,IAAY,eAGX;AAHD,WAAY,eAAe;IACzB,0CAAuB,CAAA;IACvB,4CAAyB,CAAA;AAC3B,CAAC,EAHW,eAAe,+BAAf,eAAe,QAG1B","sourcesContent":["export const UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY = 'Unified SwapBridge';\n\n/**\n * These event names map to events defined in the segment-schema: https://github.com/Consensys/segment-schema/tree/main/libraries/events/metamask-cross-chain-swaps\n */\nexport enum UnifiedSwapBridgeEventName {\n ButtonClicked = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Button Clicked`,\n PageViewed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Page Viewed`,\n InputChanged = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Input Changed`,\n InputSourceDestinationFlipped = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Source Destination Flipped`,\n QuotesRequested = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Requested`,\n QuotesReceived = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Received`,\n QuoteError = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quote Error`,\n SnapConfirmationViewed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Snap Confirmation Page Viewed`,\n Submitted = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Submitted`,\n Completed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Completed`,\n Failed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Failed`,\n AllQuotesOpened = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} All Quotes Opened`,\n AllQuotesSorted = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} All Quotes Sorted`,\n QuoteSelected = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quote Selected`,\n AssetDetailTooltipClicked = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Asset Detail Tooltip Clicked`,\n}\n\nexport enum AbortReason {\n NewQuoteRequest = 'New Quote Request',\n QuoteRequestUpdated = 'Quote Request Updated',\n ResetState = 'Reset controller state',\n}\n\n/**\n * @deprecated remove this event property\n */\nexport enum MetaMetricsSwapsEventSource {\n MainView = 'Main View',\n TokenView = 'Token View',\n}\n\nexport enum MetricsActionType {\n /**\n * @deprecated new events should use SWAPBRIDGE_V1 instead\n */\n CROSSCHAIN_V1 = 'crosschain-v1',\n SWAPBRIDGE_V1 = 'swapbridge-v1',\n}\n\nexport enum MetricsSwapType {\n SINGLE = 'single_chain',\n CROSSCHAIN = 'crosschain',\n}\n"]}
1
+ {"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,kCAAkC,GAAG,oBAAoB,CAAC;AAEvE;;GAEG;AACH,IAAY,0BAkBX;AAlBD,WAAY,0BAA0B;IACpC,iFAAsE,CAAA;IACtE,2EAAgE,CAAA;IAChE,+EAAoE,CAAA;IACpE,6GAAkG,CAAA;IAClG,qFAA0E,CAAA;IAC1E,mFAAwE,CAAA;IACxE,2EAAgE,CAAA;IAChE,yGAA8F,CAAA;IAC9F,wEAA6D,CAAA;IAC7D,wEAA6D,CAAA;IAC7D,kEAAuD,CAAA;IACvD,sFAA2E,CAAA;IAC3E,sFAA2E,CAAA;IAC3E,iFAAsE,CAAA;IACtE,2GAAgG,CAAA;IAChG,oGAAyF,CAAA;IACzF,oGAAyF,CAAA;AAC3F,CAAC,EAlBW,0BAA0B,0CAA1B,0BAA0B,QAkBrC;AAED,IAAY,WAIX;AAJD,WAAY,WAAW;IACrB,oDAAqC,CAAA;IACrC,4DAA6C,CAAA;IAC7C,oDAAqC,CAAA;AACvC,CAAC,EAJW,WAAW,2BAAX,WAAW,QAItB;AAED;;GAEG;AACH,IAAY,2BAGX;AAHD,WAAY,2BAA2B;IACrC,qDAAsB,CAAA;IACtB,uDAAwB,CAAA;AAC1B,CAAC,EAHW,2BAA2B,2CAA3B,2BAA2B,QAGtC;AAED,IAAY,iBAMX;AAND,WAAY,iBAAiB;IAC3B;;OAEG;IACH,oDAA+B,CAAA;IAC/B,oDAA+B,CAAA;AACjC,CAAC,EANW,iBAAiB,iCAAjB,iBAAiB,QAM5B;AAED,IAAY,eAGX;AAHD,WAAY,eAAe;IACzB,0CAAuB,CAAA;IACvB,4CAAyB,CAAA;AAC3B,CAAC,EAHW,eAAe,+BAAf,eAAe,QAG1B","sourcesContent":["export const UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY = 'Unified SwapBridge';\n\n/**\n * These event names map to events defined in the segment-schema: https://github.com/Consensys/segment-schema/tree/main/libraries/events/metamask-cross-chain-swaps\n */\nexport enum UnifiedSwapBridgeEventName {\n ButtonClicked = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Button Clicked`,\n PageViewed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Page Viewed`,\n InputChanged = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Input Changed`,\n InputSourceDestinationFlipped = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Source Destination Flipped`,\n QuotesRequested = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Requested`,\n QuotesReceived = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Received`,\n QuoteError = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quote Error`,\n SnapConfirmationViewed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Snap Confirmation Page Viewed`,\n Submitted = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Submitted`,\n Completed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Completed`,\n Failed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Failed`,\n AllQuotesOpened = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} All Quotes Opened`,\n AllQuotesSorted = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} All Quotes Sorted`,\n QuoteSelected = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quote Selected`,\n AssetDetailTooltipClicked = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Asset Detail Tooltip Clicked`,\n QuotesValidationFailed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Failed Validation`,\n StatusValidationFailed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Status Failed Validation`,\n}\n\nexport enum AbortReason {\n NewQuoteRequest = 'New Quote Request',\n QuoteRequestUpdated = 'Quote Request Updated',\n ResetState = 'Reset controller state',\n}\n\n/**\n * @deprecated remove this event property\n */\nexport enum MetaMetricsSwapsEventSource {\n MainView = 'Main View',\n TokenView = 'Token View',\n}\n\nexport enum MetricsActionType {\n /**\n * @deprecated new events should use SWAPBRIDGE_V1 instead\n */\n CROSSCHAIN_V1 = 'crosschain-v1',\n SWAPBRIDGE_V1 = 'swapbridge-v1',\n}\n\nexport enum MetricsSwapType {\n SINGLE = 'single_chain',\n CROSSCHAIN = 'crosschain',\n}\n"]}
@@ -17,7 +17,9 @@ export declare enum UnifiedSwapBridgeEventName {
17
17
  AllQuotesOpened = "Unified SwapBridge All Quotes Opened",
18
18
  AllQuotesSorted = "Unified SwapBridge All Quotes Sorted",
19
19
  QuoteSelected = "Unified SwapBridge Quote Selected",
20
- AssetDetailTooltipClicked = "Unified SwapBridge Asset Detail Tooltip Clicked"
20
+ AssetDetailTooltipClicked = "Unified SwapBridge Asset Detail Tooltip Clicked",
21
+ QuotesValidationFailed = "Unified SwapBridge Quotes Failed Validation",
22
+ StatusValidationFailed = "Unified SwapBridge Status Failed Validation"
21
23
  }
22
24
  export declare enum AbortReason {
23
25
  NewQuoteRequest = "New Quote Request",
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,kCAAkC,uBAAuB,CAAC;AAEvE;;GAEG;AACH,oBAAY,0BAA0B;IACpC,aAAa,sCAAyD;IACtE,UAAU,mCAAsD;IAChE,YAAY,qCAAwD;IACpE,6BAA6B,kDAAqE;IAClG,eAAe,wCAA2D;IAC1E,cAAc,uCAA0D;IACxE,UAAU,mCAAsD;IAChE,sBAAsB,qDAAwE;IAC9F,SAAS,iCAAoD;IAC7D,SAAS,iCAAoD;IAC7D,MAAM,8BAAiD;IACvD,eAAe,yCAA4D;IAC3E,eAAe,yCAA4D;IAC3E,aAAa,sCAAyD;IACtE,yBAAyB,oDAAuE;CACjG;AAED,oBAAY,WAAW;IACrB,eAAe,sBAAsB;IACrC,mBAAmB,0BAA0B;IAC7C,UAAU,2BAA2B;CACtC;AAED;;GAEG;AACH,oBAAY,2BAA2B;IACrC,QAAQ,cAAc;IACtB,SAAS,eAAe;CACzB;AAED,oBAAY,iBAAiB;IAC3B;;OAEG;IACH,aAAa,kBAAkB;IAC/B,aAAa,kBAAkB;CAChC;AAED,oBAAY,eAAe;IACzB,MAAM,iBAAiB;IACvB,UAAU,eAAe;CAC1B"}
1
+ {"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,kCAAkC,uBAAuB,CAAC;AAEvE;;GAEG;AACH,oBAAY,0BAA0B;IACpC,aAAa,sCAAyD;IACtE,UAAU,mCAAsD;IAChE,YAAY,qCAAwD;IACpE,6BAA6B,kDAAqE;IAClG,eAAe,wCAA2D;IAC1E,cAAc,uCAA0D;IACxE,UAAU,mCAAsD;IAChE,sBAAsB,qDAAwE;IAC9F,SAAS,iCAAoD;IAC7D,SAAS,iCAAoD;IAC7D,MAAM,8BAAiD;IACvD,eAAe,yCAA4D;IAC3E,eAAe,yCAA4D;IAC3E,aAAa,sCAAyD;IACtE,yBAAyB,oDAAuE;IAChG,sBAAsB,gDAAmE;IACzF,sBAAsB,gDAAmE;CAC1F;AAED,oBAAY,WAAW;IACrB,eAAe,sBAAsB;IACrC,mBAAmB,0BAA0B;IAC7C,UAAU,2BAA2B;CACtC;AAED;;GAEG;AACH,oBAAY,2BAA2B;IACrC,QAAQ,cAAc;IACtB,SAAS,eAAe;CACzB;AAED,oBAAY,iBAAiB;IAC3B;;OAEG;IACH,aAAa,kBAAkB;IAC/B,aAAa,kBAAkB;CAChC;AAED,oBAAY,eAAe;IACzB,MAAM,iBAAiB;IACvB,UAAU,eAAe;CAC1B"}
@@ -17,7 +17,9 @@ export declare enum UnifiedSwapBridgeEventName {
17
17
  AllQuotesOpened = "Unified SwapBridge All Quotes Opened",
18
18
  AllQuotesSorted = "Unified SwapBridge All Quotes Sorted",
19
19
  QuoteSelected = "Unified SwapBridge Quote Selected",
20
- AssetDetailTooltipClicked = "Unified SwapBridge Asset Detail Tooltip Clicked"
20
+ AssetDetailTooltipClicked = "Unified SwapBridge Asset Detail Tooltip Clicked",
21
+ QuotesValidationFailed = "Unified SwapBridge Quotes Failed Validation",
22
+ StatusValidationFailed = "Unified SwapBridge Status Failed Validation"
21
23
  }
22
24
  export declare enum AbortReason {
23
25
  NewQuoteRequest = "New Quote Request",