@metamask-previews/bridge-controller 80.1.1-preview-cfd35b8dd → 80.1.1-preview-ea6a28c61
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.
- package/CHANGELOG.md +11 -0
- package/dist/bridge-controller.cjs +22 -10
- package/dist/bridge-controller.cjs.map +1 -1
- package/dist/bridge-controller.d.cts.map +1 -1
- package/dist/bridge-controller.d.mts.map +1 -1
- package/dist/bridge-controller.mjs +23 -11
- package/dist/bridge-controller.mjs.map +1 -1
- package/dist/index.cjs +7 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +3 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -1
- package/dist/utils/metrics/constants.cjs +26 -1
- package/dist/utils/metrics/constants.cjs.map +1 -1
- package/dist/utils/metrics/constants.d.cts +23 -0
- package/dist/utils/metrics/constants.d.cts.map +1 -1
- package/dist/utils/metrics/constants.d.mts +23 -0
- package/dist/utils/metrics/constants.d.mts.map +1 -1
- package/dist/utils/metrics/constants.mjs +25 -0
- package/dist/utils/metrics/constants.mjs.map +1 -1
- package/dist/utils/metrics/failure-telemetry.cjs +24 -0
- package/dist/utils/metrics/failure-telemetry.cjs.map +1 -0
- package/dist/utils/metrics/failure-telemetry.d.cts +12 -0
- package/dist/utils/metrics/failure-telemetry.d.cts.map +1 -0
- package/dist/utils/metrics/failure-telemetry.d.mts +12 -0
- package/dist/utils/metrics/failure-telemetry.d.mts.map +1 -0
- package/dist/utils/metrics/failure-telemetry.mjs +20 -0
- package/dist/utils/metrics/failure-telemetry.mjs.map +1 -0
- package/dist/utils/metrics/types.cjs.map +1 -1
- package/dist/utils/metrics/types.d.cts +19 -5
- package/dist/utils/metrics/types.d.cts.map +1 -1
- package/dist/utils/metrics/types.d.mts +19 -5
- package/dist/utils/metrics/types.d.mts.map +1 -1
- package/dist/utils/metrics/types.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Add SwapBridge failure telemetry schema and quote-fetch classifier for a later emit ([#9947](https://github.com/MetaMask/core/pull/9947))
|
|
13
|
+
- New exports: `FailurePhase`, `SwapBridgeErrorCode`, and `getQuoteFetchErrorCode` (classifies quote fetch from the code path, not from `error_message`)
|
|
14
|
+
- New type exports: `HashPresenceData` / `FailureTelemetryData` (optional Mixpanel event fields) and `HashPresenceProperties` / `FailureTelemetryProperties` (required classifier return shape)
|
|
15
|
+
- Optional `failure_phase` and `error_code` on Quotes Error and Failed event context types
|
|
16
|
+
- Optional `source_hash_present` and `destination_hash_present` on Failed, Submitted, and Completed event context types
|
|
17
|
+
- Submit and status classifiers live in `@metamask/bridge-status-controller`
|
|
18
|
+
- Emit `failure_phase` and `error_code` on Quotes Error events ([#9949](https://github.com/MetaMask/core/pull/9949))
|
|
19
|
+
- Emit `failure_phase`, `error_code`, `source_hash_present`, and `destination_hash_present` on Failed events ([#9949](https://github.com/MetaMask/core/pull/9949))
|
|
20
|
+
|
|
10
21
|
### Changed
|
|
11
22
|
|
|
12
23
|
- Bump `@metamask/assets-controller` from `^14.0.2` to `^14.0.3` ([#10042](https://github.com/MetaMask/core/pull/10042))
|
|
@@ -33,6 +33,7 @@ const caip_formatters_js_1 = require("./utils/caip-formatters.cjs");
|
|
|
33
33
|
const feature_flags_js_1 = require("./utils/feature-flags.cjs");
|
|
34
34
|
const fetch_js_1 = require("./utils/fetch.cjs");
|
|
35
35
|
const constants_js_1 = require("./utils/metrics/constants.cjs");
|
|
36
|
+
const failure_telemetry_js_1 = require("./utils/metrics/failure-telemetry.cjs");
|
|
36
37
|
const properties_js_1 = require("./utils/metrics/properties.cjs");
|
|
37
38
|
const quote_fees_js_1 = require("./utils/quote-fees.cjs");
|
|
38
39
|
const snaps_js_1 = require("./utils/snaps.cjs");
|
|
@@ -648,7 +649,11 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
|
|
|
648
649
|
state.quotesLoadingStatus = types_js_1.RequestStatus.ERROR;
|
|
649
650
|
});
|
|
650
651
|
// Track event and log error
|
|
651
|
-
this.trackUnifiedSwapBridgeEvent(constants_js_1.UnifiedSwapBridgeEventName.QuotesError,
|
|
652
|
+
this.trackUnifiedSwapBridgeEvent(constants_js_1.UnifiedSwapBridgeEventName.QuotesError, {
|
|
653
|
+
...context,
|
|
654
|
+
failure_phase: constants_js_1.FailurePhase.Quote,
|
|
655
|
+
error_code: (0, failure_telemetry_js_1.getQuoteFetchErrorCode)(error),
|
|
656
|
+
});
|
|
652
657
|
console.log(`Failed to ${shouldStream ? 'stream' : 'fetch'} bridge quotes`, error);
|
|
653
658
|
}
|
|
654
659
|
finally {
|
|
@@ -910,18 +915,12 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
|
|
|
910
915
|
...__classPrivateFieldGet(this, _BridgeController_getRequestMetadata, "f").call(this),
|
|
911
916
|
error_message: this.state.quoteFetchError,
|
|
912
917
|
has_sufficient_funds: !quoteRequest.insufficientBal,
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
case constants_js_1.UnifiedSwapBridgeEventName.AllQuotesOpened:
|
|
916
|
-
case constants_js_1.UnifiedSwapBridgeEventName.AllQuotesSorted:
|
|
917
|
-
case constants_js_1.UnifiedSwapBridgeEventName.QuoteSelected:
|
|
918
|
-
return {
|
|
919
|
-
...(0, properties_js_1.getRequestParams)(quoteRequest, this.state.tokenSecurityTypeDestination),
|
|
920
|
-
...__classPrivateFieldGet(this, _BridgeController_getRequestMetadata, "f").call(this),
|
|
921
|
-
...__classPrivateFieldGet(this, _BridgeController_getQuoteFetchData, "f").call(this),
|
|
918
|
+
failure_phase: constants_js_1.FailurePhase.Quote,
|
|
919
|
+
error_code: constants_js_1.SwapBridgeErrorCode.QuoteFetchFailed,
|
|
922
920
|
...baseProperties,
|
|
923
921
|
};
|
|
924
922
|
case constants_js_1.UnifiedSwapBridgeEventName.Failed: {
|
|
923
|
+
const failedClientProperties = propertiesFromClient;
|
|
925
924
|
// Populate the properties that the error occurred before the tx was submitted
|
|
926
925
|
return {
|
|
927
926
|
...baseProperties,
|
|
@@ -929,8 +928,21 @@ class BridgeController extends (0, polling_controller_1.StaticIntervalPollingCon
|
|
|
929
928
|
...__classPrivateFieldGet(this, _BridgeController_getRequestMetadata, "f").call(this),
|
|
930
929
|
...__classPrivateFieldGet(this, _BridgeController_getQuoteFetchData, "f").call(this),
|
|
931
930
|
...propertiesFromClient,
|
|
931
|
+
failure_phase: failedClientProperties.failure_phase ?? constants_js_1.FailurePhase.Unknown,
|
|
932
|
+
error_code: failedClientProperties.error_code ?? constants_js_1.SwapBridgeErrorCode.Unknown,
|
|
933
|
+
source_hash_present: failedClientProperties.source_hash_present ?? false,
|
|
934
|
+
destination_hash_present: failedClientProperties.destination_hash_present ?? false,
|
|
932
935
|
};
|
|
933
936
|
}
|
|
937
|
+
case constants_js_1.UnifiedSwapBridgeEventName.AllQuotesOpened:
|
|
938
|
+
case constants_js_1.UnifiedSwapBridgeEventName.AllQuotesSorted:
|
|
939
|
+
case constants_js_1.UnifiedSwapBridgeEventName.QuoteSelected:
|
|
940
|
+
return {
|
|
941
|
+
...(0, properties_js_1.getRequestParams)(quoteRequest, this.state.tokenSecurityTypeDestination),
|
|
942
|
+
...__classPrivateFieldGet(this, _BridgeController_getRequestMetadata, "f").call(this),
|
|
943
|
+
...__classPrivateFieldGet(this, _BridgeController_getQuoteFetchData, "f").call(this),
|
|
944
|
+
...baseProperties,
|
|
945
|
+
};
|
|
934
946
|
case constants_js_1.UnifiedSwapBridgeEventName.AssetDetailTooltipClicked:
|
|
935
947
|
case constants_js_1.UnifiedSwapBridgeEventName.AssetPickerOpened:
|
|
936
948
|
return baseProperties;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-controller.cjs","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qEAAqE;AACrE,wDAAqD;AACrD,wDAAoD;AACpD,wDAAwD;AAIxD,mEAAuD;AACvD,qEAA+E;AAG/E,+BAAkC;AAElC,uFAA0E;AAE1E,sDAM+B;AAC/B,sDAAkD;AAClD,oDAAgE;AAChE,sDAAkD;AAClD,0CAA2C;AAW3C,kDAAyE;AACzE,oDAA0D;AAC1D,kDAM2B;AAC3B,oEAIoC;AACpC,gEAGkC;AAClC,gDAK0B;AAC1B,gEAMsC;AAKtC,kEASuC;AAOvC,0DAA2D;AAC3D,gDAA+E;AAC/E,4DAAoD;AAEpD,qEAGuC;AAIvC,MAAM,QAAQ,GAAyC;IACrD,YAAY,EAAE;QACZ,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,MAAM,EAAE;QACN,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,qBAAqB,EAAE;QACrB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,iBAAiB,EAAE;QACjB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,mBAAmB,EAAE;QACnB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,eAAe,EAAE;QACf,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KA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,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, TraceRequest } 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';\nimport { v4 as uuid } from 'uuid';\n\nimport { toQuoteResponseV2 } from './coercers/quote-response-v1-to-v2.js';\nimport type { BridgeClientId } from './constants/bridge.js';\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.js';\nimport { CHAIN_IDS } from './constants/chains.js';\nimport { SWAPS_CONTRACT_ADDRESSES } from './constants/swaps.js';\nimport { TraceName } from './constants/traces.js';\nimport { RequestStatus } from './types.js';\nimport type {\n L1GasFees,\n GenericQuoteRequest,\n NonEvmFees,\n QuoteRequest,\n BridgeControllerState,\n BridgeControllerMessenger,\n FetchFunction,\n InputPrimaryDenomination,\n} from './types.js';\nimport { getAssetIdsForToken, toExchangeRates } from './utils/assets.js';\nimport { hasSufficientBalance } from './utils/balance.js';\nimport {\n getDefaultBridgeControllerState,\n isCrossChain,\n isEthUsdt,\n isNonEvmChainId,\n isSolanaChainId,\n} from './utils/bridge.js';\nimport {\n formatAddressToCaipReference,\n formatChainIdToCaip,\n formatChainIdToHex,\n} from './utils/caip-formatters.js';\nimport {\n getBridgeFeatureFlags,\n hasMinimumRequiredVersion,\n} from './utils/feature-flags.js';\nimport {\n fetchAssetPrices,\n fetchBridgeQuotes,\n fetchBridgeQuoteStream,\n fetchBatchSellTrades,\n} from './utils/fetch.js';\nimport {\n AbortReason,\n BatchSellMetricsEventName,\n MetaMetricsSwapsEventSource,\n MetricsActionType,\n UnifiedSwapBridgeEventName,\n} from './utils/metrics/constants.js';\nimport type {\n BridgeControllerMetricsEventName,\n BridgeControllerMetricsLocation,\n} from './utils/metrics/constants.js';\nimport {\n formatProviderLabel,\n getAccountHardwareType,\n getRequestParams,\n getSwapType,\n getSwapTypeFromQuote,\n isCustomSlippage,\n toInputChangedPropertyKey,\n toInputChangedPropertyValue,\n} from './utils/metrics/properties.js';\nimport type {\n QuoteFetchData,\n RequestMetadata,\n RequiredEventContextFromClient,\n} from './utils/metrics/types.js';\nimport type { CrossChainSwapsEventProperties } from './utils/metrics/types.js';\nimport { appendFeesToQuotes } from './utils/quote-fees.js';\nimport { getMinimumBalanceForRentExemptionInLamports } from './utils/snaps.js';\nimport { sortQuotes } from './utils/sort-quotes.js';\nimport type { FeatureId } from './validators/feature-flags.js';\nimport {\n isValidQuoteRequest,\n isValidBatchSellQuoteRequest,\n} from './validators/quote-request.js';\nimport type { QuoteResponseV1 } from './validators/quote-response-v1.js';\nimport type { QuoteResponse } from './validators/quote-response.js';\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\ntype QuoteTraceResult = 'success' | 'cancelled' | 'no_quotes' | 'error';\n\nconst QUOTE_ABORT_REASONS = new Set<string>(Object.values(AbortReason));\n\nconst isExpectedQuoteAbort = (\n error: unknown,\n signal?: AbortSignal,\n): boolean => {\n if (signal?.aborted) {\n return true;\n }\n\n if (QUOTE_ABORT_REASONS.has(String(error))) {\n return true;\n }\n\n const errorText =\n error instanceof Error ? `${error.name} ${error.message}` : String(error);\n\n return (\n errorText.includes('AbortError') ||\n errorText.includes('FetchRequestCanceledException')\n );\n};\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'updateBridgeQuoteRequestParams',\n 'fetchQuotes',\n 'updateBatchSellTrades',\n 'stopPollingForQuotes',\n 'setLocation',\n 'getLocation',\n 'setInputPrimaryDenomination',\n 'resetState',\n 'setChainIntervalLength',\n 'trackUnifiedSwapBridgeEvent',\n] as const;\n\nexport class BridgeController extends StaticIntervalPollingController<BridgePollingInput>()<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState,\n BridgeControllerMessenger\n> {\n #abortController: AbortController | undefined;\n\n #batchSellTradesAbortController: AbortController | undefined;\n\n #quotesFirstFetched: number | undefined;\n\n /**\n * Stores the location/entry point from which the user initiated the swap or bridge flow.\n * Set via setLocation() before navigating to the swap/bridge flow.\n * Used as default for all subsequent internal events.\n */\n #location: BridgeControllerMetricsLocation =\n MetaMetricsSwapsEventSource.Unknown;\n\n readonly #clientId: BridgeClientId;\n\n readonly #clientVersion: string;\n\n readonly #getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n\n readonly #fetchFn: FetchFunction;\n\n readonly #trackMetaMetricsFn: <\n EventName extends BridgeControllerMetricsEventName,\n >(\n eventName: EventName,\n properties: CrossChainSwapsEventProperties<EventName>,\n ) => void;\n\n readonly #trace: TraceCallback;\n\n readonly #config: {\n customBridgeApiBaseUrl?: string;\n };\n\n /**\n * Returns whether to use AssetsController for exchange rates.\n * Set via constructor option getUseAssetsControllerForRates; defaults to false.\n *\n * @returns True when exchange rates should be read from AssetsController:getExchangeRatesForBridge.\n */\n readonly #getUseAssetsControllerForRates: () => boolean;\n\n constructor({\n messenger,\n state,\n clientId,\n clientVersion,\n getLayer1GasFee,\n fetchFn,\n config,\n trackMetaMetricsFn,\n traceFn,\n getUseAssetsControllerForRates,\n }: {\n messenger: BridgeControllerMessenger;\n state?: Partial<BridgeControllerState>;\n clientId: BridgeClientId;\n clientVersion: string;\n getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n fetchFn: FetchFunction;\n config?: {\n customBridgeApiBaseUrl?: string;\n };\n trackMetaMetricsFn: <EventName extends BridgeControllerMetricsEventName>(\n eventName: EventName,\n properties: CrossChainSwapsEventProperties<EventName>,\n ) => void;\n traceFn?: TraceCallback;\n /**\n * When provided, called to determine whether to use AssetsController for exchange rates.\n * When true, rates are read from AssetsController:getExchangeRatesForBridge instead of\n * MultichainAssetsRatesController, TokenRatesController, and CurrencyRateController.\n */\n getUseAssetsControllerForRates?: () => boolean;\n }) {\n super({\n name: BRIDGE_CONTROLLER_NAME,\n metadata,\n messenger,\n state: {\n ...getDefaultBridgeControllerState(),\n ...state,\n },\n });\n\n this.setIntervalLength(REFRESH_INTERVAL_MS);\n\n this.#abortController = new AbortController();\n this.#getLayer1GasFee = getLayer1GasFee;\n this.#clientId = clientId;\n this.#clientVersion = clientVersion;\n this.#fetchFn = fetchFn;\n this.#trackMetaMetricsFn = trackMetaMetricsFn;\n this.#config = config ?? {};\n this.#trace = traceFn ?? (((_request, fn) => fn?.()) as TraceCallback);\n this.#getUseAssetsControllerForRates =\n getUseAssetsControllerForRates ?? (() => false);\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n _executePoll = async (pollingInput: BridgePollingInput) => {\n await this.#fetchBridgeQuotes(pollingInput);\n };\n\n /**\n * Updates the quote request at the specified index with the given parameters, then starts\n * polling for quotes.\n *\n * @param paramsToUpdate - The parameters to update in the quote request at the specified index\n * @param context - metrics context\n * @param quoteRequestIndex - The index of the quote request to update\n * @param quoteRequestCount - The number of quote requests in the UI\n */\n updateBridgeQuoteRequestParams = async (\n paramsToUpdate: Partial<GenericQuoteRequest> & {\n walletAddress: GenericQuoteRequest['walletAddress'];\n },\n context: BridgePollingInput['context'],\n quoteRequestIndex: number = 0,\n quoteRequestCount: number = 1,\n ) => {\n // Guard against updating a quote request that doesn't exist\n if (quoteRequestIndex >= quoteRequestCount) {\n return;\n }\n this.#trackInputChangedEvents(\n paramsToUpdate,\n context.feature_id,\n quoteRequestIndex,\n );\n this.resetState(AbortReason.QuoteRequestUpdated, quoteRequestIndex);\n this.update((state) => {\n // Update only the specified quote request and keep the rest of the quote requests unchanged\n state.quoteRequest = state.quoteRequest\n .slice(0, quoteRequestIndex)\n .concat({\n ...DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest[0],\n ...paramsToUpdate,\n })\n .concat(\n state.quoteRequest.slice(quoteRequestIndex + 1, quoteRequestCount),\n );\n state.tokenSecurityTypeDestination =\n context.token_security_type_destination ?? null;\n });\n\n // BatchSell and Unified swaps both use the same polling logic so both validations should pass\n if (\n isValidQuoteRequest(paramsToUpdate) &&\n isValidBatchSellQuoteRequest(this.state.quoteRequest)\n ) {\n this.#quotesFirstFetched = Date.now();\n // Update the insufficientBal and resetApproval params for the quote request\n const quoteWithInsufficientBalAndResetApproval =\n await this.#appendInsufficientBalAndResetApproval(paramsToUpdate);\n this.update((state) => {\n state.quoteRequest[quoteRequestIndex] =\n quoteWithInsufficientBalAndResetApproval;\n });\n\n // Set refresh rate based on the source chain before starting polling\n this.setChainIntervalLength();\n this.startPolling({\n quoteRequests: this.state.quoteRequest,\n context,\n });\n }\n };\n\n /**\n * Fetches quotes for specified request without updating the controller state\n * This method does not start polling for quotes and does not emit UnifiedSwapBridge events\n *\n * @param quoteRequest - The parameters for quote requests to fetch\n * @param featureId - The feature ID that maps to quoteParam overrides from LD\n * @param abortSignal - The abort signal to cancel all the requests\n * @returns A list of validated quotes\n */\n fetchQuotes = async (\n quoteRequest: GenericQuoteRequest,\n featureId: FeatureId,\n abortSignal: AbortSignal | null = null,\n ): Promise<(QuoteResponseV1 & L1GasFees & NonEvmFees)[]> => {\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messenger);\n const jwt = await this.#getJwt();\n // If featureId is specified, retrieve the quoteRequestOverrides for that featureId\n const quoteRequestOverrides = featureId\n ? bridgeFeatureFlags.quoteRequestOverrides?.[featureId]\n : undefined;\n const resetApproval = await this.#shouldResetApproval(quoteRequest);\n\n // If quoteRequestOverrides is specified, merge it with the quoteRequest\n const { quotes: baseQuotes, validationFailures } = await fetchBridgeQuotes(\n quoteRequestOverrides\n ? { ...quoteRequest, ...quoteRequestOverrides, resetApproval }\n : { ...quoteRequest, resetApproval },\n abortSignal,\n this.#clientId,\n jwt,\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n featureId,\n this.#clientVersion,\n );\n\n this.#trackQuoteValidationFailures(validationFailures, featureId);\n const srcChainIds = Array.from(\n new Set(baseQuotes.map((quote) => quote.quote.srcChainId)),\n ).filter(Boolean);\n\n const quotesWithFees =\n srcChainIds.length > 1 || srcChainIds.length === 0\n ? // Don't append fees if there are multiple srcChainIds\n baseQuotes\n : await appendFeesToQuotes(\n formatChainIdToCaip(srcChainIds[0]),\n baseQuotes,\n this.messenger,\n this.#getLayer1GasFee,\n this.#getMultichainSelectedAccount(quoteRequest.walletAddress),\n );\n\n return sortQuotes(quotesWithFees, featureId);\n };\n\n /**\n * Fetches gasless transaction data and fees for BatchSell quotes.\n * To use this in the clients, add a listener for the recommendedQuotes and call\n * this handler whenever they change.\n *\n * @param quotes - The quotes to fetch the gasless transaction data and fees for\n * @param stxEnabled - Flag to estimate gas cost more precisely for the batch sell feature.\n */\n updateBatchSellTrades = async (\n quotes: (QuoteResponse | null)[],\n stxEnabled: boolean,\n ): Promise<void> => {\n this.#batchSellTradesAbortController?.abort(\n AbortReason.GaslessTxBatchFetched,\n );\n this.#batchSellTradesAbortController = new AbortController();\n\n this.update((state) => {\n // Set loading status again if recommended quotes are re-ordered\n state.batchSellTradesLoadingStatus = RequestStatus.LOADING;\n });\n\n try {\n const batchSellTradesResponse = await fetchBatchSellTrades(\n quotes,\n stxEnabled,\n this.#batchSellTradesAbortController.signal,\n this.#clientId,\n await this.#getJwt(),\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n this.#clientVersion,\n );\n\n this.update((state) => {\n state.batchSellTrades = batchSellTradesResponse;\n state.batchSellTradesLoadingStatus = RequestStatus.FETCHED;\n });\n\n // TODO if fee.asset.assetId is not in exchange rates, fetch the exchange rate and update the state\n } catch (error) {\n // Ignore abort errors\n if (\n (error as Error).toString().includes('AbortError') ||\n (error as Error).toString().includes('FetchRequestCanceledException') ||\n [\n AbortReason.ResetState,\n AbortReason.NewQuoteRequest,\n AbortReason.QuoteRequestUpdated,\n AbortReason.TransactionSubmitted,\n AbortReason.GaslessTxBatchFetched,\n ].includes(error as AbortReason)\n ) {\n // Exit the function early to prevent other state updates\n return;\n }\n\n this.update((state) => {\n // Reset the batch sell trades if the fetch fails to avoid showing stale data\n state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n // Update loading status\n state.batchSellTradesLoadingStatus = RequestStatus.ERROR;\n });\n console.log(`Failed to fetch batch sell trades`, error);\n }\n };\n\n readonly #trackQuoteValidationFailures = (\n validationFailures: string[],\n featureId: FeatureId,\n ) => {\n if (validationFailures.length === 0) {\n return;\n }\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesValidationFailed,\n {\n feature_id: featureId,\n failures: validationFailures,\n location: this.#location,\n },\n );\n };\n\n /**\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 // Get unique assetIds for all quote requests\n const assetIds = new Set<CaipAssetType>(\n quoteRequests.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 );\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, 'usd']),\n clientId: this.#clientId,\n clientVersion: this.#clientVersion,\n fetchFn: this.#fetchFn,\n signal: this.#abortController?.signal,\n });\n const exchangeRates = toExchangeRates(currency, pricesByAssetId);\n this.update((state) => {\n state.assetExchangeRates = {\n ...state.assetExchangeRates,\n ...exchangeRates,\n };\n });\n };\n\n readonly #hasInsufficientBalance = async (\n quoteRequest: GenericQuoteRequest,\n ) => {\n try {\n const srcChainIdInHex = formatChainIdToHex(quoteRequest.srcChainId);\n const provider =\n this.#getNetworkClientByChainId(srcChainIdInHex)?.provider;\n const normalizedSrcTokenAddress = formatAddressToCaipReference(\n quoteRequest.srcTokenAddress,\n );\n\n return !(\n provider &&\n normalizedSrcTokenAddress &&\n quoteRequest.srcTokenAmount &&\n srcChainIdInHex &&\n (await hasSufficientBalance(\n provider,\n quoteRequest.walletAddress,\n normalizedSrcTokenAddress,\n quoteRequest.srcTokenAmount,\n srcChainIdInHex,\n ))\n );\n } catch (error) {\n console.warn('Failed to set insufficientBal', error);\n // Fall back to true so the backend returns quotes\n return true;\n }\n };\n\n readonly #appendInsufficientBalAndResetApproval = async (\n quoteRequest: GenericQuoteRequest,\n ) => {\n const isSrcChainNonEVM = isNonEvmChainId(quoteRequest.srcChainId);\n const providerConfig = isSrcChainNonEVM\n ? undefined\n : this.#getNetworkClientByChainId(\n formatChainIdToHex(quoteRequest.srcChainId),\n )?.configuration;\n\n let insufficientBal: boolean | undefined;\n let resetApproval: boolean = Boolean(quoteRequest.resetApproval);\n if (isSrcChainNonEVM) {\n // If the source chain is not an EVM network, use value from params\n insufficientBal = quoteRequest.insufficientBal;\n } else if (providerConfig?.rpcUrl?.includes('tenderly')) {\n // If the rpcUrl is a tenderly fork (e2e tests), set insufficientBal=true\n // The bridge-api filters out quotes if the balance on mainnet is insufficient so this override allows quotes to always be returned\n insufficientBal = true;\n } else {\n // Set loading status if RPC calls are made before the quotes are fetched\n this.update((state) => {\n state.quotesLoadingStatus = RequestStatus.LOADING;\n });\n resetApproval = await this.#shouldResetApproval(quoteRequest);\n // Otherwise query the src token balance from the RPC provider\n insufficientBal =\n quoteRequest.insufficientBal ??\n (await this.#hasInsufficientBalance(quoteRequest));\n }\n\n return {\n ...quoteRequest,\n insufficientBal,\n resetApproval,\n };\n };\n\n readonly #shouldResetApproval = async (quoteRequest: GenericQuoteRequest) => {\n if (isNonEvmChainId(quoteRequest.srcChainId)) {\n return false;\n }\n try {\n const normalizedSrcTokenAddress = formatAddressToCaipReference(\n quoteRequest.srcTokenAddress,\n );\n if (isEthUsdt(quoteRequest.srcChainId, normalizedSrcTokenAddress)) {\n const allowance = BigNumber.from(\n await this.#getUSDTMainnetAllowance(\n quoteRequest.walletAddress,\n normalizedSrcTokenAddress,\n quoteRequest.destChainId,\n ),\n );\n return allowance.lt(quoteRequest.srcTokenAmount) && allowance.gt(0);\n }\n return false;\n } catch (error) {\n console.warn('Failed to set resetApproval', error);\n // Fall back to true so the backend returns quotes\n return true;\n }\n };\n\n stopPollingForQuotes = (\n reason?: AbortReason,\n context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived],\n ) => {\n this.stopAllPolling();\n // If polling is stopped before quotes finish loading, track QuotesReceived\n if (this.state.quotesLoadingStatus === RequestStatus.LOADING && context) {\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesReceived,\n context,\n );\n }\n // Clears quotes list in state\n this.#abortController?.abort(reason);\n this.#batchSellTradesAbortController?.abort(reason);\n };\n\n /**\n * Sets the location/entry point for the current swap or bridge flow.\n * Call this when the user enters the flow so that all internally-fired\n * events (InputChanged, QuotesRequested, etc.) carry the correct location.\n *\n * @param location - The entry point from which the user initiated the flow\n */\n setLocation = (location: BridgeControllerMetricsLocation) => {\n this.#location = location;\n };\n\n /**\n * Returns the location/entry point for the current swap or bridge flow.\n *\n * @returns The entry point from which the user initiated the flow\n */\n getLocation = (): BridgeControllerMetricsLocation => {\n return this.#location;\n };\n\n setInputPrimaryDenomination = (\n inputPrimaryDenomination: InputPrimaryDenomination,\n ) => {\n this.update((state) => {\n state.inputPrimaryDenomination = inputPrimaryDenomination;\n });\n };\n\n resetState = (\n reason = AbortReason.ResetState,\n quoteRequestIndex: number | null = null,\n context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived],\n ) => {\n this.stopPollingForQuotes(reason, context);\n this.update((state) => {\n // Cannot do direct assignment to state, i.e. state = {... }, need to manually assign each field\n if (quoteRequestIndex === null) {\n // Clear all requests if index is null\n state.quoteRequest = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest;\n } else {\n // Otherwise only clear the specified request\n state.quoteRequest = state.quoteRequest\n .slice(0, quoteRequestIndex)\n .concat(DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest[0])\n .concat(state.quoteRequest.slice(quoteRequestIndex + 1));\n }\n state.quotesInitialLoadTime =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesInitialLoadTime;\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n state.quotesLastFetched =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesLastFetched;\n state.quotesLoadingStatus =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesLoadingStatus;\n state.quoteFetchError = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteFetchError;\n state.quotesRefreshCount =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesRefreshCount;\n state.assetExchangeRates =\n DEFAULT_BRIDGE_CONTROLLER_STATE.assetExchangeRates;\n state.minimumBalanceForRentExemptionInLamports =\n DEFAULT_BRIDGE_CONTROLLER_STATE.minimumBalanceForRentExemptionInLamports;\n state.tokenWarnings = DEFAULT_BRIDGE_CONTROLLER_STATE.tokenWarnings;\n state.tokenSecurityTypeDestination =\n DEFAULT_BRIDGE_CONTROLLER_STATE.tokenSecurityTypeDestination;\n state.quoteStreamComplete =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quoteStreamComplete;\n state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n state.batchSellTradesLoadingStatus =\n DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTradesLoadingStatus;\n });\n };\n\n /**\n * Sets the interval length based on the source chain\n */\n setChainIntervalLength = () => {\n const { state } = this;\n // Assume that BatchSell quote requests all have the same source chain\n // Use the first one to determine refresh rate\n const { srcChainId } = state.quoteRequest[0];\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messenger);\n\n const refreshRateOverride = srcChainId\n ? bridgeFeatureFlags.chains[formatChainIdToCaip(srcChainId)]?.refreshRate\n : undefined;\n const defaultRefreshRate = bridgeFeatureFlags.refreshRate;\n this.setIntervalLength(refreshRateOverride ?? defaultRefreshRate);\n };\n\n readonly #fetchBridgeQuotes = async ({\n quoteRequests,\n context,\n }: BridgePollingInput) => {\n this.#abortController?.abort(AbortReason.NewQuoteRequest);\n this.#batchSellTradesAbortController?.abort(AbortReason.NewQuoteRequest);\n\n this.#abortController = new AbortController();\n const quoteTraceStartTime = Date.now();\n const quoteTraceRequestId = uuid();\n const quoteAbortSignal = this.#abortController.signal;\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 const [firstQuoteRequest] = quoteRequests;\n let traceResult: QuoteTraceResult = 'error';\n let traceName = TraceName.BatchSellQuotesFetched;\n if (!isBatchSellRequest) {\n traceName = isCrossChain(\n firstQuoteRequest.srcChainId,\n firstQuoteRequest.destChainId,\n )\n ? TraceName.BridgeQuotesFetched\n : TraceName.SwapQuotesFetched;\n }\n const tracedProviders = new Set<string>();\n const traceWithoutImpact = async (request: TraceRequest): Promise<void> => {\n try {\n await this.#trace(request, () => undefined);\n } catch {\n // Telemetry failures must not affect quote fetching or state updates.\n }\n };\n const traceProviderFirstResult = (\n providerData: Parameters<typeof formatProviderLabel>[0],\n ) => {\n const provider = formatProviderLabel(providerData);\n if (isBatchSellRequest || tracedProviders.has(provider)) {\n return;\n }\n tracedProviders.add(provider);\n // Provider telemetry must not delay quote processing.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n traceWithoutImpact({\n name: TraceName.QuoteProviderFirstResult,\n startTime: quoteTraceStartTime,\n data: {\n provider,\n feature_id: context.feature_id,\n request_id: quoteTraceRequestId,\n swap_type: getSwapType(\n firstQuoteRequest.srcChainId,\n firstQuoteRequest.destChainId,\n ),\n srcChainId: formatChainIdToCaip(firstQuoteRequest.srcChainId),\n destChainId: formatChainIdToCaip(firstQuoteRequest.destChainId),\n result: 'success',\n },\n });\n };\n\n try {\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 const quoteCount = await this.#handleQuoteStreaming({\n quoteRequests,\n featureId: context.feature_id,\n jwt,\n selectedAccount,\n signal: quoteAbortSignal,\n traceProviderFirstResult,\n });\n if (quoteAbortSignal.aborted) {\n traceResult = 'cancelled';\n return;\n }\n traceResult = quoteCount > 0 ? 'success' : 'no_quotes';\n } else {\n // Otherwise use regular fetch\n const quotes = await this.fetchQuotes(\n firstQuoteRequest,\n context.feature_id,\n quoteAbortSignal,\n );\n for (const quote of quotes) {\n traceProviderFirstResult(quote.quote);\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 = Date.now() - this.#quotesFirstFetched;\n }\n state.quotes = quotes.map(toQuoteResponseV2);\n state.quotesLoadingStatus = RequestStatus.FETCHED;\n });\n traceResult = quotes.length > 0 ? 'success' : 'no_quotes';\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 (isExpectedQuoteAbort(error, quoteAbortSignal)) {\n traceResult = 'cancelled';\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 } finally {\n await traceWithoutImpact({\n name: traceName,\n startTime: quoteTraceStartTime,\n data: {\n srcChainId: formatChainIdToCaip(firstQuoteRequest.srcChainId),\n destChainId: formatChainIdToCaip(firstQuoteRequest.destChainId),\n ...(!isBatchSellRequest && {\n request_id: quoteTraceRequestId,\n feature_id: context.feature_id,\n result: traceResult,\n }),\n },\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,\n featureId,\n jwt,\n selectedAccount,\n signal,\n traceProviderFirstResult,\n }: {\n quoteRequests: GenericQuoteRequest[];\n featureId: FeatureId;\n jwt?: string;\n selectedAccount?: InternalAccount;\n signal?: AbortSignal;\n traceProviderFirstResult: (\n providerData: Parameters<typeof formatProviderLabel>[0],\n ) => void;\n }): Promise<number> => {\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 signal,\n featureId,\n this.#clientId,\n jwt,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n {\n onQuoteValidationFailure: (validationFailures) =>\n this.#trackQuoteValidationFailures(validationFailures, featureId),\n onValidQuoteReceived: async (quote: QuoteResponse) => {\n const feeAppendPromise = (async () => {\n const quotesWithFees = await appendFeesToQuotes(\n quote.chainId,\n [quote],\n this.messenger,\n this.#getLayer1GasFee,\n selectedAccount,\n );\n if (quotesWithFees.length > 0) {\n validQuotesCounter += 1;\n traceProviderFirstResult(quote.quote);\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 return validQuotesCounter;\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 ?? 0,\n swap_type: getSwapTypeFromQuote(quoteRequest),\n custom_slippage: isCustomSlippage(quoteRequest.slippage),\n account_hardware_type: accountHardwareType,\n is_hardware_wallet: accountHardwareType !== null,\n };\n };\n\n readonly #getQuoteFetchData = (): Omit<\n QuoteFetchData,\n 'best_quote_provider' | 'price_impact' | 'can_submit'\n > => {\n return {\n quotes_count: this.state.quotes.length,\n quotes_list: this.state.quotes.map(({ quote }) =>\n formatProviderLabel(quote),\n ),\n initial_load_time_all_quotes: this.state.quotesInitialLoadTime ?? 0,\n has_gas_included_quote: this.state.quotes.some(\n ({ quote }) => quote.gasIncluded,\n ),\n };\n };\n\n readonly #getEventProperties = <\n EventName extends BridgeControllerMetricsEventName,\n >(\n eventName: EventName,\n propertiesFromClient: Pick<\n RequiredEventContextFromClient,\n EventName\n >[EventName],\n quoteRequestIndex: number = 0,\n ) => {\n const clientProps = propertiesFromClient as Record<string, unknown>;\n const baseProperties = {\n ...propertiesFromClient,\n location: clientProps?.location ?? this.#location,\n action_type: MetricsActionType.SWAPBRIDGE_V1,\n };\n const inputPrimaryDenominationProperties = {\n input_primary_denomination: this.state.inputPrimaryDenomination,\n };\n const batchSellClientChainProperties = propertiesFromClient as Pick<\n RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellTokenPageViewed],\n 'chain_id_source' | 'chain_id_destination'\n >;\n const batchSellBaseProperties = {\n chain_id_source: batchSellClientChainProperties.chain_id_source,\n chain_id_destination: batchSellClientChainProperties.chain_id_destination,\n location: clientProps?.location ?? this.#location,\n };\n const quoteRequest = this.state.quoteRequest[quoteRequestIndex];\n switch (eventName) {\n case UnifiedSwapBridgeEventName.ButtonClicked:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.PageViewed:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...inputPrimaryDenominationProperties,\n ...baseProperties,\n };\n case BatchSellMetricsEventName.BatchSellTokenPageViewed:\n return batchSellBaseProperties;\n case BatchSellMetricsEventName.BatchSellTokenPageContinueClicked: {\n const propsFromClient =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellTokenPageContinueClicked];\n return {\n ...batchSellBaseProperties,\n source_token_count: propsFromClient.source_token_addresses.length,\n source_token_symbols: propsFromClient.source_token_symbols,\n source_token_addresses: propsFromClient.source_token_addresses,\n };\n }\n case BatchSellMetricsEventName.BatchSellQuotePageViewed:\n case BatchSellMetricsEventName.BatchSellQuotePageReviewClicked: {\n const propsFromClient =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellQuotePageViewed];\n return {\n ...batchSellBaseProperties,\n source_token_count: propsFromClient.source_token_addresses.length,\n source_token_symbols: propsFromClient.source_token_symbols,\n source_token_addresses: propsFromClient.source_token_addresses,\n destination_token_symbol: propsFromClient.destination_token_symbol,\n destination_token_address: propsFromClient.destination_token_address,\n usd_amount_source_tokens: propsFromClient.usd_amount_source_tokens,\n usd_amount_source_total: propsFromClient.usd_amount_source_total,\n source_token_slippages: propsFromClient.source_token_slippages,\n };\n }\n case BatchSellMetricsEventName.BatchSellReviewModalSubmitted: {\n const reviewModalProperties =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellReviewModalSubmitted];\n return {\n ...batchSellBaseProperties,\n source_token_count:\n reviewModalProperties.source_token_addresses.length,\n source_token_symbols: reviewModalProperties.source_token_symbols,\n source_token_addresses: reviewModalProperties.source_token_addresses,\n destination_token_symbol:\n reviewModalProperties.destination_token_symbol,\n destination_token_address:\n reviewModalProperties.destination_token_address,\n usd_amount_source_tokens:\n reviewModalProperties.usd_amount_source_tokens,\n usd_amount_source_total:\n reviewModalProperties.usd_amount_source_total,\n source_token_slippages: reviewModalProperties.source_token_slippages,\n usd_quoted_gas: reviewModalProperties.usd_quoted_gas,\n usd_quoted_return: reviewModalProperties.usd_quoted_return,\n };\n }\n case UnifiedSwapBridgeEventName.FiatCryptoToggleClicked:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n swap_type: getSwapTypeFromQuote(quoteRequest),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesValidationFailed:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n refresh_count: this.state.quotesRefreshCount,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesReceived:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n refresh_count: this.state.quotesRefreshCount,\n has_sufficient_funds: !quoteRequest.insufficientBal,\n ...inputPrimaryDenominationProperties,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesRequested:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n has_sufficient_funds: !quoteRequest.insufficientBal,\n ...inputPrimaryDenominationProperties,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesError:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n error_message: this.state.quoteFetchError,\n has_sufficient_funds: !quoteRequest.insufficientBal,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.AllQuotesOpened:\n case UnifiedSwapBridgeEventName.AllQuotesSorted:\n case UnifiedSwapBridgeEventName.QuoteSelected:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.Failed: {\n // Populate the properties that the error occurred before the tx was submitted\n return {\n ...baseProperties,\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n ...propertiesFromClient,\n };\n }\n case UnifiedSwapBridgeEventName.AssetDetailTooltipClicked:\n case UnifiedSwapBridgeEventName.AssetPickerOpened:\n return baseProperties;\n // Inject `token_security_type_destination` from controller state so the\n // field is always present on this event. `baseProperties` (which spreads\n // `propertiesFromClient`) wins if the client supplies a value explicitly.\n case UnifiedSwapBridgeEventName.InputSourceDestinationSwitched:\n return {\n token_security_type_destination:\n this.state.tokenSecurityTypeDestination,\n ...baseProperties,\n };\n // These events may be published after the bridge-controller state is reset\n // So the BridgeStatusController populates all the properties\n case UnifiedSwapBridgeEventName.Submitted:\n case UnifiedSwapBridgeEventName.Completed:\n return propertiesFromClient;\n case UnifiedSwapBridgeEventName.InputChanged:\n default:\n return baseProperties;\n }\n };\n\n readonly #trackInputChangedEvents = (\n paramsToUpdate: Partial<GenericQuoteRequest>,\n featureId: FeatureId,\n quoteRequestIndex: number = 0,\n ) => {\n Object.entries(paramsToUpdate).forEach(([key, value]) => {\n const inputKey = toInputChangedPropertyKey[key as keyof QuoteRequest];\n const inputValue =\n toInputChangedPropertyValue[key as keyof QuoteRequest]?.(\n paramsToUpdate,\n );\n if (\n inputKey &&\n inputValue !== undefined &&\n this.state.quoteRequest[quoteRequestIndex] &&\n value !==\n this.state.quoteRequest[quoteRequestIndex][\n key as keyof GenericQuoteRequest\n ]\n ) {\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.InputChanged,\n {\n input: inputKey,\n input_value: inputValue,\n location: this.#location,\n feature_id: featureId,\n },\n );\n }\n });\n };\n\n /**\n * This method tracks cross-chain swaps events\n *\n * @param eventName - The name of the event to track\n * @param propertiesFromClient - Properties that can't be calculated from the event name and need to be provided by the client\n * @param quoteRequestIndex - The index of the quote request to track the event for\n * @example\n * this.trackUnifiedSwapBridgeEvent(UnifiedSwapBridgeEventName.ActionOpened, {\n * location: MetaMetricsSwapsEventSource.MainView,\n * });\n */\n trackUnifiedSwapBridgeEvent = <\n EventName extends BridgeControllerMetricsEventName,\n >(\n eventName: EventName,\n propertiesFromClient: Pick<\n RequiredEventContextFromClient,\n EventName\n >[EventName],\n quoteRequestIndex: number = 0,\n ) => {\n try {\n const combinedPropertiesForEvent = this.#getEventProperties<EventName>(\n eventName,\n propertiesFromClient,\n quoteRequestIndex,\n );\n\n this.#trackMetaMetricsFn(\n eventName,\n combinedPropertiesForEvent as CrossChainSwapsEventProperties<EventName>,\n );\n } catch (error) {\n console.error(\n `Error tracking cross-chain swaps MetaMetrics event ${eventName}`,\n error,\n );\n }\n };\n\n /**\n *\n * @param walletAddress - The address of the account to get the allowance for\n * @param contractAddress - The address of the ERC20 token contract on mainnet\n * @param destinationChainId - The chain ID of the destination network\n * @returns The atomic allowance of the ERC20 token contract\n */\n readonly #getUSDTMainnetAllowance = async (\n walletAddress: string,\n contractAddress: string,\n destinationChainId: GenericQuoteRequest['destChainId'],\n ): Promise<string> => {\n const networkClient = this.#getNetworkClientByChainId(CHAIN_IDS.MAINNET);\n const provider = networkClient?.provider;\n if (!provider) {\n throw new Error('No provider found');\n }\n\n const ethersProvider = new Web3Provider(provider);\n const contract = new Contract(contractAddress, abiERC20, ethersProvider);\n const spenderAddress = isCrossChain(CHAIN_IDS.MAINNET, destinationChainId)\n ? METABRIDGE_ETHEREUM_ADDRESS\n : SWAPS_CONTRACT_ADDRESSES[CHAIN_IDS.MAINNET];\n const allowance: BigNumber = await contract.allowance(\n walletAddress,\n spenderAddress,\n );\n return allowance.toString();\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bridge-controller.cjs","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qEAAqE;AACrE,wDAAqD;AACrD,wDAAoD;AACpD,wDAAwD;AAIxD,mEAAuD;AACvD,qEAA+E;AAG/E,+BAAkC;AAElC,uFAA0E;AAE1E,sDAM+B;AAC/B,sDAAkD;AAClD,oDAAgE;AAChE,sDAAkD;AAClD,0CAA2C;AAW3C,kDAAyE;AACzE,oDAA0D;AAC1D,kDAM2B;AAC3B,oEAIoC;AACpC,gEAGkC;AAClC,gDAK0B;AAC1B,gEAQsC;AAKtC,gFAA8E;AAC9E,kEASuC;AAOvC,0DAA2D;AAC3D,gDAA+E;AAC/E,4DAAoD;AAEpD,qEAGuC;AAIvC,MAAM,QAAQ,GAAyC;IACrD,YAAY,EAAE;QACZ,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,MAAM,EAAE;QACN,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;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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, TraceRequest } 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';\nimport { v4 as uuid } from 'uuid';\n\nimport { toQuoteResponseV2 } from './coercers/quote-response-v1-to-v2.js';\nimport type { BridgeClientId } from './constants/bridge.js';\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.js';\nimport { CHAIN_IDS } from './constants/chains.js';\nimport { SWAPS_CONTRACT_ADDRESSES } from './constants/swaps.js';\nimport { TraceName } from './constants/traces.js';\nimport { RequestStatus } from './types.js';\nimport type {\n L1GasFees,\n GenericQuoteRequest,\n NonEvmFees,\n QuoteRequest,\n BridgeControllerState,\n BridgeControllerMessenger,\n FetchFunction,\n InputPrimaryDenomination,\n} from './types.js';\nimport { getAssetIdsForToken, toExchangeRates } from './utils/assets.js';\nimport { hasSufficientBalance } from './utils/balance.js';\nimport {\n getDefaultBridgeControllerState,\n isCrossChain,\n isEthUsdt,\n isNonEvmChainId,\n isSolanaChainId,\n} from './utils/bridge.js';\nimport {\n formatAddressToCaipReference,\n formatChainIdToCaip,\n formatChainIdToHex,\n} from './utils/caip-formatters.js';\nimport {\n getBridgeFeatureFlags,\n hasMinimumRequiredVersion,\n} from './utils/feature-flags.js';\nimport {\n fetchAssetPrices,\n fetchBridgeQuotes,\n fetchBridgeQuoteStream,\n fetchBatchSellTrades,\n} from './utils/fetch.js';\nimport {\n AbortReason,\n BatchSellMetricsEventName,\n FailurePhase,\n MetaMetricsSwapsEventSource,\n MetricsActionType,\n SwapBridgeErrorCode,\n UnifiedSwapBridgeEventName,\n} from './utils/metrics/constants.js';\nimport type {\n BridgeControllerMetricsEventName,\n BridgeControllerMetricsLocation,\n} from './utils/metrics/constants.js';\nimport { getQuoteFetchErrorCode } from './utils/metrics/failure-telemetry.js';\nimport {\n formatProviderLabel,\n getAccountHardwareType,\n getRequestParams,\n getSwapType,\n getSwapTypeFromQuote,\n isCustomSlippage,\n toInputChangedPropertyKey,\n toInputChangedPropertyValue,\n} from './utils/metrics/properties.js';\nimport type {\n QuoteFetchData,\n RequestMetadata,\n RequiredEventContextFromClient,\n} from './utils/metrics/types.js';\nimport type { CrossChainSwapsEventProperties } from './utils/metrics/types.js';\nimport { appendFeesToQuotes } from './utils/quote-fees.js';\nimport { getMinimumBalanceForRentExemptionInLamports } from './utils/snaps.js';\nimport { sortQuotes } from './utils/sort-quotes.js';\nimport type { FeatureId } from './validators/feature-flags.js';\nimport {\n isValidQuoteRequest,\n isValidBatchSellQuoteRequest,\n} from './validators/quote-request.js';\nimport type { QuoteResponseV1 } from './validators/quote-response-v1.js';\nimport type { QuoteResponse } from './validators/quote-response.js';\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\ntype QuoteTraceResult = 'success' | 'cancelled' | 'no_quotes' | 'error';\n\nconst QUOTE_ABORT_REASONS = new Set<string>(Object.values(AbortReason));\n\nconst isExpectedQuoteAbort = (\n error: unknown,\n signal?: AbortSignal,\n): boolean => {\n if (signal?.aborted) {\n return true;\n }\n\n if (QUOTE_ABORT_REASONS.has(String(error))) {\n return true;\n }\n\n const errorText =\n error instanceof Error ? `${error.name} ${error.message}` : String(error);\n\n return (\n errorText.includes('AbortError') ||\n errorText.includes('FetchRequestCanceledException')\n );\n};\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'updateBridgeQuoteRequestParams',\n 'fetchQuotes',\n 'updateBatchSellTrades',\n 'stopPollingForQuotes',\n 'setLocation',\n 'getLocation',\n 'setInputPrimaryDenomination',\n 'resetState',\n 'setChainIntervalLength',\n 'trackUnifiedSwapBridgeEvent',\n] as const;\n\nexport class BridgeController extends StaticIntervalPollingController<BridgePollingInput>()<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState,\n BridgeControllerMessenger\n> {\n #abortController: AbortController | undefined;\n\n #batchSellTradesAbortController: AbortController | undefined;\n\n #quotesFirstFetched: number | undefined;\n\n /**\n * Stores the location/entry point from which the user initiated the swap or bridge flow.\n * Set via setLocation() before navigating to the swap/bridge flow.\n * Used as default for all subsequent internal events.\n */\n #location: BridgeControllerMetricsLocation =\n MetaMetricsSwapsEventSource.Unknown;\n\n readonly #clientId: BridgeClientId;\n\n readonly #clientVersion: string;\n\n readonly #getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n\n readonly #fetchFn: FetchFunction;\n\n readonly #trackMetaMetricsFn: <\n EventName extends BridgeControllerMetricsEventName,\n >(\n eventName: EventName,\n properties: CrossChainSwapsEventProperties<EventName>,\n ) => void;\n\n readonly #trace: TraceCallback;\n\n readonly #config: {\n customBridgeApiBaseUrl?: string;\n };\n\n /**\n * Returns whether to use AssetsController for exchange rates.\n * Set via constructor option getUseAssetsControllerForRates; defaults to false.\n *\n * @returns True when exchange rates should be read from AssetsController:getExchangeRatesForBridge.\n */\n readonly #getUseAssetsControllerForRates: () => boolean;\n\n constructor({\n messenger,\n state,\n clientId,\n clientVersion,\n getLayer1GasFee,\n fetchFn,\n config,\n trackMetaMetricsFn,\n traceFn,\n getUseAssetsControllerForRates,\n }: {\n messenger: BridgeControllerMessenger;\n state?: Partial<BridgeControllerState>;\n clientId: BridgeClientId;\n clientVersion: string;\n getLayer1GasFee: typeof TransactionController.prototype.getLayer1GasFee;\n fetchFn: FetchFunction;\n config?: {\n customBridgeApiBaseUrl?: string;\n };\n trackMetaMetricsFn: <EventName extends BridgeControllerMetricsEventName>(\n eventName: EventName,\n properties: CrossChainSwapsEventProperties<EventName>,\n ) => void;\n traceFn?: TraceCallback;\n /**\n * When provided, called to determine whether to use AssetsController for exchange rates.\n * When true, rates are read from AssetsController:getExchangeRatesForBridge instead of\n * MultichainAssetsRatesController, TokenRatesController, and CurrencyRateController.\n */\n getUseAssetsControllerForRates?: () => boolean;\n }) {\n super({\n name: BRIDGE_CONTROLLER_NAME,\n metadata,\n messenger,\n state: {\n ...getDefaultBridgeControllerState(),\n ...state,\n },\n });\n\n this.setIntervalLength(REFRESH_INTERVAL_MS);\n\n this.#abortController = new AbortController();\n this.#getLayer1GasFee = getLayer1GasFee;\n this.#clientId = clientId;\n this.#clientVersion = clientVersion;\n this.#fetchFn = fetchFn;\n this.#trackMetaMetricsFn = trackMetaMetricsFn;\n this.#config = config ?? {};\n this.#trace = traceFn ?? (((_request, fn) => fn?.()) as TraceCallback);\n this.#getUseAssetsControllerForRates =\n getUseAssetsControllerForRates ?? (() => false);\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n _executePoll = async (pollingInput: BridgePollingInput) => {\n await this.#fetchBridgeQuotes(pollingInput);\n };\n\n /**\n * Updates the quote request at the specified index with the given parameters, then starts\n * polling for quotes.\n *\n * @param paramsToUpdate - The parameters to update in the quote request at the specified index\n * @param context - metrics context\n * @param quoteRequestIndex - The index of the quote request to update\n * @param quoteRequestCount - The number of quote requests in the UI\n */\n updateBridgeQuoteRequestParams = async (\n paramsToUpdate: Partial<GenericQuoteRequest> & {\n walletAddress: GenericQuoteRequest['walletAddress'];\n },\n context: BridgePollingInput['context'],\n quoteRequestIndex: number = 0,\n quoteRequestCount: number = 1,\n ) => {\n // Guard against updating a quote request that doesn't exist\n if (quoteRequestIndex >= quoteRequestCount) {\n return;\n }\n this.#trackInputChangedEvents(\n paramsToUpdate,\n context.feature_id,\n quoteRequestIndex,\n );\n this.resetState(AbortReason.QuoteRequestUpdated, quoteRequestIndex);\n this.update((state) => {\n // Update only the specified quote request and keep the rest of the quote requests unchanged\n state.quoteRequest = state.quoteRequest\n .slice(0, quoteRequestIndex)\n .concat({\n ...DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest[0],\n ...paramsToUpdate,\n })\n .concat(\n state.quoteRequest.slice(quoteRequestIndex + 1, quoteRequestCount),\n );\n state.tokenSecurityTypeDestination =\n context.token_security_type_destination ?? null;\n });\n\n // BatchSell and Unified swaps both use the same polling logic so both validations should pass\n if (\n isValidQuoteRequest(paramsToUpdate) &&\n isValidBatchSellQuoteRequest(this.state.quoteRequest)\n ) {\n this.#quotesFirstFetched = Date.now();\n // Update the insufficientBal and resetApproval params for the quote request\n const quoteWithInsufficientBalAndResetApproval =\n await this.#appendInsufficientBalAndResetApproval(paramsToUpdate);\n this.update((state) => {\n state.quoteRequest[quoteRequestIndex] =\n quoteWithInsufficientBalAndResetApproval;\n });\n\n // Set refresh rate based on the source chain before starting polling\n this.setChainIntervalLength();\n this.startPolling({\n quoteRequests: this.state.quoteRequest,\n context,\n });\n }\n };\n\n /**\n * Fetches quotes for specified request without updating the controller state\n * This method does not start polling for quotes and does not emit UnifiedSwapBridge events\n *\n * @param quoteRequest - The parameters for quote requests to fetch\n * @param featureId - The feature ID that maps to quoteParam overrides from LD\n * @param abortSignal - The abort signal to cancel all the requests\n * @returns A list of validated quotes\n */\n fetchQuotes = async (\n quoteRequest: GenericQuoteRequest,\n featureId: FeatureId,\n abortSignal: AbortSignal | null = null,\n ): Promise<(QuoteResponseV1 & L1GasFees & NonEvmFees)[]> => {\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messenger);\n const jwt = await this.#getJwt();\n // If featureId is specified, retrieve the quoteRequestOverrides for that featureId\n const quoteRequestOverrides = featureId\n ? bridgeFeatureFlags.quoteRequestOverrides?.[featureId]\n : undefined;\n const resetApproval = await this.#shouldResetApproval(quoteRequest);\n\n // If quoteRequestOverrides is specified, merge it with the quoteRequest\n const { quotes: baseQuotes, validationFailures } = await fetchBridgeQuotes(\n quoteRequestOverrides\n ? { ...quoteRequest, ...quoteRequestOverrides, resetApproval }\n : { ...quoteRequest, resetApproval },\n abortSignal,\n this.#clientId,\n jwt,\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n featureId,\n this.#clientVersion,\n );\n\n this.#trackQuoteValidationFailures(validationFailures, featureId);\n const srcChainIds = Array.from(\n new Set(baseQuotes.map((quote) => quote.quote.srcChainId)),\n ).filter(Boolean);\n\n const quotesWithFees =\n srcChainIds.length > 1 || srcChainIds.length === 0\n ? // Don't append fees if there are multiple srcChainIds\n baseQuotes\n : await appendFeesToQuotes(\n formatChainIdToCaip(srcChainIds[0]),\n baseQuotes,\n this.messenger,\n this.#getLayer1GasFee,\n this.#getMultichainSelectedAccount(quoteRequest.walletAddress),\n );\n\n return sortQuotes(quotesWithFees, featureId);\n };\n\n /**\n * Fetches gasless transaction data and fees for BatchSell quotes.\n * To use this in the clients, add a listener for the recommendedQuotes and call\n * this handler whenever they change.\n *\n * @param quotes - The quotes to fetch the gasless transaction data and fees for\n * @param stxEnabled - Flag to estimate gas cost more precisely for the batch sell feature.\n */\n updateBatchSellTrades = async (\n quotes: (QuoteResponse | null)[],\n stxEnabled: boolean,\n ): Promise<void> => {\n this.#batchSellTradesAbortController?.abort(\n AbortReason.GaslessTxBatchFetched,\n );\n this.#batchSellTradesAbortController = new AbortController();\n\n this.update((state) => {\n // Set loading status again if recommended quotes are re-ordered\n state.batchSellTradesLoadingStatus = RequestStatus.LOADING;\n });\n\n try {\n const batchSellTradesResponse = await fetchBatchSellTrades(\n quotes,\n stxEnabled,\n this.#batchSellTradesAbortController.signal,\n this.#clientId,\n await this.#getJwt(),\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n this.#clientVersion,\n );\n\n this.update((state) => {\n state.batchSellTrades = batchSellTradesResponse;\n state.batchSellTradesLoadingStatus = RequestStatus.FETCHED;\n });\n\n // TODO if fee.asset.assetId is not in exchange rates, fetch the exchange rate and update the state\n } catch (error) {\n // Ignore abort errors\n if (\n (error as Error).toString().includes('AbortError') ||\n (error as Error).toString().includes('FetchRequestCanceledException') ||\n [\n AbortReason.ResetState,\n AbortReason.NewQuoteRequest,\n AbortReason.QuoteRequestUpdated,\n AbortReason.TransactionSubmitted,\n AbortReason.GaslessTxBatchFetched,\n ].includes(error as AbortReason)\n ) {\n // Exit the function early to prevent other state updates\n return;\n }\n\n this.update((state) => {\n // Reset the batch sell trades if the fetch fails to avoid showing stale data\n state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n // Update loading status\n state.batchSellTradesLoadingStatus = RequestStatus.ERROR;\n });\n console.log(`Failed to fetch batch sell trades`, error);\n }\n };\n\n readonly #trackQuoteValidationFailures = (\n validationFailures: string[],\n featureId: FeatureId,\n ) => {\n if (validationFailures.length === 0) {\n return;\n }\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesValidationFailed,\n {\n feature_id: featureId,\n failures: validationFailures,\n location: this.#location,\n },\n );\n };\n\n /**\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 // Get unique assetIds for all quote requests\n const assetIds = new Set<CaipAssetType>(\n quoteRequests.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 );\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, 'usd']),\n clientId: this.#clientId,\n clientVersion: this.#clientVersion,\n fetchFn: this.#fetchFn,\n signal: this.#abortController?.signal,\n });\n const exchangeRates = toExchangeRates(currency, pricesByAssetId);\n this.update((state) => {\n state.assetExchangeRates = {\n ...state.assetExchangeRates,\n ...exchangeRates,\n };\n });\n };\n\n readonly #hasInsufficientBalance = async (\n quoteRequest: GenericQuoteRequest,\n ) => {\n try {\n const srcChainIdInHex = formatChainIdToHex(quoteRequest.srcChainId);\n const provider =\n this.#getNetworkClientByChainId(srcChainIdInHex)?.provider;\n const normalizedSrcTokenAddress = formatAddressToCaipReference(\n quoteRequest.srcTokenAddress,\n );\n\n return !(\n provider &&\n normalizedSrcTokenAddress &&\n quoteRequest.srcTokenAmount &&\n srcChainIdInHex &&\n (await hasSufficientBalance(\n provider,\n quoteRequest.walletAddress,\n normalizedSrcTokenAddress,\n quoteRequest.srcTokenAmount,\n srcChainIdInHex,\n ))\n );\n } catch (error) {\n console.warn('Failed to set insufficientBal', error);\n // Fall back to true so the backend returns quotes\n return true;\n }\n };\n\n readonly #appendInsufficientBalAndResetApproval = async (\n quoteRequest: GenericQuoteRequest,\n ) => {\n const isSrcChainNonEVM = isNonEvmChainId(quoteRequest.srcChainId);\n const providerConfig = isSrcChainNonEVM\n ? undefined\n : this.#getNetworkClientByChainId(\n formatChainIdToHex(quoteRequest.srcChainId),\n )?.configuration;\n\n let insufficientBal: boolean | undefined;\n let resetApproval: boolean = Boolean(quoteRequest.resetApproval);\n if (isSrcChainNonEVM) {\n // If the source chain is not an EVM network, use value from params\n insufficientBal = quoteRequest.insufficientBal;\n } else if (providerConfig?.rpcUrl?.includes('tenderly')) {\n // If the rpcUrl is a tenderly fork (e2e tests), set insufficientBal=true\n // The bridge-api filters out quotes if the balance on mainnet is insufficient so this override allows quotes to always be returned\n insufficientBal = true;\n } else {\n // Set loading status if RPC calls are made before the quotes are fetched\n this.update((state) => {\n state.quotesLoadingStatus = RequestStatus.LOADING;\n });\n resetApproval = await this.#shouldResetApproval(quoteRequest);\n // Otherwise query the src token balance from the RPC provider\n insufficientBal =\n quoteRequest.insufficientBal ??\n (await this.#hasInsufficientBalance(quoteRequest));\n }\n\n return {\n ...quoteRequest,\n insufficientBal,\n resetApproval,\n };\n };\n\n readonly #shouldResetApproval = async (quoteRequest: GenericQuoteRequest) => {\n if (isNonEvmChainId(quoteRequest.srcChainId)) {\n return false;\n }\n try {\n const normalizedSrcTokenAddress = formatAddressToCaipReference(\n quoteRequest.srcTokenAddress,\n );\n if (isEthUsdt(quoteRequest.srcChainId, normalizedSrcTokenAddress)) {\n const allowance = BigNumber.from(\n await this.#getUSDTMainnetAllowance(\n quoteRequest.walletAddress,\n normalizedSrcTokenAddress,\n quoteRequest.destChainId,\n ),\n );\n return allowance.lt(quoteRequest.srcTokenAmount) && allowance.gt(0);\n }\n return false;\n } catch (error) {\n console.warn('Failed to set resetApproval', error);\n // Fall back to true so the backend returns quotes\n return true;\n }\n };\n\n stopPollingForQuotes = (\n reason?: AbortReason,\n context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived],\n ) => {\n this.stopAllPolling();\n // If polling is stopped before quotes finish loading, track QuotesReceived\n if (this.state.quotesLoadingStatus === RequestStatus.LOADING && context) {\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.QuotesReceived,\n context,\n );\n }\n // Clears quotes list in state\n this.#abortController?.abort(reason);\n this.#batchSellTradesAbortController?.abort(reason);\n };\n\n /**\n * Sets the location/entry point for the current swap or bridge flow.\n * Call this when the user enters the flow so that all internally-fired\n * events (InputChanged, QuotesRequested, etc.) carry the correct location.\n *\n * @param location - The entry point from which the user initiated the flow\n */\n setLocation = (location: BridgeControllerMetricsLocation) => {\n this.#location = location;\n };\n\n /**\n * Returns the location/entry point for the current swap or bridge flow.\n *\n * @returns The entry point from which the user initiated the flow\n */\n getLocation = (): BridgeControllerMetricsLocation => {\n return this.#location;\n };\n\n setInputPrimaryDenomination = (\n inputPrimaryDenomination: InputPrimaryDenomination,\n ) => {\n this.update((state) => {\n state.inputPrimaryDenomination = inputPrimaryDenomination;\n });\n };\n\n resetState = (\n reason = AbortReason.ResetState,\n quoteRequestIndex: number | null = null,\n context?: RequiredEventContextFromClient[UnifiedSwapBridgeEventName.QuotesReceived],\n ) => {\n this.stopPollingForQuotes(reason, context);\n this.update((state) => {\n // Cannot do direct assignment to state, i.e. state = {... }, need to manually assign each field\n if (quoteRequestIndex === null) {\n // Clear all requests if index is null\n state.quoteRequest = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest;\n } else {\n // Otherwise only clear the specified request\n state.quoteRequest = state.quoteRequest\n .slice(0, quoteRequestIndex)\n .concat(DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest[0])\n .concat(state.quoteRequest.slice(quoteRequestIndex + 1));\n }\n state.quotesInitialLoadTime =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesInitialLoadTime;\n state.quotes = DEFAULT_BRIDGE_CONTROLLER_STATE.quotes;\n state.quotesLastFetched =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesLastFetched;\n state.quotesLoadingStatus =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesLoadingStatus;\n state.quoteFetchError = DEFAULT_BRIDGE_CONTROLLER_STATE.quoteFetchError;\n state.quotesRefreshCount =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quotesRefreshCount;\n state.assetExchangeRates =\n DEFAULT_BRIDGE_CONTROLLER_STATE.assetExchangeRates;\n state.minimumBalanceForRentExemptionInLamports =\n DEFAULT_BRIDGE_CONTROLLER_STATE.minimumBalanceForRentExemptionInLamports;\n state.tokenWarnings = DEFAULT_BRIDGE_CONTROLLER_STATE.tokenWarnings;\n state.tokenSecurityTypeDestination =\n DEFAULT_BRIDGE_CONTROLLER_STATE.tokenSecurityTypeDestination;\n state.quoteStreamComplete =\n DEFAULT_BRIDGE_CONTROLLER_STATE.quoteStreamComplete;\n state.batchSellTrades = DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTrades;\n state.batchSellTradesLoadingStatus =\n DEFAULT_BRIDGE_CONTROLLER_STATE.batchSellTradesLoadingStatus;\n });\n };\n\n /**\n * Sets the interval length based on the source chain\n */\n setChainIntervalLength = () => {\n const { state } = this;\n // Assume that BatchSell quote requests all have the same source chain\n // Use the first one to determine refresh rate\n const { srcChainId } = state.quoteRequest[0];\n const bridgeFeatureFlags = getBridgeFeatureFlags(this.messenger);\n\n const refreshRateOverride = srcChainId\n ? bridgeFeatureFlags.chains[formatChainIdToCaip(srcChainId)]?.refreshRate\n : undefined;\n const defaultRefreshRate = bridgeFeatureFlags.refreshRate;\n this.setIntervalLength(refreshRateOverride ?? defaultRefreshRate);\n };\n\n readonly #fetchBridgeQuotes = async ({\n quoteRequests,\n context,\n }: BridgePollingInput) => {\n this.#abortController?.abort(AbortReason.NewQuoteRequest);\n this.#batchSellTradesAbortController?.abort(AbortReason.NewQuoteRequest);\n\n this.#abortController = new AbortController();\n const quoteTraceStartTime = Date.now();\n const quoteTraceRequestId = uuid();\n const quoteAbortSignal = this.#abortController.signal;\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 const [firstQuoteRequest] = quoteRequests;\n let traceResult: QuoteTraceResult = 'error';\n let traceName = TraceName.BatchSellQuotesFetched;\n if (!isBatchSellRequest) {\n traceName = isCrossChain(\n firstQuoteRequest.srcChainId,\n firstQuoteRequest.destChainId,\n )\n ? TraceName.BridgeQuotesFetched\n : TraceName.SwapQuotesFetched;\n }\n const tracedProviders = new Set<string>();\n const traceWithoutImpact = async (request: TraceRequest): Promise<void> => {\n try {\n await this.#trace(request, () => undefined);\n } catch {\n // Telemetry failures must not affect quote fetching or state updates.\n }\n };\n const traceProviderFirstResult = (\n providerData: Parameters<typeof formatProviderLabel>[0],\n ) => {\n const provider = formatProviderLabel(providerData);\n if (isBatchSellRequest || tracedProviders.has(provider)) {\n return;\n }\n tracedProviders.add(provider);\n // Provider telemetry must not delay quote processing.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n traceWithoutImpact({\n name: TraceName.QuoteProviderFirstResult,\n startTime: quoteTraceStartTime,\n data: {\n provider,\n feature_id: context.feature_id,\n request_id: quoteTraceRequestId,\n swap_type: getSwapType(\n firstQuoteRequest.srcChainId,\n firstQuoteRequest.destChainId,\n ),\n srcChainId: formatChainIdToCaip(firstQuoteRequest.srcChainId),\n destChainId: formatChainIdToCaip(firstQuoteRequest.destChainId),\n result: 'success',\n },\n });\n };\n\n try {\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 const quoteCount = await this.#handleQuoteStreaming({\n quoteRequests,\n featureId: context.feature_id,\n jwt,\n selectedAccount,\n signal: quoteAbortSignal,\n traceProviderFirstResult,\n });\n if (quoteAbortSignal.aborted) {\n traceResult = 'cancelled';\n return;\n }\n traceResult = quoteCount > 0 ? 'success' : 'no_quotes';\n } else {\n // Otherwise use regular fetch\n const quotes = await this.fetchQuotes(\n firstQuoteRequest,\n context.feature_id,\n quoteAbortSignal,\n );\n for (const quote of quotes) {\n traceProviderFirstResult(quote.quote);\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 = Date.now() - this.#quotesFirstFetched;\n }\n state.quotes = quotes.map(toQuoteResponseV2);\n state.quotesLoadingStatus = RequestStatus.FETCHED;\n });\n traceResult = quotes.length > 0 ? 'success' : 'no_quotes';\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 (isExpectedQuoteAbort(error, quoteAbortSignal)) {\n traceResult = 'cancelled';\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(UnifiedSwapBridgeEventName.QuotesError, {\n ...context,\n failure_phase: FailurePhase.Quote,\n error_code: getQuoteFetchErrorCode(error),\n });\n console.log(\n `Failed to ${shouldStream ? 'stream' : 'fetch'} bridge quotes`,\n error,\n );\n } finally {\n await traceWithoutImpact({\n name: traceName,\n startTime: quoteTraceStartTime,\n data: {\n srcChainId: formatChainIdToCaip(firstQuoteRequest.srcChainId),\n destChainId: formatChainIdToCaip(firstQuoteRequest.destChainId),\n ...(!isBatchSellRequest && {\n request_id: quoteTraceRequestId,\n feature_id: context.feature_id,\n result: traceResult,\n }),\n },\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,\n featureId,\n jwt,\n selectedAccount,\n signal,\n traceProviderFirstResult,\n }: {\n quoteRequests: GenericQuoteRequest[];\n featureId: FeatureId;\n jwt?: string;\n selectedAccount?: InternalAccount;\n signal?: AbortSignal;\n traceProviderFirstResult: (\n providerData: Parameters<typeof formatProviderLabel>[0],\n ) => void;\n }): Promise<number> => {\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 signal,\n featureId,\n this.#clientId,\n jwt,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n {\n onQuoteValidationFailure: (validationFailures) =>\n this.#trackQuoteValidationFailures(validationFailures, featureId),\n onValidQuoteReceived: async (quote: QuoteResponse) => {\n const feeAppendPromise = (async () => {\n const quotesWithFees = await appendFeesToQuotes(\n quote.chainId,\n [quote],\n this.messenger,\n this.#getLayer1GasFee,\n selectedAccount,\n );\n if (quotesWithFees.length > 0) {\n validQuotesCounter += 1;\n traceProviderFirstResult(quote.quote);\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 return validQuotesCounter;\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 ?? 0,\n swap_type: getSwapTypeFromQuote(quoteRequest),\n custom_slippage: isCustomSlippage(quoteRequest.slippage),\n account_hardware_type: accountHardwareType,\n is_hardware_wallet: accountHardwareType !== null,\n };\n };\n\n readonly #getQuoteFetchData = (): Omit<\n QuoteFetchData,\n 'best_quote_provider' | 'price_impact' | 'can_submit'\n > => {\n return {\n quotes_count: this.state.quotes.length,\n quotes_list: this.state.quotes.map(({ quote }) =>\n formatProviderLabel(quote),\n ),\n initial_load_time_all_quotes: this.state.quotesInitialLoadTime ?? 0,\n has_gas_included_quote: this.state.quotes.some(\n ({ quote }) => quote.gasIncluded,\n ),\n };\n };\n\n readonly #getEventProperties = <\n EventName extends BridgeControllerMetricsEventName,\n >(\n eventName: EventName,\n propertiesFromClient: Pick<\n RequiredEventContextFromClient,\n EventName\n >[EventName],\n quoteRequestIndex: number = 0,\n ) => {\n const clientProps = propertiesFromClient as Record<string, unknown>;\n const baseProperties = {\n ...propertiesFromClient,\n location: clientProps?.location ?? this.#location,\n action_type: MetricsActionType.SWAPBRIDGE_V1,\n };\n const inputPrimaryDenominationProperties = {\n input_primary_denomination: this.state.inputPrimaryDenomination,\n };\n const batchSellClientChainProperties = propertiesFromClient as Pick<\n RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellTokenPageViewed],\n 'chain_id_source' | 'chain_id_destination'\n >;\n const batchSellBaseProperties = {\n chain_id_source: batchSellClientChainProperties.chain_id_source,\n chain_id_destination: batchSellClientChainProperties.chain_id_destination,\n location: clientProps?.location ?? this.#location,\n };\n const quoteRequest = this.state.quoteRequest[quoteRequestIndex];\n switch (eventName) {\n case UnifiedSwapBridgeEventName.ButtonClicked:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.PageViewed:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...inputPrimaryDenominationProperties,\n ...baseProperties,\n };\n case BatchSellMetricsEventName.BatchSellTokenPageViewed:\n return batchSellBaseProperties;\n case BatchSellMetricsEventName.BatchSellTokenPageContinueClicked: {\n const propsFromClient =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellTokenPageContinueClicked];\n return {\n ...batchSellBaseProperties,\n source_token_count: propsFromClient.source_token_addresses.length,\n source_token_symbols: propsFromClient.source_token_symbols,\n source_token_addresses: propsFromClient.source_token_addresses,\n };\n }\n case BatchSellMetricsEventName.BatchSellQuotePageViewed:\n case BatchSellMetricsEventName.BatchSellQuotePageReviewClicked: {\n const propsFromClient =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellQuotePageViewed];\n return {\n ...batchSellBaseProperties,\n source_token_count: propsFromClient.source_token_addresses.length,\n source_token_symbols: propsFromClient.source_token_symbols,\n source_token_addresses: propsFromClient.source_token_addresses,\n destination_token_symbol: propsFromClient.destination_token_symbol,\n destination_token_address: propsFromClient.destination_token_address,\n usd_amount_source_tokens: propsFromClient.usd_amount_source_tokens,\n usd_amount_source_total: propsFromClient.usd_amount_source_total,\n source_token_slippages: propsFromClient.source_token_slippages,\n };\n }\n case BatchSellMetricsEventName.BatchSellReviewModalSubmitted: {\n const reviewModalProperties =\n propertiesFromClient as RequiredEventContextFromClient[BatchSellMetricsEventName.BatchSellReviewModalSubmitted];\n return {\n ...batchSellBaseProperties,\n source_token_count:\n reviewModalProperties.source_token_addresses.length,\n source_token_symbols: reviewModalProperties.source_token_symbols,\n source_token_addresses: reviewModalProperties.source_token_addresses,\n destination_token_symbol:\n reviewModalProperties.destination_token_symbol,\n destination_token_address:\n reviewModalProperties.destination_token_address,\n usd_amount_source_tokens:\n reviewModalProperties.usd_amount_source_tokens,\n usd_amount_source_total:\n reviewModalProperties.usd_amount_source_total,\n source_token_slippages: reviewModalProperties.source_token_slippages,\n usd_quoted_gas: reviewModalProperties.usd_quoted_gas,\n usd_quoted_return: reviewModalProperties.usd_quoted_return,\n };\n }\n case UnifiedSwapBridgeEventName.FiatCryptoToggleClicked:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n swap_type: getSwapTypeFromQuote(quoteRequest),\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesValidationFailed:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n refresh_count: this.state.quotesRefreshCount,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.QuotesReceived:\n return {\n ...getRequestParams(\n quoteRequest,\n this.state.tokenSecurityTypeDestination,\n ),\n ...this.#getRequestMetadata(),\n ...this.#getQuoteFetchData(),\n refresh_count: this.state.quotesRefreshCount,\n has_sufficient_funds: !quoteRequest.insufficientBal,\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 failure_phase: FailurePhase.Quote,\n error_code: SwapBridgeErrorCode.QuoteFetchFailed,\n ...baseProperties,\n };\n case UnifiedSwapBridgeEventName.Failed: {\n const failedClientProperties =\n propertiesFromClient as RequiredEventContextFromClient[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 failure_phase:\n failedClientProperties.failure_phase ?? FailurePhase.Unknown,\n error_code:\n failedClientProperties.error_code ?? SwapBridgeErrorCode.Unknown,\n source_hash_present:\n failedClientProperties.source_hash_present ?? false,\n destination_hash_present:\n failedClientProperties.destination_hash_present ?? false,\n };\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.AssetDetailTooltipClicked:\n case UnifiedSwapBridgeEventName.AssetPickerOpened:\n return baseProperties;\n // Inject `token_security_type_destination` from controller state so the\n // field is always present on this event. `baseProperties` (which spreads\n // `propertiesFromClient`) wins if the client supplies a value explicitly.\n case UnifiedSwapBridgeEventName.InputSourceDestinationSwitched:\n return {\n token_security_type_destination:\n this.state.tokenSecurityTypeDestination,\n ...baseProperties,\n };\n // These events may be published after the bridge-controller state is reset\n // So the BridgeStatusController populates all the properties\n case UnifiedSwapBridgeEventName.Submitted:\n case UnifiedSwapBridgeEventName.Completed:\n return propertiesFromClient;\n case UnifiedSwapBridgeEventName.InputChanged:\n default:\n return baseProperties;\n }\n };\n\n readonly #trackInputChangedEvents = (\n paramsToUpdate: Partial<GenericQuoteRequest>,\n featureId: FeatureId,\n quoteRequestIndex: number = 0,\n ) => {\n Object.entries(paramsToUpdate).forEach(([key, value]) => {\n const inputKey = toInputChangedPropertyKey[key as keyof QuoteRequest];\n const inputValue =\n toInputChangedPropertyValue[key as keyof QuoteRequest]?.(\n paramsToUpdate,\n );\n if (\n inputKey &&\n inputValue !== undefined &&\n this.state.quoteRequest[quoteRequestIndex] &&\n value !==\n this.state.quoteRequest[quoteRequestIndex][\n key as keyof GenericQuoteRequest\n ]\n ) {\n this.trackUnifiedSwapBridgeEvent(\n UnifiedSwapBridgeEventName.InputChanged,\n {\n input: inputKey,\n input_value: inputValue,\n location: this.#location,\n feature_id: featureId,\n },\n );\n }\n });\n };\n\n /**\n * This method tracks cross-chain swaps events\n *\n * @param eventName - The name of the event to track\n * @param propertiesFromClient - Properties that can't be calculated from the event name and need to be provided by the client\n * @param quoteRequestIndex - The index of the quote request to track the event for\n * @example\n * this.trackUnifiedSwapBridgeEvent(UnifiedSwapBridgeEventName.ActionOpened, {\n * location: MetaMetricsSwapsEventSource.MainView,\n * });\n */\n trackUnifiedSwapBridgeEvent = <\n EventName extends BridgeControllerMetricsEventName,\n >(\n eventName: EventName,\n propertiesFromClient: Pick<\n RequiredEventContextFromClient,\n EventName\n >[EventName],\n quoteRequestIndex: number = 0,\n ) => {\n try {\n const combinedPropertiesForEvent = this.#getEventProperties<EventName>(\n eventName,\n propertiesFromClient,\n quoteRequestIndex,\n );\n\n this.#trackMetaMetricsFn(\n eventName,\n combinedPropertiesForEvent as CrossChainSwapsEventProperties<EventName>,\n );\n } catch (error) {\n console.error(\n `Error tracking cross-chain swaps MetaMetrics event ${eventName}`,\n error,\n );\n }\n };\n\n /**\n *\n * @param walletAddress - The address of the account to get the allowance for\n * @param contractAddress - The address of the ERC20 token contract on mainnet\n * @param destinationChainId - The chain ID of the destination network\n * @returns The atomic allowance of the ERC20 token contract\n */\n readonly #getUSDTMainnetAllowance = async (\n walletAddress: string,\n contractAddress: string,\n destinationChainId: GenericQuoteRequest['destChainId'],\n ): Promise<string> => {\n const networkClient = this.#getNetworkClientByChainId(CHAIN_IDS.MAINNET);\n const provider = networkClient?.provider;\n if (!provider) {\n throw new Error('No provider found');\n }\n\n const ethersProvider = new Web3Provider(provider);\n const contract = new Contract(contractAddress, abiERC20, ethersProvider);\n const spenderAddress = isCrossChain(CHAIN_IDS.MAINNET, destinationChainId)\n ? METABRIDGE_ETHEREUM_ADDRESS\n : SWAPS_CONTRACT_ADDRESSES[CHAIN_IDS.MAINNET];\n const allowance: BigNumber = await contract.allowance(\n walletAddress,\n spenderAddress,\n );\n return allowance.toString();\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-controller.d.cts","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAgB,mCAAmC;AAI9E,OAAO,KAAK,EAAE,qBAAqB,EAAE,yCAAyC;AAK9E,OAAO,KAAK,EAAE,cAAc,EAAE,+BAA8B;AAC5D,OAAO,EACL,sBAAsB,EAKvB,+BAA8B;AAK/B,OAAO,KAAK,EACV,SAAS,EACT,mBAAmB,EACnB,UAAU,EAEV,qBAAqB,EACrB,yBAAyB,EACzB,aAAa,EACb,wBAAwB,EACzB,oBAAmB;AAyBpB,OAAO,EACL,WAAW,
|
|
1
|
+
{"version":3,"file":"bridge-controller.d.cts","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAgB,mCAAmC;AAI9E,OAAO,KAAK,EAAE,qBAAqB,EAAE,yCAAyC;AAK9E,OAAO,KAAK,EAAE,cAAc,EAAE,+B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{"version":3,"file":"bridge-controller.d.mts","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAgB,mCAAmC;AAI9E,OAAO,KAAK,EAAE,qBAAqB,EAAE,yCAAyC;AAK9E,OAAO,KAAK,EAAE,cAAc,EAAE,+BAA8B;AAC5D,OAAO,EACL,sBAAsB,EAKvB,+BAA8B;AAK/B,OAAO,KAAK,EACV,SAAS,EACT,mBAAmB,EACnB,UAAU,EAEV,qBAAqB,EACrB,yBAAyB,EACzB,aAAa,EACb,wBAAwB,EACzB,oBAAmB;AAyBpB,OAAO,EACL,WAAW,
|
|
1
|
+
{"version":3,"file":"bridge-controller.d.mts","sourceRoot":"","sources":["../src/bridge-controller.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAgB,mCAAmC;AAI9E,OAAO,KAAK,EAAE,qBAAqB,EAAE,yCAAyC;AAK9E,OAAO,KAAK,EAAE,cAAc,EAAE,+BAA8B;AAC5D,OAAO,EACL,sBAAsB,EAKvB,+BAA8B;AAK/B,OAAO,KAAK,EACV,SAAS,EACT,mBAAmB,EACnB,UAAU,EAEV,qBAAqB,EACrB,yBAAyB,EACzB,aAAa,EACb,wBAAwB,EACzB,oBAAmB;AAyBpB,OAAO,EACL,WAAW,EAMX,0BAA0B,EAC3B,sCAAqC;AACtC,OAAO,KAAK,EACV,gCAAgC,EAChC,+BAA+B,EAChC,sCAAqC;AAYtC,OAAO,KAAK,EAGV,8BAA8B,EAC/B,kCAAiC;AAClC,OAAO,KAAK,EAAE,8BAA8B,EAAE,kCAAiC;AAI/E,OAAO,KAAK,EAAE,SAAS,EAAE,uCAAsC;AAK/D,OAAO,KAAK,EAAE,eAAe,EAAE,2CAA0C;AACzE,OAAO,KAAK,EAAE,aAAa,EAAE,wCAAuC;AA+FpE;;;;;;GAMG;AACH,KAAK,kBAAkB,GAAG;IACxB,aAAa,EAAE,mBAAmB,EAAE,CAAC;IACrC,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9B,QAAQ,CAAC,eAAe,GAAG,SAAS,GAAG,UAAU,CAAC,EAAE,CAAC,CAyCtD;IAEF;;;;;;;OAOG;IACH,qBAAqB,WACX,CAAC,aAAa,GAAG,IAAI,CAAC,EAAE,cACpB,OAAO,KAClB,QAAQ,IAAI,CAAC,CAsDd;IAqKF,oBAAoB,YACT,WAAW,YACV,8BAA8B,CAAC,2BAA2B,cAAc,CAAC,UAanF;IAEF;;;;;;OAMG;IACH,WAAW,aAAc,+BAA+B,UAEtD;IAEF;;;;OAIG;IACH,WAAW,QAAO,+BAA+B,CAE/C;IAEF,2BAA2B,6BACC,wBAAwB,UAKlD;IAEF,UAAU,6CAEW,MAAM,GAAG,IAAI,YACtB,8BAA8B,CAAC,2BAA2B,cAAc,CAAC,UAsCnF;IAEF;;OAEG;IACH,sBAAsB,aAYpB;IAiqBF;;;;;;;;;;OAUG;IACH,2BAA2B,mLAQN,MAAM,UAmBzB;CA+BH"}
|
|
@@ -29,7 +29,8 @@ import { getDefaultBridgeControllerState, isCrossChain, isEthUsdt, isNonEvmChain
|
|
|
29
29
|
import { formatAddressToCaipReference, formatChainIdToCaip, formatChainIdToHex } from "./utils/caip-formatters.mjs";
|
|
30
30
|
import { getBridgeFeatureFlags, hasMinimumRequiredVersion } from "./utils/feature-flags.mjs";
|
|
31
31
|
import { fetchAssetPrices, fetchBridgeQuotes, fetchBridgeQuoteStream, fetchBatchSellTrades } from "./utils/fetch.mjs";
|
|
32
|
-
import { AbortReason, BatchSellMetricsEventName, MetaMetricsSwapsEventSource, MetricsActionType, UnifiedSwapBridgeEventName } from "./utils/metrics/constants.mjs";
|
|
32
|
+
import { AbortReason, BatchSellMetricsEventName, FailurePhase, MetaMetricsSwapsEventSource, MetricsActionType, SwapBridgeErrorCode, UnifiedSwapBridgeEventName } from "./utils/metrics/constants.mjs";
|
|
33
|
+
import { getQuoteFetchErrorCode } from "./utils/metrics/failure-telemetry.mjs";
|
|
33
34
|
import { formatProviderLabel, getAccountHardwareType, getRequestParams, getSwapType, getSwapTypeFromQuote, isCustomSlippage, toInputChangedPropertyKey, toInputChangedPropertyValue } from "./utils/metrics/properties.mjs";
|
|
34
35
|
import { appendFeesToQuotes } from "./utils/quote-fees.mjs";
|
|
35
36
|
import { getMinimumBalanceForRentExemptionInLamports } from "./utils/snaps.mjs";
|
|
@@ -645,7 +646,11 @@ export class BridgeController extends StaticIntervalPollingController() {
|
|
|
645
646
|
state.quotesLoadingStatus = RequestStatus.ERROR;
|
|
646
647
|
});
|
|
647
648
|
// Track event and log error
|
|
648
|
-
this.trackUnifiedSwapBridgeEvent(UnifiedSwapBridgeEventName.QuotesError,
|
|
649
|
+
this.trackUnifiedSwapBridgeEvent(UnifiedSwapBridgeEventName.QuotesError, {
|
|
650
|
+
...context,
|
|
651
|
+
failure_phase: FailurePhase.Quote,
|
|
652
|
+
error_code: getQuoteFetchErrorCode(error),
|
|
653
|
+
});
|
|
649
654
|
console.log(`Failed to ${shouldStream ? 'stream' : 'fetch'} bridge quotes`, error);
|
|
650
655
|
}
|
|
651
656
|
finally {
|
|
@@ -907,18 +912,12 @@ export class BridgeController extends StaticIntervalPollingController() {
|
|
|
907
912
|
...__classPrivateFieldGet(this, _BridgeController_getRequestMetadata, "f").call(this),
|
|
908
913
|
error_message: this.state.quoteFetchError,
|
|
909
914
|
has_sufficient_funds: !quoteRequest.insufficientBal,
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
case UnifiedSwapBridgeEventName.AllQuotesOpened:
|
|
913
|
-
case UnifiedSwapBridgeEventName.AllQuotesSorted:
|
|
914
|
-
case UnifiedSwapBridgeEventName.QuoteSelected:
|
|
915
|
-
return {
|
|
916
|
-
...getRequestParams(quoteRequest, this.state.tokenSecurityTypeDestination),
|
|
917
|
-
...__classPrivateFieldGet(this, _BridgeController_getRequestMetadata, "f").call(this),
|
|
918
|
-
...__classPrivateFieldGet(this, _BridgeController_getQuoteFetchData, "f").call(this),
|
|
915
|
+
failure_phase: FailurePhase.Quote,
|
|
916
|
+
error_code: SwapBridgeErrorCode.QuoteFetchFailed,
|
|
919
917
|
...baseProperties,
|
|
920
918
|
};
|
|
921
919
|
case UnifiedSwapBridgeEventName.Failed: {
|
|
920
|
+
const failedClientProperties = propertiesFromClient;
|
|
922
921
|
// Populate the properties that the error occurred before the tx was submitted
|
|
923
922
|
return {
|
|
924
923
|
...baseProperties,
|
|
@@ -926,8 +925,21 @@ export class BridgeController extends StaticIntervalPollingController() {
|
|
|
926
925
|
...__classPrivateFieldGet(this, _BridgeController_getRequestMetadata, "f").call(this),
|
|
927
926
|
...__classPrivateFieldGet(this, _BridgeController_getQuoteFetchData, "f").call(this),
|
|
928
927
|
...propertiesFromClient,
|
|
928
|
+
failure_phase: failedClientProperties.failure_phase ?? FailurePhase.Unknown,
|
|
929
|
+
error_code: failedClientProperties.error_code ?? SwapBridgeErrorCode.Unknown,
|
|
930
|
+
source_hash_present: failedClientProperties.source_hash_present ?? false,
|
|
931
|
+
destination_hash_present: failedClientProperties.destination_hash_present ?? false,
|
|
929
932
|
};
|
|
930
933
|
}
|
|
934
|
+
case UnifiedSwapBridgeEventName.AllQuotesOpened:
|
|
935
|
+
case UnifiedSwapBridgeEventName.AllQuotesSorted:
|
|
936
|
+
case UnifiedSwapBridgeEventName.QuoteSelected:
|
|
937
|
+
return {
|
|
938
|
+
...getRequestParams(quoteRequest, this.state.tokenSecurityTypeDestination),
|
|
939
|
+
...__classPrivateFieldGet(this, _BridgeController_getRequestMetadata, "f").call(this),
|
|
940
|
+
...__classPrivateFieldGet(this, _BridgeController_getQuoteFetchData, "f").call(this),
|
|
941
|
+
...baseProperties,
|
|
942
|
+
};
|
|
931
943
|
case UnifiedSwapBridgeEventName.AssetDetailTooltipClicked:
|
|
932
944
|
case UnifiedSwapBridgeEventName.AssetPickerOpened:
|
|
933
945
|
return baseProperties;
|