{"version":3,"file":"bridge-controller.mjs","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,qEAAqE;AACrE,OAAO,EAAE,SAAS,EAAE,iCAAiC;AACrD,OAAO,EAAE,QAAQ,EAAE,iCAAiC;AACpD,OAAO,EAAE,YAAY,EAAE,iCAAiC;AAIxD,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AACvD,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAK/E,OAAO,EACL,sBAAsB,EACtB,wBAAwB,EACxB,+BAA+B,EAC/B,2BAA2B,EAC3B,mBAAmB,EACpB,+BAA2B;AAC5B,OAAO,EAAE,SAAS,EAAE,+BAA2B;AAC/C,OAAO,EAAE,wBAAwB,EAAE,8BAA0B;AAC7D,OAAO,EAAE,SAAS,EAAE,+BAA2B;AAC/C,OAAO,EAEL,gCAAgC,EACjC,wBAAoB;AACrB,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,oBAAgB;AAYnD,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,2BAAuB;AACtE,OAAO,EAAE,oBAAoB,EAAE,4BAAwB;AACvD,OAAO,EACL,+BAA+B,EAC/B,YAAY,EACZ,SAAS,EACT,eAAe,EACf,eAAe,EAChB,2BAAuB;AACxB,OAAO,EACL,4BAA4B,EAC5B,mBAAmB,EACnB,kBAAkB,EACnB,oCAAgC;AACjC,OAAO,EACL,qBAAqB,EACrB,yBAAyB,EAC1B,kCAA8B;AAC/B,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,sBAAsB,EACtB,oBAAoB,EACrB,0BAAsB;AACvB,OAAO,EACL,WAAW,EACX,2BAA2B,EAC3B,iBAAiB,EACjB,0BAA0B,EAC3B,sCAAkC;AACnC,OAAO,EACL,mBAAmB,EACnB,sBAAsB,EACtB,gBAAgB,EAChB,oBAAoB,EACpB,gBAAgB,EAChB,yBAAyB,EACzB,2BAA2B,EAC5B,uCAAmC;AAOpC,OAAO,EACL,m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,GAAG,EAAE,CAAC,KAAK,CAAC,MAAA,CAAC;QAElD,IAAI,CAAC,SAAS,CAAC,4BAA4B,CACzC,IAAI,EACJ,yBAAyB,CAC1B,CAAC;IACJ,CAAC;CA4jCF;+lDAjUG,aAAoD;IAEpD,6DAA6D;IAC7D,MAAM,YAAY,GAChB,aAAa,IAAI,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC;IAC5D,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IACjD,CAAC;IACD,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACzC,wCAAwC,EACxC,YAAY,CACb,CAAC;IACF,OAAO,eAAe,CAAC;AACzB,CAAC,qGAE0B,OAAY;IACrC,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACzC,gDAAgD,EAChD,OAAO,CACR,CAAC;IACF,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,wCAAwC,OAAO,EAAE,CAAC,CAAC;IACrE,CAAC;IACD,MAAM,aAAa,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACvC,wCAAwC,EACxC,eAAe,CAChB,CAAC;IACF,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type { StateMetadata } from '@metamask/base-controller';\nimport type { TraceCallback } from '@metamask/controller-utils';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { TransactionController } from '@metamask/transaction-controller';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\n\nimport type { BridgeClientId } from './constants/bridge';\nimport {\n  BRIDGE_CONTROLLER_NAME,\n  BRIDGE_PROD_API_BASE_URL,\n  DEFAULT_BRIDGE_CONTROLLER_STATE,\n  METABRIDGE_ETHEREUM_ADDRESS,\n  REFRESH_INTERVAL_MS,\n} from './constants/bridge';\nimport { CHAIN_IDS } from './constants/chains';\nimport { SWAPS_CONTRACT_ADDRESSES } from './constants/swaps';\nimport { TraceName } from './constants/traces';\nimport {\n  ExchangeRateSourcesForLookup,\n  selectIsAssetExchangeRateInState,\n} from './selectors';\nimport { FeatureId, RequestStatus } from './types';\nimport type {\n  L1GasFees,\n  GenericQuoteRequest,\n  NonEvmFees,\n  QuoteRequest,\n  QuoteResponseV1,\n  BridgeControllerState,\n  BridgeControllerMessenger,\n  FetchFunction,\n  InputPrimaryDenomination,\n} from './types';\nimport { getAssetIdsForToken, toExchangeRates } from './utils/assets';\nimport { hasSufficientBalance } from './utils/balance';\nimport {\n  getDefaultBridgeControllerState,\n  isCrossChain,\n  isEthUsdt,\n  isNonEvmChainId,\n  isSolanaChainId,\n} from './utils/bridge';\nimport {\n  formatAddressToCaipReference,\n  formatChainIdToCaip,\n  formatChainIdToHex,\n} from './utils/caip-formatters';\nimport {\n  getBridgeFeatureFlags,\n  hasMinimumRequiredVersion,\n} from './utils/feature-flags';\nimport {\n  fetchAssetPrices,\n  fetchBridgeQuotes,\n  fetchBridgeQuoteStream,\n  fetchBatchSellTrades,\n} from './utils/fetch';\nimport {\n  AbortReason,\n  MetaMetricsSwapsEventSource,\n  MetricsActionType,\n  UnifiedSwapBridgeEventName,\n} from './utils/metrics/constants';\nimport {\n  formatProviderLabel,\n  getAccountHardwareType,\n  getRequestParams,\n  getSwapTypeFromQuote,\n  isCustomSlippage,\n  toInputChangedPropertyKey,\n  toInputChangedPropertyValue,\n} from './utils/metrics/properties';\nimport type {\n  QuoteFetchData,\n  RequestMetadata,\n  RequiredEventContextFromClient,\n} from './utils/metrics/types';\nimport type { CrossChainSwapsEventProperties } from './utils/metrics/types';\nimport {\n  isValidQuoteRequest,\n  isValidBatchSellQuoteRequest,\n  sortQuotes,\n} from './utils/quote';\nimport { appendFeesToQuotes } from './utils/quote-fees';\nimport { getMinimumBalanceForRentExemptionInLamports } from './utils/snaps';\n\nconst metadata: StateMetadata<BridgeControllerState> = {\n  quoteRequest: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  quotes: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  quotesInitialLoadTime: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  quotesLastFetched: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  quotesLoadingStatus: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  quoteFetchError: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  quotesRefreshCount: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  assetExchangeRates: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  minimumBalanceForRentExemptionInLamports: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  tokenWarnings: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  tokenSecurityTypeDestination: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  inputPrimaryDenomination: {\n    includeInStateLogs: true,\n    persist: true,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  quoteStreamComplete: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  batchSellTrades: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n  batchSellTradesLoadingStatus: {\n    includeInStateLogs: true,\n    persist: false,\n    includeInDebugSnapshot: false,\n    usedInUi: true,\n  },\n};\n\n/**\n * The input to start polling for the {@link BridgeController}\n *\n * @param updatedQuoteRequest - The updated quote request\n * @param context - The context contains properties that can't be populated by the\n * controller and need to be provided by the client for analytics\n */\ntype BridgePollingInput = {\n  quoteRequests: GenericQuoteRequest[];\n  context: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesError] &\n    RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesRequested];\n};\n\nconst MESSENGER_EXPOSED_METHODS = [\n  'updateBridgeQuoteRequestParams',\n  'fetchQuotes',\n  'updateBatchSellTrades',\n  'stopPollingForQuotes',\n  'setLocation',\n  'getLocation',\n  'setInputPrimaryDenomination',\n  'resetState',\n  'setChainIntervalLength',\n  'trackUnifiedSwapBridgeEvent',\n] as const;\n\nexport class BridgeController extends StaticIntervalPollingController<BridgePollingInput>()<\n  typeof BRIDGE_CONTROLLER_NAME,\n  BridgeControllerState,\n  BridgeControllerMessenger\n> {\n  #abortController: AbortController | undefined;\n\n  #batchSellTradesAbortController: AbortController | undefined;\n\n  #quotesFirstFetched: number | undefined;\n\n  /**\n   * Stores the location/entry point from which the user initiated the swap or bridge flow.\n   * Set via setLocation() before navigating to the swap/bridge flow.\n   * Used as default for all subsequent internal events.\n   */\n  #location: MetaMetricsSwapsEventSource = MetaMetricsSwapsEventSource.Unknown;\n\n  readonly #clientId: BridgeClientId;\n\n  readonly #clientVersion: string;\n\n  readonly #getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n\n  readonly #fetchFn: FetchFunction;\n\n  readonly #trackMetaMetricsFn: <\n    EventName extends\n      (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n  >(\n    eventName: EventName,\n    properties: CrossChainSwapsEventProperties<EventName>,\n  ) => void;\n\n  readonly #trace: TraceCallback;\n\n  readonly #config: {\n    customBridgeApiBaseUrl?: string;\n  };\n\n  /**\n   * Returns whether to use AssetsController for exchange rates.\n   * Set via constructor option getUseAssetsControllerForRates; defaults to false.\n   *\n   * @returns True when exchange rates should be read from AssetsController:getExchangeRatesForBridge.\n   */\n  readonly #getUseAssetsControllerForRates: () => boolean;\n\n  constructor({\n    messenger,\n    state,\n    clientId,\n    clientVersion,\n    getLayer1GasFee,\n    fetchFn,\n    config,\n    trackMetaMetricsFn,\n    traceFn,\n    getUseAssetsControllerForRates,\n  }: {\n    messenger: BridgeControllerMessenger;\n    state?: Partial<BridgeControllerState>;\n    clientId: BridgeClientId;\n    clientVersion: string;\n    getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n    fetchFn: FetchFunction;\n    config?: {\n      customBridgeApiBaseUrl?: string;\n    };\n    trackMetaMetricsFn: <\n      EventName extends\n        (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n    >(\n      eventName: EventName,\n      properties: CrossChainSwapsEventProperties<EventName>,\n    ) => void;\n    traceFn?: TraceCallback;\n    /**\n     * When provided, called to determine whether to use AssetsController for exchange rates.\n     * When true, rates are read from AssetsController:getExchangeRatesForBridge instead of\n     * MultichainAssetsRatesController, TokenRatesController, and CurrencyRateController.\n     */\n    getUseAssetsControllerForRates?: () => boolean;\n  }) {\n    super({\n      name: BRIDGE_CONTROLLER_NAME,\n      metadata,\n      messenger,\n      state: {\n        ...getDefaultBridgeControllerState(),\n        ...state,\n      },\n    });\n\n    this.setIntervalLength(REFRESH_INTERVAL_MS);\n\n    this.#abortController = new AbortController();\n    this.#getLayer1GasFee = getLayer1GasFee;\n    this.#clientId = clientId;\n    this.#clientVersion = clientVersion;\n    this.#fetchFn = fetchFn;\n    this.#trackMetaMetricsFn = trackMetaMetricsFn;\n    this.#config = config ?? {};\n    this.#trace = traceFn ?? (((_request, fn) => fn?.()) as TraceCallback);\n    this.#getUseAssetsControllerForRates =\n      getUseAssetsControllerForRates ?? (() => false);\n\n    this.messenger.registerMethodActionHandlers(\n      this,\n      MESSENGER_EXPOSED_METHODS,\n    );\n  }\n\n  _executePoll = async (pollingInput: BridgePollingInput) => {\n    await this.#fetchBridgeQuotes(pollingInput);\n  };\n\n  /**\n   * Updates the quote request at the specified index with the given parameters, then starts\n   * polling for quotes.\n   *\n   * @param paramsToUpdate - The parameters to update in the quote request at the specified index\n   * @param context - metrics context\n   * @param quoteRequestIndex - The index of the quote request to update\n   * @param quoteRequestCount - The number of quote requests in the UI\n   */\n  updateBridgeQuoteRequestParams = async (\n    paramsToUpdate: Partial<GenericQuoteRequest> & {\n      walletAddress: GenericQuoteRequest['walletAddress'];\n    },\n    context: BridgePollingInput['context'],\n    quoteRequestIndex: number = 0,\n    quoteRequestCount: number = 1,\n  ) => {\n    // Guard against updating a quote request that doesn't exist\n    if (quoteRequestIndex >= quoteRequestCount) {\n      return;\n    }\n    this.#trackInputChangedEvents(\n      paramsToUpdate,\n      context.feature_id,\n      quoteRequestIndex,\n    );\n    this.resetState(AbortReason.QuoteRequestUpdated, quoteRequestIndex);\n    this.update((state) => {\n      // Update only the specified quote request and keep the rest of the quote requests unchanged\n      state.quoteRequest = state.quoteRequest\n        .slice(0, quoteRequestIndex)\n        .concat({\n          ...DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest[0],\n          ...paramsToUpdate,\n        })\n        .concat(\n          state.quoteRequest.slice(quoteRequestIndex + 1, quoteRequestCount),\n        );\n      state.tokenSecurityTypeDestination =\n        context.token_security_type_destination ?? null;\n    });\n\n    // BatchSell and Unified swaps both use the same polling logic so both validations should pass\n    if (\n      isValidQuoteRequest(paramsToUpdate) &&\n      isValidBatchSellQuoteRequest(this.state.quoteRequest)\n    ) {\n      this.#quotesFirstFetched = Date.now();\n      // Update the insufficientBal and resetApproval params for the quote request\n      const quoteWithInsufficientBalAndResetApproval =\n        await this.#appendInsufficientBalAndResetApproval(paramsToUpdate);\n      this.update((state) => {\n        state.quoteRequest[quoteRequestIndex] =\n          quoteWithInsufficientBalAndResetApproval;\n      });\n\n      // Set refresh rate based on the source chain before starting polling\n      this.setChainIntervalLength();\n      this.startPolling({\n        quoteRequests: this.state.quoteRequest,\n        context,\n      });\n    }\n  };\n\n  /**\n   * Fetches quotes for specified request without updating the controller state\n   * This method does not start polling for quotes and does not emit UnifiedSwapBridge events\n   *\n   * @param quoteRequest - The parameters for quote requests to fetch\n   * @param featureId - The feature ID that maps to quoteParam overrides from LD\n   * @param abortSignal - The abort signal to cancel all the requests\n   * @returns A list of validated quotes\n   */\n  fetchQuotes = async (\n    quoteRequest: GenericQuoteRequest,\n    featureId: FeatureId,\n    abortSignal: AbortSignal | null = null,\n  ): Promise<(QuoteResponseV1 & L1GasFees & NonEvmFees)[]> => {\n    const bridgeFeatureFlags = getBridgeFeatureFlags(this.messenger);\n    const jwt = await this.#getJwt();\n    // If featureId is specified, retrieve the quoteRequestOverrides for that featureId\n    const quoteRequestOverrides = featureId\n      ? bridgeFeatureFlags.quoteRequestOverrides?.[featureId]\n      : undefined;\n    const resetApproval = await this.#shouldResetApproval(quoteRequest);\n\n    // If quoteRequestOverrides is specified, merge it with the quoteRequest\n    const { quotes: baseQuotes, validationFailures } = await fetchBridgeQuotes(\n      quoteRequestOverrides\n        ? { ...quoteRequest, ...quoteRequestOverrides, resetApproval }\n        : { ...quoteRequest, resetApproval },\n      abortSignal,\n      this.#clientId,\n      jwt,\n      this.#fetchFn,\n      this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n      featureId,\n      this.#clientVersion,\n    );\n\n    this.#trackQuoteValidationFailures(validationFailures, featureId);\n\n    const quotesWithFees = await appendFeesToQuotes(\n      baseQuotes,\n      this.messenger,\n      this.#getLayer1GasFee,\n      this.#getMultichainSelectedAccount(quoteRequest.walletAddress),\n    );\n\n    return sortQuotes(quotesWithFees, featureId);\n  };\n\n  /**\n   * Fetches gasless transaction data and fees for BatchSell quotes.\n   * To use this in the clients, add a listener for the recommendedQuotes and call\n   * this handler whenever they change.\n   *\n   * @param quotes - The quotes to fetch the gasless transaction data and fees for\n   * @param stxEnabled - Flag to estimate gas cost more precisely for the batch sell feature.\n   */\n  updateBatchSellTrades = async (\n    quotes: (QuoteResponseV1 | null)[],\n    stxEnabled: boolean,\n  ): Promise<void> => {\n    this.#batchSellTradesAbortController?.abort(\n      AbortReason.GaslessTxBatchFetched,\n    );\n    this.#batchSellTradesAbortController = new AbortController();\n\n    this.update((state) => {\n      // Set loading status again if recommended quotes are re-ordered\n      state.batchSellTradesLoadingStatus = RequestStatus.LOADING;\n    });\n\n    try {\n      const batchSellTradesResponse = await fetchBatchSellTrades(\n        quotes,\n        stxEnabled,\n        this.#batchSellTradesAbortController.signal,\n        this.#clientId,\n        await this.#getJwt(),\n        this.#fetchFn,\n        this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n        this.#clientVersion,\n      );\n\n      this.update((state) => {\n        state.batchSellTrades = batchSellTradesResponse;\n        state.batchSellTradesLoadingStatus = RequestStatus.FETCHED;\n      });\n\n      // TODO if fee.asset.assetId is not in exchange rates, fetch the exchange rate and update the state\n    } catch (error) {\n      // Ignore abort errors\n      if (\n        (error as Error).toString().includes('AbortError') ||\n        (error as Error).toString().includes('FetchRequestCanceledException') ||\n        [\n          AbortReason.ResetState,\n          AbortReason.NewQuoteRequest,\n          AbortReason.QuoteRequestUpdated,\n          AbortReason.TransactionSubmitted,\n          AbortReason.GaslessTxBatchFetched,\n        ].includes(error as AbortReason)\n      ) {\n        // Exit the function early to prevent other state updates\n        return;\n      }\n\n      this.update((state) => {\n        // Reset the batch sell trades if the fetch fails to avoid showing stale data\n        state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n        // Update loading status\n        state.batchSellTradesLoadingStatus = RequestStatus.ERROR;\n      });\n      console.log(`Failed to fetch batch sell trades`, error);\n    }\n  };\n\n  readonly #trackQuoteValidationFailures = (\n    validationFailures: string[],\n    featureId: FeatureId,\n  ) => {\n    if (validationFailures.length === 0) {\n      return;\n    }\n    this.trackUnifiedSwapBridgeEvent(\n      UnifiedSwapBridgeEventName.QuotesValidationFailed,\n      {\n        feature_id: featureId,\n        failures: validationFailures,\n        location: this.#location,\n      },\n    );\n  };\n\n  readonly #getExchangeRateSources = (): ExchangeRateSourcesForLookup => {\n    if (this.#getUseAssetsControllerForRates()) {\n      return {\n        ...this.messenger.call('AssetsController:getExchangeRatesForBridge'),\n        historicalPrices: {},\n        ...this.state,\n      };\n    }\n    return {\n      ...this.messenger.call('MultichainAssetsRatesController:getState'),\n      ...this.messenger.call('CurrencyRateController:getState'),\n      ...this.messenger.call('TokenRatesController:getState'),\n      ...this.state,\n    };\n  };\n\n  /**\n   * Fetches the exchange rates for the assets in the quote request if they are not already in the state\n   * In addition to the selected tokens, this also fetches the native asset for the source and destination chains\n   *\n   * @param quoteRequests - The quote requests to fetch the exchange rates for\n   */\n  readonly #fetchAssetExchangeRates = async (\n    quoteRequests: GenericQuoteRequest[],\n  ) => {\n    const exchangeRateSources = this.#getExchangeRateSources();\n\n    // Get unique assetIds for all quote requests\n    const assetIds = new Set<CaipAssetType>(\n      quoteRequests\n        .flatMap((quoteRequest) =>\n          [\n            getAssetIdsForToken(\n              quoteRequest.srcTokenAddress,\n              quoteRequest.srcChainId,\n            ),\n            getAssetIdsForToken(\n              quoteRequest.destTokenAddress,\n              quoteRequest.destChainId,\n            ),\n          ].flat(),\n        )\n        .filter(\n          (assetId: CaipAssetType | undefined): assetId is CaipAssetType =>\n            !selectIsAssetExchangeRateInState(exchangeRateSources, assetId),\n        ),\n    );\n\n    const currency = this.#getUseAssetsControllerForRates()\n      ? this.messenger.call('AssetsController:getExchangeRatesForBridge')\n          .currentCurrency\n      : this.messenger.call('CurrencyRateController:getState').currentCurrency;\n\n    if (assetIds.size === 0) {\n      return;\n    }\n\n    const pricesByAssetId = await fetchAssetPrices({\n      assetIds,\n      currencies: new Set([currency]),\n      clientId: this.#clientId,\n      clientVersion: this.#clientVersion,\n      fetchFn: this.#fetchFn,\n      signal: this.#abortController?.signal,\n    });\n    const exchangeRates = toExchangeRates(currency, pricesByAssetId);\n    this.update((state) => {\n      state.assetExchangeRates = {\n        ...state.assetExchangeRates,\n        ...exchangeRates,\n      };\n    });\n  };\n\n  readonly #hasInsufficientBalance = async (\n    quoteRequest: GenericQuoteRequest,\n  ) => {\n    try {\n      const srcChainIdInHex = formatChainIdToHex(quoteRequest.srcChainId);\n      const provider =\n        this.#getNetworkClientByChainId(srcChainIdInHex)?.provider;\n      const normalizedSrcTokenAddress = formatAddressToCaipReference(\n        quoteRequest.srcTokenAddress,\n      );\n\n      return !(\n        provider &&\n        normalizedSrcTokenAddress &&\n        quoteRequest.srcTokenAmount &&\n        srcChainIdInHex &&\n        (await hasSufficientBalance(\n          provider,\n          quoteRequest.walletAddress,\n          normalizedSrcTokenAddress,\n          quoteRequest.srcTokenAmount,\n          srcChainIdInHex,\n        ))\n      );\n    } catch (error) {\n      console.warn('Failed to set insufficientBal', error);\n      // Fall back to true so the backend returns quotes\n      return true;\n    }\n  };\n\n  readonly #appendInsufficientBalAndResetApproval = async (\n    quoteRequest: GenericQuoteRequest,\n  ) => {\n    const isSrcChainNonEVM = isNonEvmChainId(quoteRequest.srcChainId);\n    const providerConfig = isSrcChainNonEVM\n      ? undefined\n      : this.#getNetworkClientByChainId(\n          formatChainIdToHex(quoteRequest.srcChainId),\n        )?.configuration;\n\n    let insufficientBal: boolean | undefined;\n    let resetApproval: boolean = Boolean(quoteRequest.resetApproval);\n    if (isSrcChainNonEVM) {\n      // If the source chain is not an EVM network, use value from params\n      insufficientBal = quoteRequest.insufficientBal;\n    } else if (providerConfig?.rpcUrl?.includes('tenderly')) {\n      // If the rpcUrl is a tenderly fork (e2e tests), set insufficientBal=true\n      // The bridge-api filters out quotes if the balance on mainnet is insufficient so this override allows quotes to always be returned\n      insufficientBal = true;\n    } else {\n      // Set loading status if RPC calls are made before the quotes are fetched\n      this.update((state) => {\n        state.quotesLoadingStatus = RequestStatus.LOADING;\n      });\n      resetApproval = await this.#shouldResetApproval(quoteRequest);\n      // Otherwise query the src token balance from the RPC provider\n      insufficientBal =\n        quoteRequest.insufficientBal ??\n        (await this.#hasInsufficientBalance(quoteRequest));\n    }\n\n    return {\n      ...quoteRequest,\n      insufficientBal,\n      resetApproval,\n    };\n  };\n\n  readonly #shouldResetApproval = async (quoteRequest: GenericQuoteRequest) => {\n    if (isNonEvmChainId(quoteRequest.srcChainId)) {\n      return false;\n    }\n    try {\n      const normalizedSrcTokenAddress = formatAddressToCaipReference(\n        quoteRequest.srcTokenAddress,\n      );\n      if (isEthUsdt(quoteRequest.srcChainId, normalizedSrcTokenAddress)) {\n        const allowance = BigNumber.from(\n          await this.#getUSDTMainnetAllowance(\n            quoteRequest.walletAddress,\n            normalizedSrcTokenAddress,\n            quoteRequest.destChainId,\n          ),\n        );\n        return allowance.lt(quoteRequest.srcTokenAmount) && allowance.gt(0);\n      }\n      return false;\n    } catch (error) {\n      console.warn('Failed to set resetApproval', error);\n      // Fall back to true so the backend returns quotes\n      return true;\n    }\n  };\n\n  stopPollingForQuotes = (\n    reason?: AbortReason,\n    context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived],\n  ) => {\n    this.stopAllPolling();\n    // If polling is stopped before quotes finish loading, track QuotesReceived\n    if (this.state.quotesLoadingStatus === RequestStatus.LOADING && context) {\n      this.trackUnifiedSwapBridgeEvent(\n        UnifiedSwapBridgeEventName.QuotesReceived,\n        context,\n      );\n    }\n    // Clears quotes list in state\n    this.#abortController?.abort(reason);\n    this.#batchSellTradesAbortController?.abort(reason);\n  };\n\n  /**\n   * Sets the location/entry point for the current swap or bridge flow.\n   * Call this when the user enters the flow so that all internally-fired\n   * events (InputChanged, QuotesRequested, etc.) carry the correct location.\n   *\n   * @param location - The entry point from which the user initiated the flow\n   */\n  setLocation = (location: MetaMetricsSwapsEventSource) => {\n    this.#location = location;\n  };\n\n  /**\n   * Returns the location/entry point for the current swap or bridge flow.\n   *\n   * @returns The entry point from which the user initiated the flow\n   */\n  getLocation = (): MetaMetricsSwapsEventSource => {\n    return this.#location;\n  };\n\n  setInputPrimaryDenomination = (\n    inputPrimaryDenomination: InputPrimaryDenomination,\n  ) => {\n    this.update((state) => {\n      state.inputPrimaryDenomination = inputPrimaryDenomination;\n    });\n  };\n\n  resetState = (\n    reason = AbortReason.ResetState,\n    quoteRequestIndex: number | null = null,\n    context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived],\n  ) => {\n    this.stopPollingForQuotes(reason, context);\n    this.update((state) => {\n      // Cannot do direct assignment to state, i.e. state = {... }, need to manually assign each field\n      if (quoteRequestIndex === null) {\n        // Clear all requests if index is null\n        state.quoteRequest = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest;\n      } else {\n        // Otherwise only clear the specified request\n        state.quoteRequest = state.quoteRequest\n          .slice(0, quoteRequestIndex)\n          .concat(DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest[0])\n          .concat(state.quoteRequest.slice(quoteRequestIndex + 1));\n      }\n      state.quotesInitialLoadTime =\n        DEFAULT_BRIDGE_CONTROLLER_STATE.quotesInitialLoadTime;\n      state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n      state.quotesLastFetched =\n        DEFAULT_BRIDGE_CONTROLLER_STATE.quotesLastFetched;\n      state.quotesLoadingStatus =\n        DEFAULT_BRIDGE_CONTROLLER_STATE.quotesLoadingStatus;\n      state.quoteFetchError = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteFetchError;\n      state.quotesRefreshCount =\n        DEFAULT_BRIDGE_CONTROLLER_STATE.quotesRefreshCount;\n      state.assetExchangeRates =\n        DEFAULT_BRIDGE_CONTROLLER_STATE.assetExchangeRates;\n      state.minimumBalanceForRentExemptionInLamports =\n        DEFAULT_BRIDGE_CONTROLLER_STATE.minimumBalanceForRentExemptionInLamports;\n      state.tokenWarnings = DEFAULT_BRIDGE_CONTROLLER_STATE.tokenWarnings;\n      state.tokenSecurityTypeDestination =\n        DEFAULT_BRIDGE_CONTROLLER_STATE.tokenSecurityTypeDestination;\n      state.quoteStreamComplete =\n        DEFAULT_BRIDGE_CONTROLLER_STATE.quoteStreamComplete;\n      state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n      state.batchSellTradesLoadingStatus =\n        DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTradesLoadingStatus;\n    });\n  };\n\n  /**\n   * Sets the interval length based on the source chain\n   */\n  setChainIntervalLength = () => {\n    const { state } = this;\n    // Assume that BatchSell quote requests all have the same source chain\n    // Use the first one to determine refresh rate\n    const { srcChainId } = state.quoteRequest[0];\n    const bridgeFeatureFlags = getBridgeFeatureFlags(this.messenger);\n\n    const refreshRateOverride = srcChainId\n      ? bridgeFeatureFlags.chains[formatChainIdToCaip(srcChainId)]?.refreshRate\n      : undefined;\n    const defaultRefreshRate = bridgeFeatureFlags.refreshRate;\n    this.setIntervalLength(refreshRateOverride ?? defaultRefreshRate);\n  };\n\n  readonly #fetchBridgeQuotes = async ({\n    quoteRequests,\n    context,\n  }: BridgePollingInput) => {\n    this.#abortController?.abort(AbortReason.NewQuoteRequest);\n    this.#batchSellTradesAbortController?.abort(AbortReason.NewQuoteRequest);\n\n    this.#abortController = new AbortController();\n\n    this.#fetchAssetExchangeRates(quoteRequests).catch((error) =>\n      console.warn('Failed to fetch asset exchange rates', error),\n    );\n\n    this.trackUnifiedSwapBridgeEvent(\n      UnifiedSwapBridgeEventName.QuotesRequested,\n      context,\n    );\n\n    const { sse, maxRefreshCount } = getBridgeFeatureFlags(this.messenger);\n    const shouldStream =\n      sse?.enabled &&\n      hasMinimumRequiredVersion(this.#clientVersion, sse.minimumVersion);\n    const isBatchSellRequest = quoteRequests.length > 1;\n\n    this.update((state) => {\n      state.quoteFetchError = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteFetchError;\n      state.tokenWarnings = DEFAULT_BRIDGE_CONTROLLER_STATE.tokenWarnings;\n      state.quoteStreamComplete =\n        DEFAULT_BRIDGE_CONTROLLER_STATE.quoteStreamComplete;\n      state.quotesLastFetched = Date.now();\n      state.quotesLoadingStatus = RequestStatus.LOADING;\n      // Prevent clients from displaying stale batch sell fees\n      if (quoteRequests.length > 1) {\n        state.batchSellTradesLoadingStatus = RequestStatus.LOADING;\n        state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n      }\n    });\n\n    const jwt = await this.#getJwt();\n\n    try {\n      const [firstQuoteRequest] = quoteRequests;\n\n      const unifiedSwapTraceName = isCrossChain(\n        firstQuoteRequest.srcChainId,\n        firstQuoteRequest.destChainId,\n      )\n        ? TraceName.BridgeQuotesFetched\n        : TraceName.SwapQuotesFetched;\n\n      await this.#trace(\n        {\n          name: isBatchSellRequest\n            ? TraceName.BatchSellQuotesFetched\n            : unifiedSwapTraceName,\n          data: {\n            srcChainId: formatChainIdToCaip(firstQuoteRequest.srcChainId),\n            destChainId: formatChainIdToCaip(firstQuoteRequest.destChainId),\n          },\n        },\n        async () => {\n          const selectedAccount = this.#getMultichainSelectedAccount(\n            firstQuoteRequest.walletAddress,\n          );\n          // This call is not awaited to prevent blocking quote fetching if the snap takes too long to respond\n          // eslint-disable-next-line @typescript-eslint/no-floating-promises\n          this.#setMinimumBalanceForRentExemptionInLamports(\n            firstQuoteRequest.srcChainId,\n            selectedAccount?.metadata?.snap?.id,\n          );\n          // Use SSE if enabled and return early\n          if (shouldStream || isBatchSellRequest) {\n            await this.#handleQuoteStreaming(\n              quoteRequests,\n              context.feature_id,\n              jwt,\n              selectedAccount,\n            );\n            return;\n          }\n          // Otherwise use regular fetch\n          const quotes = await this.fetchQuotes(\n            firstQuoteRequest,\n            context.feature_id,\n            this.#abortController?.signal,\n          );\n          this.update((state) => {\n            // Set the initial load time if this is the first fetch\n            if (\n              state.quotesRefreshCount ===\n                DEFAULT_BRIDGE_CONTROLLER_STATE.quotesRefreshCount &&\n              this.#quotesFirstFetched\n            ) {\n              state.quotesInitialLoadTime =\n                Date.now() - this.#quotesFirstFetched;\n            }\n            state.quotes = quotes;\n            state.quotesLoadingStatus = RequestStatus.FETCHED;\n          });\n        },\n      );\n    } catch (error) {\n      // Reset the quotes list if the fetch fails to avoid showing stale quotes\n      this.update((state) => {\n        state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n      });\n      // Ignore abort errors\n      if (\n        (error as Error).toString().includes('AbortError') ||\n        (error as Error).toString().includes('FetchRequestCanceledException') ||\n        [\n          AbortReason.ResetState,\n          AbortReason.NewQuoteRequest,\n          AbortReason.QuoteRequestUpdated,\n          AbortReason.TransactionSubmitted,\n        ].includes(error as AbortReason)\n      ) {\n        // Exit the function early to prevent other state updates\n        return;\n      }\n\n      // Update loading status and error message\n      this.update((state) => {\n        // The error object reference is not guaranteed to exist on mobile so reading\n        // the message directly could cause an error.\n        let errorMessage;\n        try {\n          errorMessage =\n            (error as Error)?.message ?? (error as Error).toString();\n        } catch {\n          // Intentionally empty\n        } finally {\n          state.quoteFetchError = errorMessage ?? 'Unknown error';\n        }\n        state.quotesLoadingStatus = RequestStatus.ERROR;\n      });\n      // Track event and log error\n      this.trackUnifiedSwapBridgeEvent(\n        UnifiedSwapBridgeEventName.QuotesError,\n        context,\n      );\n      console.log(\n        `Failed to ${shouldStream ? 'stream' : 'fetch'} bridge quotes`,\n        error,\n      );\n    }\n\n    // Update refresh count after fetching, validation and fee calculation have completed\n    this.update((state) => {\n      state.quotesRefreshCount += 1;\n    });\n    const hasNoFundedQuoteRequests = quoteRequests.every(\n      ({ insufficientBal }) => Boolean(insufficientBal),\n    );\n\n    if (\n      hasNoFundedQuoteRequests\n        ? // If all quote requests are insufficiently funded, stop polling\n          // So if a BatchSell has at least 1 sufficiently funded quote request, polling continues\n          true\n        : // Otherwise continue polling until the maximum number of refreshes has been reached\n          this.state.quotesRefreshCount >= maxRefreshCount\n    ) {\n      this.stopAllPolling();\n    }\n  };\n\n  readonly #handleQuoteStreaming = async (\n    quoteRequests: GenericQuoteRequest[],\n    featureId: FeatureId,\n    jwt?: string,\n    selectedAccount?: InternalAccount,\n  ) => {\n    /**\n     * Tracks the number of valid quotes received from the current stream, which is used\n     * to determine when to clear the quotes list and set the initial load time\n     */\n    let validQuotesCounter = 0;\n    /**\n     * Tracks all pending promises from appendFeesToQuotes calls to ensure they complete\n     * before setting quotesLoadingStatus to FETCHED\n     */\n    const pendingFeeAppendPromises = new Set<Promise<void>>();\n\n    await fetchBridgeQuoteStream(\n      this.#fetchFn,\n      quoteRequests,\n      this.#abortController?.signal,\n      featureId,\n      this.#clientId,\n      jwt,\n      this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n      {\n        onQuoteValidationFailure: (validationFailures) =>\n          this.#trackQuoteValidationFailures(validationFailures, featureId),\n        onValidQuoteReceived: async (quote: QuoteResponseV1) => {\n          const feeAppendPromise = (async () => {\n            const quotesWithFees = await appendFeesToQuotes(\n              [quote],\n              this.messenger,\n              this.#getLayer1GasFee,\n              selectedAccount,\n            );\n            if (quotesWithFees.length > 0) {\n              validQuotesCounter += 1;\n            }\n            this.update((state) => {\n              // Clear previous quotes and quotes load time when first quote in the current\n              // polling loop is received\n              // This enables clients to continue showing the previous quotes while new\n              // quotes are loading\n              // Note: If there are no valid quotes until the 2nd fetch, quotesInitialLoadTime will be > refreshRate\n              if (validQuotesCounter === 1) {\n                state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n                if (!state.quotesInitialLoadTime && this.#quotesFirstFetched) {\n                  // Set the initial load time after the first quote is received\n                  state.quotesInitialLoadTime =\n                    Date.now() - this.#quotesFirstFetched;\n                }\n              }\n              state.quotes = [...state.quotes, ...quotesWithFees];\n            });\n          })();\n          pendingFeeAppendPromises.add(feeAppendPromise);\n          feeAppendPromise\n            .catch((error) => {\n              // Catch errors to prevent them from breaking stream processing\n              // If appendFeesToQuotes throws, the state update never happens, so no invalid entry is added\n              console.error('Error appending fees to quote', error);\n            })\n            .finally(() => {\n              pendingFeeAppendPromises.delete(feeAppendPromise);\n            });\n          // Await the promise to ensure errors are caught and handled before continuing\n          // The promise is also tracked in pendingFeeAppendPromises for onClose to wait for\n          await feeAppendPromise;\n        },\n        onTokenWarning: (warning) => {\n          this.update((state) => {\n            const isDuplicate = state.tokenWarnings.some(\n              (existing) => existing.feature_id === warning.feature_id,\n            );\n            if (!isDuplicate) {\n              state.tokenWarnings = [...state.tokenWarnings, warning];\n            }\n          });\n        },\n        onComplete: (data) => {\n          this.update((state) => {\n            state.quoteStreamComplete = data;\n          });\n        },\n        onClose: async () => {\n          // Wait for all pending appendFeesToQuotes operations to complete\n          // before setting quotesLoadingStatus to FETCHED\n          await Promise.allSettled(Array.from(pendingFeeAppendPromises));\n          this.update((state) => {\n            // If there are no valid quotes in the current stream, clear the quotes list\n            // to remove quotes from the previous stream\n            if (validQuotesCounter === 0) {\n              state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n            }\n            state.quotesLoadingStatus = RequestStatus.FETCHED;\n          });\n        },\n      },\n      this.#clientVersion,\n    );\n  };\n\n  readonly #setMinimumBalanceForRentExemptionInLamports = async (\n    srcChainId: GenericQuoteRequest['srcChainId'],\n    snapId?: string,\n  ) => {\n    if (!isSolanaChainId(srcChainId) || !snapId) {\n      return;\n    }\n    const minimumBalanceForRentExemptionInLamports =\n      await getMinimumBalanceForRentExemptionInLamports(snapId, this.messenger);\n    this.update((state) => {\n      state.minimumBalanceForRentExemptionInLamports =\n        minimumBalanceForRentExemptionInLamports;\n    });\n  };\n\n  #getMultichainSelectedAccount(\n    walletAddress?: GenericQuoteRequest['walletAddress'],\n  ) {\n    // Assume that all quotes in a batch are for the same account\n    const addressToUse =\n      walletAddress ?? this.state.quoteRequest[0].walletAddress;\n    if (!addressToUse) {\n      throw new Error('Account address is required');\n    }\n    const selectedAccount = this.messenger.call(\n      'AccountsController:getAccountByAddress',\n      addressToUse,\n    );\n    return selectedAccount;\n  }\n\n  #getNetworkClientByChainId(chainId: Hex) {\n    const networkClientId = this.messenger.call(\n      'NetworkController:findNetworkClientIdByChainId',\n      chainId,\n    );\n    if (!networkClientId) {\n      throw new Error(`No network client found for chainId: ${chainId}`);\n    }\n    const networkClient = this.messenger.call(\n      'NetworkController:getNetworkClientById',\n      networkClientId,\n    );\n    return networkClient;\n  }\n\n  readonly #getJwt = async (): Promise<string | undefined> => {\n    try {\n      const token = await this.messenger.call(\n        'AuthenticationController:getBearerToken',\n      );\n      return token;\n    } catch (error) {\n      console.error('Error getting JWT token for bridge-api request', error);\n      return undefined;\n    }\n  };\n\n  readonly #getRequestMetadata = (\n    quoteRequestIndex: number = 0,\n  ): Omit<\n    RequestMetadata,\n    'stx_enabled' | 'usd_amount_source' | 'security_warnings'\n  > => {\n    const quoteRequest = this.state.quoteRequest[quoteRequestIndex];\n    const { walletAddress } = quoteRequest;\n    const accountHardwareType = getAccountHardwareType(\n      walletAddress\n        ? this.#getMultichainSelectedAccount(walletAddress)\n        : undefined,\n    );\n\n    return {\n      slippage_limit: quoteRequest.slippage,\n      swap_type: getSwapTypeFromQuote(quoteRequest),\n      custom_slippage: isCustomSlippage(quoteRequest.slippage),\n      account_hardware_type: accountHardwareType,\n      is_hardware_wallet: accountHardwareType !== null,\n    };\n  };\n\n  readonly #getQuoteFetchData = (): Omit<\n    QuoteFetchData,\n    'best_quote_provider' | 'price_impact' | 'can_submit'\n  > => {\n    return {\n      quotes_count: this.state.quotes.length,\n      quotes_list: this.state.quotes.map(({ quote }) =>\n        formatProviderLabel(quote),\n      ),\n      initial_load_time_all_quotes: this.state.quotesInitialLoadTime ?? 0,\n      has_gas_included_quote: this.state.quotes.some(\n        ({ quote }) => quote.gasIncluded,\n      ),\n    };\n  };\n\n  readonly #getEventProperties = <\n    EventName extends\n      (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n  >(\n    eventName: EventName,\n    propertiesFromClient: Pick<\n      RequiredEventContextFromClient,\n      EventName\n    >[EventName],\n    quoteRequestIndex: number = 0,\n  ): CrossChainSwapsEventProperties<EventName> => {\n    const clientProps = propertiesFromClient as Record<string, unknown>;\n    const baseProperties = {\n      ...propertiesFromClient,\n      location: clientProps?.location ?? this.#location,\n      action_type: MetricsActionType.SWAPBRIDGE_V1,\n    };\n    const inputPrimaryDenominationProperties = {\n      input_primary_denomination: this.state.inputPrimaryDenomination,\n    };\n    const quoteRequest = this.state.quoteRequest[quoteRequestIndex];\n    switch (eventName) {\n      case UnifiedSwapBridgeEventName.ButtonClicked:\n        return {\n          ...getRequestParams(\n            quoteRequest,\n            this.state.tokenSecurityTypeDestination,\n          ),\n          ...baseProperties,\n        };\n      case UnifiedSwapBridgeEventName.PageViewed:\n        return {\n          ...getRequestParams(\n            quoteRequest,\n            this.state.tokenSecurityTypeDestination,\n          ),\n          ...this.#getRequestMetadata(),\n          ...inputPrimaryDenominationProperties,\n          ...baseProperties,\n        };\n      case UnifiedSwapBridgeEventName.FiatCryptoToggleClicked:\n        return {\n          ...getRequestParams(\n            quoteRequest,\n            this.state.tokenSecurityTypeDestination,\n          ),\n          swap_type: getSwapTypeFromQuote(quoteRequest),\n          ...baseProperties,\n        };\n      case UnifiedSwapBridgeEventName.QuotesValidationFailed:\n        return {\n          ...getRequestParams(\n            quoteRequest,\n            this.state.tokenSecurityTypeDestination,\n          ),\n          refresh_count: this.state.quotesRefreshCount,\n          ...baseProperties,\n        };\n      case UnifiedSwapBridgeEventName.QuotesReceived:\n        return {\n          ...getRequestParams(\n            quoteRequest,\n            this.state.tokenSecurityTypeDestination,\n          ),\n          ...this.#getRequestMetadata(),\n          ...this.#getQuoteFetchData(),\n          refresh_count: this.state.quotesRefreshCount,\n          ...inputPrimaryDenominationProperties,\n          ...baseProperties,\n        };\n      case UnifiedSwapBridgeEventName.QuotesRequested:\n        return {\n          ...getRequestParams(\n            quoteRequest,\n            this.state.tokenSecurityTypeDestination,\n          ),\n          ...this.#getRequestMetadata(),\n          has_sufficient_funds: !quoteRequest.insufficientBal,\n          ...inputPrimaryDenominationProperties,\n          ...baseProperties,\n        };\n      case UnifiedSwapBridgeEventName.QuotesError:\n        return {\n          ...getRequestParams(\n            quoteRequest,\n            this.state.tokenSecurityTypeDestination,\n          ),\n          ...this.#getRequestMetadata(),\n          error_message: this.state.quoteFetchError,\n          has_sufficient_funds: !quoteRequest.insufficientBal,\n          ...baseProperties,\n        };\n      case UnifiedSwapBridgeEventName.AllQuotesOpened:\n      case UnifiedSwapBridgeEventName.AllQuotesSorted:\n      case UnifiedSwapBridgeEventName.QuoteSelected:\n        return {\n          ...getRequestParams(\n            quoteRequest,\n            this.state.tokenSecurityTypeDestination,\n          ),\n          ...this.#getRequestMetadata(),\n          ...this.#getQuoteFetchData(),\n          ...baseProperties,\n        };\n      case UnifiedSwapBridgeEventName.Failed: {\n        // Populate the properties that the error occurred before the tx was submitted\n        return {\n          ...baseProperties,\n          ...getRequestParams(\n            quoteRequest,\n            this.state.tokenSecurityTypeDestination,\n          ),\n          ...this.#getRequestMetadata(),\n          ...this.#getQuoteFetchData(),\n          ...propertiesFromClient,\n        };\n      }\n      case UnifiedSwapBridgeEventName.AssetDetailTooltipClicked:\n      case UnifiedSwapBridgeEventName.AssetPickerOpened:\n        return baseProperties;\n      // Inject `token_security_type_destination` from controller state so the\n      // field is always present on this event. `baseProperties` (which spreads\n      // `propertiesFromClient`) wins if the client supplies a value explicitly.\n      case UnifiedSwapBridgeEventName.InputSourceDestinationSwitched:\n        return {\n          token_security_type_destination:\n            this.state.tokenSecurityTypeDestination,\n          ...baseProperties,\n        };\n      // These events may be published after the bridge-controller state is reset\n      // So the BridgeStatusController populates all the properties\n      case UnifiedSwapBridgeEventName.Submitted:\n      case UnifiedSwapBridgeEventName.Completed:\n        return propertiesFromClient;\n      case UnifiedSwapBridgeEventName.InputChanged:\n      default:\n        return baseProperties;\n    }\n  };\n\n  readonly #trackInputChangedEvents = (\n    paramsToUpdate: Partial<GenericQuoteRequest>,\n    featureId: FeatureId,\n    quoteRequestIndex: number = 0,\n  ) => {\n    Object.entries(paramsToUpdate).forEach(([key, value]) => {\n      const inputKey = toInputChangedPropertyKey[key as keyof QuoteRequest];\n      const inputValue =\n        toInputChangedPropertyValue[key as keyof QuoteRequest]?.(\n          paramsToUpdate,\n        );\n      if (\n        inputKey &&\n        inputValue !== undefined &&\n        this.state.quoteRequest[quoteRequestIndex] &&\n        value !==\n          this.state.quoteRequest[quoteRequestIndex][\n            key as keyof GenericQuoteRequest\n          ]\n      ) {\n        this.trackUnifiedSwapBridgeEvent(\n          UnifiedSwapBridgeEventName.InputChanged,\n          {\n            input: inputKey,\n            input_value: inputValue,\n            location: this.#location,\n            feature_id: featureId,\n          },\n        );\n      }\n    });\n  };\n\n  /**\n   * This method tracks cross-chain swaps events\n   *\n   * @param eventName - The name of the event to track\n   * @param propertiesFromClient - Properties that can't be calculated from the event name and need to be provided by the client\n   * @param quoteRequestIndex - The index of the quote request to track the event for\n   * @example\n   * this.trackUnifiedSwapBridgeEvent(UnifiedSwapBridgeEventName.ActionOpened, {\n   *   location: MetaMetricsSwapsEventSource.MainView,\n   * });\n   */\n  trackUnifiedSwapBridgeEvent = <\n    EventName extends\n      (typeof UnifiedSwapBridgeEventName)[keyof typeof UnifiedSwapBridgeEventName],\n  >(\n    eventName: EventName,\n    propertiesFromClient: Pick<\n      RequiredEventContextFromClient,\n      EventName\n    >[EventName],\n    quoteRequestIndex: number = 0,\n  ) => {\n    try {\n      const combinedPropertiesForEvent = this.#getEventProperties<EventName>(\n        eventName,\n        propertiesFromClient,\n        quoteRequestIndex,\n      );\n\n      this.#trackMetaMetricsFn(eventName, combinedPropertiesForEvent);\n    } catch (error) {\n      console.error(\n        `Error tracking cross-chain swaps MetaMetrics event ${eventName}`,\n        error,\n      );\n    }\n  };\n\n  /**\n   *\n   * @param walletAddress - The address of the account to get the allowance for\n   * @param contractAddress - The address of the ERC20 token contract on mainnet\n   * @param destinationChainId - The chain ID of the destination network\n   * @returns The atomic allowance of the ERC20 token contract\n   */\n  readonly #getUSDTMainnetAllowance = async (\n    walletAddress: string,\n    contractAddress: string,\n    destinationChainId: GenericQuoteRequest['destChainId'],\n  ): Promise<string> => {\n    const networkClient = this.#getNetworkClientByChainId(CHAIN_IDS.MAINNET);\n    const provider = networkClient?.provider;\n    if (!provider) {\n      throw new Error('No provider found');\n    }\n\n    const ethersProvider = new Web3Provider(provider);\n    const contract = new Contract(contractAddress, abiERC20, ethersProvider);\n    const spenderAddress = isCrossChain(CHAIN_IDS.MAINNET, destinationChainId)\n      ? METABRIDGE_ETHEREUM_ADDRESS\n      : SWAPS_CONTRACT_ADDRESSES[CHAIN_IDS.MAINNET];\n    const allowance: BigNumber = await contract.allowance(\n      walletAddress,\n      spenderAddress,\n    );\n    return allowance.toString();\n  };\n}\n"]}