@metamask/bridge-controller 74.0.0 → 75.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -1
- package/dist/bridge-controller.cjs +17 -19
- package/dist/bridge-controller.cjs.map +1 -1
- package/dist/bridge-controller.d.cts +5 -13
- package/dist/bridge-controller.d.cts.map +1 -1
- package/dist/bridge-controller.d.mts +5 -13
- package/dist/bridge-controller.d.mts.map +1 -1
- package/dist/bridge-controller.mjs +18 -20
- package/dist/bridge-controller.mjs.map +1 -1
- package/dist/constants/bridge.cjs +2 -0
- package/dist/constants/bridge.cjs.map +1 -1
- package/dist/constants/bridge.d.cts +4 -1
- package/dist/constants/bridge.d.cts.map +1 -1
- package/dist/constants/bridge.d.mts +4 -1
- package/dist/constants/bridge.d.mts.map +1 -1
- package/dist/constants/bridge.mjs +2 -0
- package/dist/constants/bridge.mjs.map +1 -1
- package/dist/constants/chains.cjs +4 -1
- package/dist/constants/chains.cjs.map +1 -1
- package/dist/constants/chains.d.cts +3 -0
- package/dist/constants/chains.d.cts.map +1 -1
- package/dist/constants/chains.d.mts +3 -0
- package/dist/constants/chains.d.mts.map +1 -1
- package/dist/constants/chains.mjs +3 -0
- package/dist/constants/chains.mjs.map +1 -1
- package/dist/constants/tokens.cjs +12 -0
- package/dist/constants/tokens.cjs.map +1 -1
- package/dist/constants/tokens.d.cts +7 -0
- package/dist/constants/tokens.d.cts.map +1 -1
- package/dist/constants/tokens.d.mts +7 -0
- package/dist/constants/tokens.d.mts.map +1 -1
- package/dist/constants/tokens.mjs +12 -0
- package/dist/constants/tokens.mjs.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/selectors.d.cts +143 -143
- package/dist/selectors.d.mts +143 -143
- package/dist/types.cjs +12 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +12 -2
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +12 -2
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs +11 -0
- package/dist/types.mjs.map +1 -1
- package/dist/utils/feature-flags.d.cts +1 -1
- package/dist/utils/feature-flags.d.mts +1 -1
- package/dist/utils/fetch.cjs +3 -1
- package/dist/utils/fetch.cjs.map +1 -1
- package/dist/utils/fetch.d.cts +3 -3
- package/dist/utils/fetch.d.cts.map +1 -1
- package/dist/utils/fetch.d.mts +3 -3
- package/dist/utils/fetch.d.mts.map +1 -1
- package/dist/utils/fetch.mjs +3 -1
- package/dist/utils/fetch.mjs.map +1 -1
- package/dist/utils/metrics/properties.cjs +2 -0
- package/dist/utils/metrics/properties.cjs.map +1 -1
- package/dist/utils/metrics/properties.d.cts +2 -0
- package/dist/utils/metrics/properties.d.cts.map +1 -1
- package/dist/utils/metrics/properties.d.mts +2 -0
- package/dist/utils/metrics/properties.d.mts.map +1 -1
- package/dist/utils/metrics/properties.mjs +2 -0
- package/dist/utils/metrics/properties.mjs.map +1 -1
- package/dist/utils/metrics/types.cjs.map +1 -1
- package/dist/utils/metrics/types.d.cts +30 -17
- package/dist/utils/metrics/types.d.cts.map +1 -1
- package/dist/utils/metrics/types.d.mts +30 -17
- package/dist/utils/metrics/types.d.mts.map +1 -1
- package/dist/utils/metrics/types.mjs.map +1 -1
- package/dist/utils/quote.cjs +2 -2
- package/dist/utils/quote.cjs.map +1 -1
- package/dist/utils/quote.d.cts +1 -1
- package/dist/utils/quote.d.cts.map +1 -1
- package/dist/utils/quote.d.mts +1 -1
- package/dist/utils/quote.d.mts.map +1 -1
- package/dist/utils/quote.mjs +1 -1
- package/dist/utils/quote.mjs.map +1 -1
- package/dist/utils/validators.cjs +2 -9
- package/dist/utils/validators.cjs.map +1 -1
- package/dist/utils/validators.d.cts +3 -8
- package/dist/utils/validators.d.cts.map +1 -1
- package/dist/utils/validators.d.mts +3 -8
- package/dist/utils/validators.d.mts.map +1 -1
- package/dist/utils/validators.mjs +1 -8
- package/dist/utils/validators.mjs.map +1 -1
- package/package.json +6 -6
package/dist/types.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.RequestStatus = exports.ChainId = exports.StatusTypes = exports.SortOrder = exports.AssetType = void 0;
|
|
3
|
+
exports.RequestStatus = exports.ChainId = exports.FeatureId = exports.StatusTypes = exports.SortOrder = exports.AssetType = void 0;
|
|
4
4
|
/**
|
|
5
5
|
* The types of assets that a user can send
|
|
6
6
|
*/
|
|
@@ -34,6 +34,16 @@ var StatusTypes;
|
|
|
34
34
|
StatusTypes["PENDING"] = "PENDING";
|
|
35
35
|
StatusTypes["COMPLETE"] = "COMPLETE";
|
|
36
36
|
})(StatusTypes || (exports.StatusTypes = StatusTypes = {}));
|
|
37
|
+
var FeatureId;
|
|
38
|
+
(function (FeatureId) {
|
|
39
|
+
FeatureId["UNKNOWN"] = "unknown";
|
|
40
|
+
FeatureId["PERPS"] = "perps";
|
|
41
|
+
FeatureId["QUICK_BUY_FOLLOW_TRADING"] = "quick_buy_follow_trading";
|
|
42
|
+
FeatureId["QUICK_BUY_TOKEN_DETAILS"] = "quick_buy_token_details";
|
|
43
|
+
FeatureId["DAPP_SWAP"] = "dapp_swap";
|
|
44
|
+
FeatureId["BATCH_SELL"] = "batch_sell";
|
|
45
|
+
FeatureId["UNIFIED_SWAP_BRIDGE"] = "unified_swap_bridge";
|
|
46
|
+
})(FeatureId || (exports.FeatureId = FeatureId = {}));
|
|
37
47
|
var ChainId;
|
|
38
48
|
(function (ChainId) {
|
|
39
49
|
ChainId[ChainId["ETH"] = 1] = "ETH";
|
|
@@ -52,6 +62,7 @@ var ChainId;
|
|
|
52
62
|
ChainId[ChainId["MONAD"] = 143] = "MONAD";
|
|
53
63
|
ChainId[ChainId["HYPEREVM"] = 999] = "HYPEREVM";
|
|
54
64
|
ChainId[ChainId["MEGAETH"] = 4326] = "MEGAETH";
|
|
65
|
+
ChainId[ChainId["ARC"] = 5042] = "ARC";
|
|
55
66
|
})(ChainId || (exports.ChainId = ChainId = {}));
|
|
56
67
|
var RequestStatus;
|
|
57
68
|
(function (RequestStatus) {
|
package/dist/types.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AA6DA;;GAEG;AACH,IAAY,SAYX;AAZD,WAAY,SAAS;IACnB,4DAA4D;IAC5D,8BAAiB,CAAA;IACjB,qBAAqB;IACrB,4BAAe,CAAA;IACf,kCAAkC;IAClC,wBAAW,CAAA;IACX;;;OAGG;IACH,gCAAmB,CAAA;AACrB,CAAC,EAZW,SAAS,yBAAT,SAAS,QAYpB;AAkGD;;GAEG;AACH,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,wCAA2B,CAAA;IAC3B,wCAA2B,CAAA;AAC7B,CAAC,EAHW,SAAS,yBAAT,SAAS,QAGpB;AAyED,IAAY,WAMX;AAND,WAAY,WAAW;IACrB,sCAAuB,CAAA;IACvB,kCAAmB,CAAA;IACnB,gCAAiB,CAAA;IACjB,kCAAmB,CAAA;IACnB,oCAAqB,CAAA;AACvB,CAAC,EANW,WAAW,2BAAX,WAAW,QAMtB;AA0ED,IAAY,OAiBX;AAjBD,WAAY,OAAO;IACjB,mCAAO,CAAA;IACP,8CAAa,CAAA;IACb,oCAAQ,CAAA;IACR,6CAAa,CAAA;IACb,2CAAY,CAAA;IACZ,wCAAW,CAAA;IACX,iDAAgB,CAAA;IAChB,mDAAiB,CAAA;IACjB,2CAAa,CAAA;IACb,wDAAyB,CAAA;IACzB,gDAAoB,CAAA;IACpB,6CAAgB,CAAA;IAChB,sCAAU,CAAA;IACV,yCAAW,CAAA;IACX,+CAAc,CAAA;IACd,8CAAc,CAAA;AAChB,CAAC,EAjBW,OAAO,uBAAP,OAAO,QAiBlB;AAQD,IAAY,aAIX;AAJD,WAAY,aAAa;IACvB,uDAAW,CAAA;IACX,uDAAW,CAAA;IACX,mDAAS,CAAA;AACX,CAAC,EAJW,aAAa,6BAAb,aAAa,QAIxB","sourcesContent":["/* eslint-disable @typescript-eslint/naming-convention */\nimport type { AccountsControllerGetAccountByAddressAction } from '@metamask/accounts-controller';\nimport type { AssetsControllerGetExchangeRatesForBridgeAction } from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n MultichainAssetsRatesControllerGetStateAction,\n TokenRatesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n NetworkControllerFindNetworkClientIdByChainIdAction,\n NetworkControllerGetNetworkClientByIdAction,\n} from '@metamask/network-controller';\nimport type { AuthenticationControllerGetBearerTokenAction } from '@metamask/profile-sync-controller/auth';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SnapControllerHandleRequestAction } from '@metamask/snaps-controllers';\nimport type { Infer } from '@metamask/superstruct';\nimport type {\n CaipAccountId,\n CaipAssetId,\n CaipAssetType,\n CaipChainId,\n Hex,\n} from '@metamask/utils';\n\nimport type { BridgeController } from './bridge-controller';\nimport type { BridgeControllerMethodActions } from './bridge-controller-method-action-types';\nimport type { BRIDGE_CONTROLLER_NAME } from './constants/bridge';\nimport type {\n BitcoinTradeDataSchema,\n BridgeAssetSchema,\n ChainConfigurationSchema,\n ChainRankingSchema,\n FeatureId,\n FeeDataSchema,\n IntentSchema,\n PlatformConfigSchema,\n ProtocolSchema,\n QuoteResponseSchema,\n QuoteSchema,\n StepSchema,\n TokenFeatureSchema,\n QuoteStreamCompleteSchema,\n TronTradeDataSchema,\n TxDataSchema,\n BatchSellTradesResponseSchema,\n GaslessPropertiesSchema,\n SimulatedGasFeeLimitsSchema,\n TxFeeGasLimitsSchema,\n} from './utils/validators';\n\nexport type FetchFunction = (\n input: RequestInfo | URL | string,\n init?: RequestInit,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => Promise<any>;\n\n/**\n * The types of assets that a user can send\n */\nexport enum AssetType {\n /** The native asset for the current network, such as ETH */\n native = 'NATIVE',\n /** An ERC20 token */\n token = 'TOKEN',\n /** An ERC721 or ERC1155 token. */\n NFT = 'NFT',\n /**\n * A transaction interacting with a contract that isn't a token method\n * interaction will be marked as dealing with an unknown asset type.\n */\n unknown = 'UNKNOWN',\n}\n\nexport type ChainConfiguration = Infer<typeof ChainConfigurationSchema>;\n\nexport type ChainRanking = Infer<typeof ChainRankingSchema>;\n\nexport type L1GasFees = {\n l1GasFeesInHexWei?: string; // l1 fees for approval and trade in hex wei, appended by BridgeController.#appendL1GasFees\n};\n\nexport type NonEvmFees = {\n nonEvmFeesInNative?: string; // Non-EVM chain fees in native units (SOL for Solana, BTC for Bitcoin)\n};\n\n/**\n * The types of values for the token amount and its values when converted to the user's selected currency and USD\n */\nexport type TokenAmountValues = {\n /**\n * The amount of the token\n *\n * @example \"1.005\"\n */\n amount: string;\n /**\n * The amount of the token in the user's selected currency\n *\n * @example \"4.55\"\n */\n valueInCurrency: string | null;\n /**\n * The amount of the token in USD\n *\n * @example \"1.234\"\n */\n usd: string | null;\n};\n\n/**\n * Asset exchange rate values for a given chain and address\n */\nexport type ExchangeRate = { exchangeRate?: string; usdExchangeRate?: string };\n\n/**\n * Values derived from the quote response\n */\nexport type QuoteMetadata = {\n /**\n * If gas is included, this is the value of the src or dest token that was used to pay for the gas.\n * Show this value to indicate transaction fees for gasless quotes.\n */\n includedTxFees?: TokenAmountValues | null;\n /**\n * The gas fee for the bridge transaction.\n * effective is the gas fee that is shown to the user. If this value is not\n * included in the trade, the calculation falls back to the gasLimit (total)\n * total is the gas fee that is spent by the user, including refunds.\n * max is the max gas fee that will be used by the transaction.\n */\n gasFee: Record<'effective' | 'total' | 'max', TokenAmountValues>;\n /**\n * The total network fee required to submit the trade and any approvals. This includes\n * the relayer fee or other native fees. Should be used for balance checks and tx submission.\n * Note: This is only accurate for non-gasless transactions. Use {@link QuoteMetadata.includedTxFees} to\n * get the total network fee for gasless transactions.\n */\n totalNetworkFee: TokenAmountValues; // estimatedGasFees + relayerFees\n totalMaxNetworkFee: TokenAmountValues; // maxGasFees + relayerFees\n /**\n * The amount that the user will receive (destTokenAmount)\n */\n toTokenAmount: TokenAmountValues;\n /**\n * The minimum amount that the user will receive (minDestTokenAmount)\n */\n minToTokenAmount: TokenAmountValues;\n /**\n * If gas is included: {@link QuoteMetadata.toTokenAmount} - {@link QuoteMetadata.includedTxFees}.\n * Otherwise: {@link QuoteMetadata.toTokenAmount} - {@link QuoteMetadata.totalNetworkFee}.\n */\n adjustedReturn: Omit<TokenAmountValues, 'amount'>;\n /**\n * The amount that the user will send, including fees that are paid in the src token\n * {@link Quote.srcTokenAmount} + {@link Quote.feeData[FeeType.METABRIDGE].amount} + {@link Quote.feeData[FeeType.TX_FEE].amount}\n */\n sentAmount: TokenAmountValues;\n /**\n * The swap rate is the amount that the user will receive per amount sent. Accounts for fees paid in the src or dest token.\n * This is calculated as {@link QuoteMetadata.toTokenAmount} / {@link QuoteMetadata.sentAmount}.\n */\n swapRate: string;\n /**\n * The cost of the trade, which is the difference between the amount sent and the adjusted return.\n * This is calculated as {@link QuoteMetadata.sentAmount} - {@link QuoteMetadata.adjustedReturn}.\n */\n cost: Omit<TokenAmountValues, 'amount'>; // sentAmount - adjustedReturn\n};\n\n/**\n * Sort order set by the user\n */\nexport enum SortOrder {\n COST_ASC = 'cost_ascending',\n ETA_ASC = 'time_descending',\n}\n\n/**\n * This is the interface for the asset object returned by the bridge-api\n * This type is used in the QuoteResponse and in the fetchBridgeTokens response\n */\nexport type BridgeAsset = Infer<typeof BridgeAssetSchema>;\n\n/**\n * This is the interface for the token object used in the extension client\n * In addition to the {@link BridgeAsset} fields, it includes balance information\n */\nexport type BridgeToken = {\n address: string;\n symbol: string;\n image: string;\n decimals: number;\n chainId: number | Hex | ChainId | CaipChainId;\n balance: string; // raw balance\n // TODO deprecate this field and use balance instead\n string: string | undefined; // normalized balance as a stringified number\n tokenFiatAmount?: number | null;\n occurrences?: number;\n};\n\ntype DecimalChainId = string;\nexport type GasMultiplierByChainId = Record<DecimalChainId, number>;\n\nexport type FeatureFlagResponse = Infer<typeof PlatformConfigSchema>;\n\n// TODO move definition to validators.ts\n/**\n * This is the interface for the quote request sent to the bridge-api\n * and should only be used by the fetchBridgeQuotes utility function\n * Components and redux stores should use the {@link GenericQuoteRequest} type\n */\nexport type QuoteRequest<\n ChainIdType = ChainId | number,\n TokenAddressType = string,\n WalletAddressType = string,\n> = {\n walletAddress: WalletAddressType;\n destWalletAddress?: WalletAddressType;\n srcChainId: ChainIdType;\n destChainId: ChainIdType;\n srcTokenAddress: TokenAddressType;\n destTokenAddress: TokenAddressType;\n /**\n * This is the amount sent, in atomic amount\n */\n srcTokenAmount: string;\n slippage?: number;\n aggIds?: string[];\n bridgeIds?: string[];\n insufficientBal?: boolean;\n resetApproval?: boolean;\n refuel?: boolean;\n /**\n * Whether the response should include gasless swap quotes\n * This should be true if the user has opted in to STX on the client\n * and the current network has STX support\n */\n gasIncluded: boolean;\n /**\n * Whether to request quotes that use EIP-7702 delegated gasless execution\n */\n gasIncluded7702: boolean;\n /**\n * The fee that will be charged by MetaMask\n */\n fee?: number;\n};\n\nexport enum StatusTypes {\n SUBMITTED = 'SUBMITTED',\n UNKNOWN = 'UNKNOWN',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n COMPLETE = 'COMPLETE',\n}\n\n/**\n * These are types that components pass in. Since data is a mix of types when coming from the redux store, we need to use a generic type that can cover all the types.\n * Payloads with this type are transformed into QuoteRequest by fetchBridgeQuotes right before fetching quotes\n */\nexport type GenericQuoteRequest = QuoteRequest<\n Hex | CaipChainId | string | number, // chainIds\n Hex | CaipAssetId | string, // assetIds/addresses\n Hex | CaipAccountId | string // accountIds/addresses\n>;\n\nexport type Protocol = Infer<typeof ProtocolSchema>;\n\nexport type Step = Infer<typeof StepSchema>;\n\nexport type RefuelData = Step;\n\nexport type FeeData = Infer<typeof FeeDataSchema>;\n\nexport type Quote = Infer<typeof QuoteSchema>;\n\nexport type TxData = Infer<typeof TxDataSchema>;\n\nexport type Intent = Infer<typeof IntentSchema>;\nexport type IntentOrderLike = Intent['order'];\n\nexport type BitcoinTradeData = Infer<typeof BitcoinTradeDataSchema>;\n\nexport type TronTradeData = Infer<typeof TronTradeDataSchema>;\n/**\n * This is the type for the quote response from the bridge-api\n * TxDataType can be overriden to be a string when the quote is non-evm\n * ApprovalType can be overriden when you know the specific approval type (e.g., TxData for EVM-only contexts)\n */\nexport type QuoteResponse<\n TxDataType = TxData | string | BitcoinTradeData | TronTradeData,\n ApprovalType = TxData | TronTradeData,\n> = Infer<typeof QuoteResponseSchema> & {\n trade: TxDataType;\n approval?: ApprovalType;\n /**\n * Appended to the quote response based on the quote request\n */\n featureId?: FeatureId;\n /**\n * Appended to the quote response based on the quote request resetApproval flag\n * If defined, the quote's total network fee will include the reset approval's gas limit.\n */\n resetApproval?: TxData;\n /**\n * Appended to the quote if there are multiple quote requests in a batch. This\n * indicates which quoteRequest the quote is for\n */\n quoteRequestIndex?: number;\n};\n\nexport type BatchSellTradesRequest = {\n quotes: QuoteResponse[];\n stxEnabled: boolean;\n};\n\n/**\n * This is the bridge-api response for the obtainGaslessBatch method\n */\nexport type BatchSellTradesResponse = Infer<\n typeof BatchSellTradesResponseSchema\n>;\n\nexport type SimulatedGasFeeLimits = Infer<typeof SimulatedGasFeeLimitsSchema>;\nexport type TxFeeGasLimits = Infer<typeof TxFeeGasLimitsSchema>;\n\nexport type GaslessProperties = Infer<typeof GaslessPropertiesSchema>;\n\nexport enum ChainId {\n ETH = 1,\n OPTIMISM = 10,\n BSC = 56,\n POLYGON = 137,\n ZKSYNC = 324,\n BASE = 8453,\n ARBITRUM = 42161,\n AVALANCHE = 43114,\n LINEA = 59144,\n SOLANA = 1151111081099710,\n BTC = 20000000000001,\n TRON = 728126428,\n SEI = 1329,\n MONAD = 143,\n HYPEREVM = 999,\n MEGAETH = 4326,\n}\n\nexport type FeatureFlagsPlatformConfig = Infer<typeof PlatformConfigSchema>;\n\nexport type TokenFeature = Infer<typeof TokenFeatureSchema>;\n\nexport type QuoteStreamCompleteData = Infer<typeof QuoteStreamCompleteSchema>;\n\nexport enum RequestStatus {\n LOADING = 0,\n FETCHED = 1,\n ERROR = 2,\n}\n\nexport type BridgeControllerState = {\n quoteRequest: Partial<GenericQuoteRequest>[];\n quotes: (QuoteResponse & L1GasFees & NonEvmFees)[];\n /**\n * The time elapsed between the initial quote fetch and when the first valid quote was received\n */\n quotesInitialLoadTime: number | null;\n /**\n * The timestamp of when the latest quote fetch started\n */\n quotesLastFetched: number | null;\n /**\n * The status of the quote fetch, including fee calculations and validations\n * This is set to\n * - LOADING when the quote fetch starts\n * - FETCHED when the process completes successfully, including when quotes are empty\n * - ERROR when any errors occur\n *\n * When SSE is enabled, this is set to LOADING even when a quote is available. It is only\n * set to FETCHED when the stream is closed and all quotes have been received\n */\n quotesLoadingStatus: RequestStatus | null;\n quoteFetchError: string | null;\n /**\n * The number of times the quotes have been refreshed, starts at 0 and is\n * incremented at the end of each quote fetch\n */\n quotesRefreshCount: number;\n /**\n * Asset exchange rates for EVM and multichain assets that are not indexed by the assets controllers\n */\n assetExchangeRates: Record<CaipAssetType, ExchangeRate>;\n /**\n * When the src token is SOL, this needs to be subtracted from their balance to determine\n * the max amount that can be sent.\n */\n minimumBalanceForRentExemptionInLamports: string | null;\n /**\n * Security alerts for the destination token in the current quote request,\n * populated from `token_warning` SSE events.\n */\n tokenWarnings: TokenFeature[];\n /**\n * Client-supplied security classification for the destination token in the\n * current quote request, used as the `token_security_type_destination`\n * analytics property. Set via the `context` arg of\n * `updateBridgeQuoteRequestParams` and reset whenever the quote request is\n * reset. `null` when the client has no security data for the token.\n */\n tokenSecurityTypeDestination: string | null;\n /**\n * Metadata about the completed quote stream, populated from the `complete` SSE event.\n * Set to null at the start of each fetch and updated when the complete event is received.\n */\n quoteStreamComplete: QuoteStreamCompleteData | null;\n /**\n * Contains gasless transaction data and fees for BatchSell quotes, provided by the obtainGaslessBatch API\n */\n batchSellTrades: BatchSellTradesResponse | null;\n /**\n * The status of the batch sell trades fetch, including fee calculations and validations\n */\n batchSellTradesLoadingStatus: RequestStatus | null;\n};\n\n/**\n * @deprecated Use the separate method action types (e.g.,\n * `BridgeControllerFetchQuotesAction`) instead.\n */\nexport type BridgeControllerAction<\n FunctionName extends keyof BridgeController,\n> = {\n type: `${typeof BRIDGE_CONTROLLER_NAME}:${FunctionName}`;\n handler: BridgeController[FunctionName];\n};\n\nexport type BridgeControllerGetStateAction = ControllerGetStateAction<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState\n>;\n\nexport type BridgeControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState\n>;\n\nexport type BridgeControllerActions =\n | BridgeControllerGetStateAction\n | BridgeControllerMethodActions;\n\nexport type BridgeControllerEvents = BridgeControllerStateChangeEvent;\n\nexport type AllowedActions =\n | AccountsControllerGetAccountByAddressAction\n | AuthenticationControllerGetBearerTokenAction\n | CurrencyRateControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | MultichainAssetsRatesControllerGetStateAction\n | SnapControllerHandleRequestAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | RemoteFeatureFlagControllerGetStateAction\n | AssetsControllerGetExchangeRatesForBridgeAction;\nexport type AllowedEvents = never;\n\n/**\n * The messenger for the BridgeController.\n */\nexport type BridgeControllerMessenger = Messenger<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerActions | AllowedActions,\n BridgeControllerEvents | AllowedEvents\n>;\n"]}
|
|
1
|
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kBlB;AAQD,IAAY,aAIX;AAJD,WAAY,aAAa;IACvB,uDAAW,CAAA;IACX,uDAAW,CAAA;IACX,mDAAS,CAAA;AACX,CAAC,EAJW,aAAa,6BAAb,aAAa,QAIxB","sourcesContent":["/* eslint-disable @typescript-eslint/naming-convention */\nimport type { AccountsControllerGetAccountByAddressAction } from '@metamask/accounts-controller';\nimport type { AssetsControllerGetExchangeRatesForBridgeAction } from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n MultichainAssetsRatesControllerGetStateAction,\n TokenRatesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n NetworkControllerFindNetworkClientIdByChainIdAction,\n NetworkControllerGetNetworkClientByIdAction,\n} from '@metamask/network-controller';\nimport type { AuthenticationControllerGetBearerTokenAction } from '@metamask/profile-sync-controller/auth';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SnapControllerHandleRequestAction } from '@metamask/snaps-controllers';\nimport type { Infer } from '@metamask/superstruct';\nimport type {\n CaipAccountId,\n CaipAssetId,\n CaipAssetType,\n CaipChainId,\n Hex,\n} from '@metamask/utils';\n\nimport type { BridgeController } from './bridge-controller';\nimport type { BridgeControllerMethodActions } from './bridge-controller-method-action-types';\nimport type { BRIDGE_CONTROLLER_NAME } from './constants/bridge';\nimport type {\n BitcoinTradeDataSchema,\n BridgeAssetSchema,\n ChainConfigurationSchema,\n ChainRankingSchema,\n FeeDataSchema,\n IntentSchema,\n PlatformConfigSchema,\n ProtocolSchema,\n QuoteResponseSchema,\n QuoteSchema,\n StepSchema,\n TokenFeatureSchema,\n QuoteStreamCompleteSchema,\n TronTradeDataSchema,\n TxDataSchema,\n BatchSellTradesResponseSchema,\n GaslessPropertiesSchema,\n SimulatedGasFeeLimitsSchema,\n TxFeeGasLimitsSchema,\n} from './utils/validators';\n\nexport type FetchFunction = (\n input: RequestInfo | URL | string,\n init?: RequestInit,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => Promise<any>;\n\n/**\n * The types of assets that a user can send\n */\nexport enum AssetType {\n /** The native asset for the current network, such as ETH */\n native = 'NATIVE',\n /** An ERC20 token */\n token = 'TOKEN',\n /** An ERC721 or ERC1155 token. */\n NFT = 'NFT',\n /**\n * A transaction interacting with a contract that isn't a token method\n * interaction will be marked as dealing with an unknown asset type.\n */\n unknown = 'UNKNOWN',\n}\n\nexport type ChainConfiguration = Infer<typeof ChainConfigurationSchema>;\n\nexport type ChainRanking = Infer<typeof ChainRankingSchema>;\n\nexport type L1GasFees = {\n l1GasFeesInHexWei?: string; // l1 fees for approval and trade in hex wei, appended by BridgeController.#appendL1GasFees\n};\n\nexport type NonEvmFees = {\n nonEvmFeesInNative?: string; // Non-EVM chain fees in native units (SOL for Solana, BTC for Bitcoin)\n};\n\n/**\n * The types of values for the token amount and its values when converted to the user's selected currency and USD\n */\nexport type TokenAmountValues = {\n /**\n * The amount of the token\n *\n * @example \"1.005\"\n */\n amount: string;\n /**\n * The amount of the token in the user's selected currency\n *\n * @example \"4.55\"\n */\n valueInCurrency: string | null;\n /**\n * The amount of the token in USD\n *\n * @example \"1.234\"\n */\n usd: string | null;\n};\n\n/**\n * Asset exchange rate values for a given chain and address\n */\nexport type ExchangeRate = { exchangeRate?: string; usdExchangeRate?: string };\n\n/**\n * Values derived from the quote response\n */\nexport type QuoteMetadata = {\n /**\n * If gas is included, this is the value of the src or dest token that was used to pay for the gas.\n * Show this value to indicate transaction fees for gasless quotes.\n */\n includedTxFees?: TokenAmountValues | null;\n /**\n * The gas fee for the bridge transaction.\n * effective is the gas fee that is shown to the user. If this value is not\n * included in the trade, the calculation falls back to the gasLimit (total)\n * total is the gas fee that is spent by the user, including refunds.\n * max is the max gas fee that will be used by the transaction.\n */\n gasFee: Record<'effective' | 'total' | 'max', TokenAmountValues>;\n /**\n * The total network fee required to submit the trade and any approvals. This includes\n * the relayer fee or other native fees. Should be used for balance checks and tx submission.\n * Note: This is only accurate for non-gasless transactions. Use {@link QuoteMetadata.includedTxFees} to\n * get the total network fee for gasless transactions.\n */\n totalNetworkFee: TokenAmountValues; // estimatedGasFees + relayerFees\n totalMaxNetworkFee: TokenAmountValues; // maxGasFees + relayerFees\n /**\n * The amount that the user will receive (destTokenAmount)\n */\n toTokenAmount: TokenAmountValues;\n /**\n * The minimum amount that the user will receive (minDestTokenAmount)\n */\n minToTokenAmount: TokenAmountValues;\n /**\n * If gas is included: {@link QuoteMetadata.toTokenAmount} - {@link QuoteMetadata.includedTxFees}.\n * Otherwise: {@link QuoteMetadata.toTokenAmount} - {@link QuoteMetadata.totalNetworkFee}.\n */\n adjustedReturn: Omit<TokenAmountValues, 'amount'>;\n /**\n * The amount that the user will send, including fees that are paid in the src token\n * {@link Quote.srcTokenAmount} + {@link Quote.feeData[FeeType.METABRIDGE].amount} + {@link Quote.feeData[FeeType.TX_FEE].amount}\n */\n sentAmount: TokenAmountValues;\n /**\n * The swap rate is the amount that the user will receive per amount sent. Accounts for fees paid in the src or dest token.\n * This is calculated as {@link QuoteMetadata.toTokenAmount} / {@link QuoteMetadata.sentAmount}.\n */\n swapRate: string;\n /**\n * The cost of the trade, which is the difference between the amount sent and the adjusted return.\n * This is calculated as {@link QuoteMetadata.sentAmount} - {@link QuoteMetadata.adjustedReturn}.\n */\n cost: Omit<TokenAmountValues, 'amount'>; // sentAmount - adjustedReturn\n};\n\n/**\n * Sort order set by the user\n */\nexport enum SortOrder {\n COST_ASC = 'cost_ascending',\n ETA_ASC = 'time_descending',\n}\n\n/**\n * This is the interface for the asset object returned by the bridge-api\n * This type is used in the QuoteResponse and in the fetchBridgeTokens response\n */\nexport type BridgeAsset = Infer<typeof BridgeAssetSchema>;\n\n/**\n * This is the interface for the token object used in the extension client\n * In addition to the {@link BridgeAsset} fields, it includes balance information\n */\nexport type BridgeToken = {\n address: string;\n symbol: string;\n image: string;\n decimals: number;\n chainId: number | Hex | ChainId | CaipChainId;\n balance: string; // raw balance\n // TODO deprecate this field and use balance instead\n string: string | undefined; // normalized balance as a stringified number\n tokenFiatAmount?: number | null;\n occurrences?: number;\n};\n\ntype DecimalChainId = string;\nexport type GasMultiplierByChainId = Record<DecimalChainId, number>;\n\nexport type FeatureFlagResponse = Infer<typeof PlatformConfigSchema>;\n\n// TODO move definition to validators.ts\n/**\n * This is the interface for the quote request sent to the bridge-api\n * and should only be used by the fetchBridgeQuotes utility function\n * Components and redux stores should use the {@link GenericQuoteRequest} type\n */\nexport type QuoteRequest<\n ChainIdType = ChainId | number,\n TokenAddressType = string,\n WalletAddressType = string,\n> = {\n walletAddress: WalletAddressType;\n destWalletAddress?: WalletAddressType;\n srcChainId: ChainIdType;\n destChainId: ChainIdType;\n srcTokenAddress: TokenAddressType;\n destTokenAddress: TokenAddressType;\n /**\n * This is the amount sent, in atomic amount\n */\n srcTokenAmount: string;\n slippage?: number;\n aggIds?: string[];\n bridgeIds?: string[];\n insufficientBal?: boolean;\n resetApproval?: boolean;\n refuel?: boolean;\n /**\n * Whether the response should include gasless swap quotes\n * This should be true if the user has opted in to STX on the client\n * and the current network has STX support\n */\n gasIncluded: boolean;\n /**\n * Whether to request quotes that use EIP-7702 delegated gasless execution\n */\n gasIncluded7702: boolean;\n /**\n * The fee that will be charged by MetaMask\n */\n fee?: number;\n};\n\nexport enum StatusTypes {\n SUBMITTED = 'SUBMITTED',\n UNKNOWN = 'UNKNOWN',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n COMPLETE = 'COMPLETE',\n}\n\nexport enum FeatureId {\n UNKNOWN = 'unknown',\n PERPS = 'perps',\n QUICK_BUY_FOLLOW_TRADING = 'quick_buy_follow_trading',\n QUICK_BUY_TOKEN_DETAILS = 'quick_buy_token_details',\n DAPP_SWAP = 'dapp_swap',\n BATCH_SELL = 'batch_sell',\n UNIFIED_SWAP_BRIDGE = 'unified_swap_bridge',\n}\n\n/**\n * These are types that components pass in. Since data is a mix of types when coming from the redux store, we need to use a generic type that can cover all the types.\n * Payloads with this type are transformed into QuoteRequest by fetchBridgeQuotes right before fetching quotes\n */\nexport type GenericQuoteRequest = QuoteRequest<\n Hex | CaipChainId | string | number, // chainIds\n Hex | CaipAssetId | string, // assetIds/addresses\n Hex | CaipAccountId | string // accountIds/addresses\n>;\n\nexport type Protocol = Infer<typeof ProtocolSchema>;\n\nexport type Step = Infer<typeof StepSchema>;\n\nexport type RefuelData = Step;\n\nexport type FeeData = Infer<typeof FeeDataSchema>;\n\nexport type Quote = Infer<typeof QuoteSchema>;\n\nexport type TxData = Infer<typeof TxDataSchema>;\n\nexport type Intent = Infer<typeof IntentSchema>;\nexport type IntentOrderLike = Intent['order'];\n\nexport type BitcoinTradeData = Infer<typeof BitcoinTradeDataSchema>;\n\nexport type TronTradeData = Infer<typeof TronTradeDataSchema>;\n/**\n * This is the type for the quote response from the bridge-api\n * TxDataType can be overriden to be a string when the quote is non-evm\n * ApprovalType can be overriden when you know the specific approval type (e.g., TxData for EVM-only contexts)\n */\nexport type QuoteResponse<\n TxDataType = TxData | string | BitcoinTradeData | TronTradeData,\n ApprovalType = TxData | TronTradeData,\n> = Infer<typeof QuoteResponseSchema> & {\n trade: TxDataType;\n approval?: ApprovalType;\n /**\n * Appended to the quote response based on the quote request\n */\n featureId?: FeatureId;\n /**\n * Appended to the quote response based on the quote request resetApproval flag\n * If defined, the quote's total network fee will include the reset approval's gas limit.\n */\n resetApproval?: TxData;\n /**\n * Appended to the quote if there are multiple quote requests in a batch. This\n * indicates which quoteRequest the quote is for\n */\n quoteRequestIndex?: number;\n};\n\nexport type BatchSellTradesRequest = {\n quotes: QuoteResponse[];\n stxEnabled: boolean;\n};\n\n/**\n * This is the bridge-api response for the obtainGaslessBatch method\n */\nexport type BatchSellTradesResponse = Infer<\n typeof BatchSellTradesResponseSchema\n>;\n\nexport type SimulatedGasFeeLimits = Infer<typeof SimulatedGasFeeLimitsSchema>;\nexport type TxFeeGasLimits = Infer<typeof TxFeeGasLimitsSchema>;\n\nexport type GaslessProperties = Infer<typeof GaslessPropertiesSchema>;\n\nexport enum ChainId {\n ETH = 1,\n OPTIMISM = 10,\n BSC = 56,\n POLYGON = 137,\n ZKSYNC = 324,\n BASE = 8453,\n ARBITRUM = 42161,\n AVALANCHE = 43114,\n LINEA = 59144,\n SOLANA = 1151111081099710,\n BTC = 20000000000001,\n TRON = 728126428,\n SEI = 1329,\n MONAD = 143,\n HYPEREVM = 999,\n MEGAETH = 4326,\n ARC = 5042,\n}\n\nexport type FeatureFlagsPlatformConfig = Infer<typeof PlatformConfigSchema>;\n\nexport type TokenFeature = Infer<typeof TokenFeatureSchema>;\n\nexport type QuoteStreamCompleteData = Infer<typeof QuoteStreamCompleteSchema>;\n\nexport enum RequestStatus {\n LOADING = 0,\n FETCHED = 1,\n ERROR = 2,\n}\n\nexport type BridgeControllerState = {\n quoteRequest: Partial<GenericQuoteRequest>[];\n quotes: (QuoteResponse & L1GasFees & NonEvmFees)[];\n /**\n * The time elapsed between the initial quote fetch and when the first valid quote was received\n */\n quotesInitialLoadTime: number | null;\n /**\n * The timestamp of when the latest quote fetch started\n */\n quotesLastFetched: number | null;\n /**\n * The status of the quote fetch, including fee calculations and validations\n * This is set to\n * - LOADING when the quote fetch starts\n * - FETCHED when the process completes successfully, including when quotes are empty\n * - ERROR when any errors occur\n *\n * When SSE is enabled, this is set to LOADING even when a quote is available. It is only\n * set to FETCHED when the stream is closed and all quotes have been received\n */\n quotesLoadingStatus: RequestStatus | null;\n quoteFetchError: string | null;\n /**\n * The number of times the quotes have been refreshed, starts at 0 and is\n * incremented at the end of each quote fetch\n */\n quotesRefreshCount: number;\n /**\n * Asset exchange rates for EVM and multichain assets that are not indexed by the assets controllers\n */\n assetExchangeRates: Record<CaipAssetType, ExchangeRate>;\n /**\n * When the src token is SOL, this needs to be subtracted from their balance to determine\n * the max amount that can be sent.\n */\n minimumBalanceForRentExemptionInLamports: string | null;\n /**\n * Security alerts for the destination token in the current quote request,\n * populated from `token_warning` SSE events.\n */\n tokenWarnings: TokenFeature[];\n /**\n * Client-supplied security classification for the destination token in the\n * current quote request, used as the `token_security_type_destination`\n * analytics property. Set via the `context` arg of\n * `updateBridgeQuoteRequestParams` and reset whenever the quote request is\n * reset. `null` when the client has no security data for the token.\n */\n tokenSecurityTypeDestination: string | null;\n /**\n * Metadata about the completed quote stream, populated from the `complete` SSE event.\n * Set to null at the start of each fetch and updated when the complete event is received.\n */\n quoteStreamComplete: QuoteStreamCompleteData | null;\n /**\n * Contains gasless transaction data and fees for BatchSell quotes, provided by the obtainGaslessBatch API\n */\n batchSellTrades: BatchSellTradesResponse | null;\n /**\n * The status of the batch sell trades fetch, including fee calculations and validations\n */\n batchSellTradesLoadingStatus: RequestStatus | null;\n};\n\n/**\n * @deprecated Use the separate method action types (e.g.,\n * `BridgeControllerFetchQuotesAction`) instead.\n */\nexport type BridgeControllerAction<\n FunctionName extends keyof BridgeController,\n> = {\n type: `${typeof BRIDGE_CONTROLLER_NAME}:${FunctionName}`;\n handler: BridgeController[FunctionName];\n};\n\nexport type BridgeControllerGetStateAction = ControllerGetStateAction<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState\n>;\n\nexport type BridgeControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState\n>;\n\nexport type BridgeControllerActions =\n | BridgeControllerGetStateAction\n | BridgeControllerMethodActions;\n\nexport type BridgeControllerEvents = BridgeControllerStateChangeEvent;\n\nexport type AllowedActions =\n | AccountsControllerGetAccountByAddressAction\n | AuthenticationControllerGetBearerTokenAction\n | CurrencyRateControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | MultichainAssetsRatesControllerGetStateAction\n | SnapControllerHandleRequestAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | RemoteFeatureFlagControllerGetStateAction\n | AssetsControllerGetExchangeRatesForBridgeAction;\nexport type AllowedEvents = never;\n\n/**\n * The messenger for the BridgeController.\n */\nexport type BridgeControllerMessenger = Messenger<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerActions | AllowedActions,\n BridgeControllerEvents | AllowedEvents\n>;\n"]}
|
package/dist/types.d.cts
CHANGED
|
@@ -12,7 +12,7 @@ import type { CaipAccountId, CaipAssetId, CaipAssetType, CaipChainId, Hex } from
|
|
|
12
12
|
import type { BridgeController } from "./bridge-controller.cjs";
|
|
13
13
|
import type { BridgeControllerMethodActions } from "./bridge-controller-method-action-types.cjs";
|
|
14
14
|
import type { BRIDGE_CONTROLLER_NAME } from "./constants/bridge.cjs";
|
|
15
|
-
import type { BitcoinTradeDataSchema, BridgeAssetSchema, ChainConfigurationSchema, ChainRankingSchema,
|
|
15
|
+
import type { BitcoinTradeDataSchema, BridgeAssetSchema, ChainConfigurationSchema, ChainRankingSchema, FeeDataSchema, IntentSchema, PlatformConfigSchema, ProtocolSchema, QuoteResponseSchema, QuoteSchema, StepSchema, TokenFeatureSchema, QuoteStreamCompleteSchema, TronTradeDataSchema, TxDataSchema, BatchSellTradesResponseSchema, GaslessPropertiesSchema, SimulatedGasFeeLimitsSchema, TxFeeGasLimitsSchema } from "./utils/validators.cjs";
|
|
16
16
|
export type FetchFunction = (input: RequestInfo | URL | string, init?: RequestInit) => Promise<any>;
|
|
17
17
|
/**
|
|
18
18
|
* The types of assets that a user can send
|
|
@@ -196,6 +196,15 @@ export declare enum StatusTypes {
|
|
|
196
196
|
PENDING = "PENDING",
|
|
197
197
|
COMPLETE = "COMPLETE"
|
|
198
198
|
}
|
|
199
|
+
export declare enum FeatureId {
|
|
200
|
+
UNKNOWN = "unknown",
|
|
201
|
+
PERPS = "perps",
|
|
202
|
+
QUICK_BUY_FOLLOW_TRADING = "quick_buy_follow_trading",
|
|
203
|
+
QUICK_BUY_TOKEN_DETAILS = "quick_buy_token_details",
|
|
204
|
+
DAPP_SWAP = "dapp_swap",
|
|
205
|
+
BATCH_SELL = "batch_sell",
|
|
206
|
+
UNIFIED_SWAP_BRIDGE = "unified_swap_bridge"
|
|
207
|
+
}
|
|
199
208
|
/**
|
|
200
209
|
* These are types that components pass in. Since data is a mix of types when coming from the redux store, we need to use a generic type that can cover all the types.
|
|
201
210
|
* Payloads with this type are transformed into QuoteRequest by fetchBridgeQuotes right before fetching quotes
|
|
@@ -265,7 +274,8 @@ export declare enum ChainId {
|
|
|
265
274
|
SEI = 1329,
|
|
266
275
|
MONAD = 143,
|
|
267
276
|
HYPEREVM = 999,
|
|
268
|
-
MEGAETH = 4326
|
|
277
|
+
MEGAETH = 4326,
|
|
278
|
+
ARC = 5042
|
|
269
279
|
}
|
|
270
280
|
export type FeatureFlagsPlatformConfig = Infer<typeof PlatformConfigSchema>;
|
|
271
281
|
export type TokenFeature = Infer<typeof TokenFeatureSchema>;
|
package/dist/types.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2CAA2C,EAAE,sCAAsC;AACjG,OAAO,KAAK,EAAE,+CAA+C,EAAE,oCAAoC;AACnG,OAAO,KAAK,EACV,oCAAoC,EACpC,6CAA6C,EAC7C,kCAAkC,EACnC,qCAAqC;AACtC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EACV,mDAAmD,EACnD,2CAA2C,EAC5C,qCAAqC;AACtC,OAAO,KAAK,EAAE,4CAA4C,EAAE,+CAA+C;AAC3G,OAAO,KAAK,EAAE,yCAAyC,EAAE,iDAAiD;AAC1G,OAAO,KAAK,EAAE,iCAAiC,EAAE,oCAAoC;AACrF,OAAO,KAAK,EAAE,KAAK,EAAE,8BAA8B;AACnD,OAAO,KAAK,EACV,aAAa,EACb,WAAW,EACX,aAAa,EACb,WAAW,EACX,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pD,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC;AAElC;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG,SAAS,CAC/C,OAAO,sBAAsB,EAC7B,uBAAuB,GAAG,cAAc,EACxC,sBAAsB,GAAG,aAAa,CACvC,CAAC"}
|
package/dist/types.d.mts
CHANGED
|
@@ -12,7 +12,7 @@ import type { CaipAccountId, CaipAssetId, CaipAssetType, CaipChainId, Hex } from
|
|
|
12
12
|
import type { BridgeController } from "./bridge-controller.mjs";
|
|
13
13
|
import type { BridgeControllerMethodActions } from "./bridge-controller-method-action-types.mjs";
|
|
14
14
|
import type { BRIDGE_CONTROLLER_NAME } from "./constants/bridge.mjs";
|
|
15
|
-
import type { BitcoinTradeDataSchema, BridgeAssetSchema, ChainConfigurationSchema, ChainRankingSchema,
|
|
15
|
+
import type { BitcoinTradeDataSchema, BridgeAssetSchema, ChainConfigurationSchema, ChainRankingSchema, FeeDataSchema, IntentSchema, PlatformConfigSchema, ProtocolSchema, QuoteResponseSchema, QuoteSchema, StepSchema, TokenFeatureSchema, QuoteStreamCompleteSchema, TronTradeDataSchema, TxDataSchema, BatchSellTradesResponseSchema, GaslessPropertiesSchema, SimulatedGasFeeLimitsSchema, TxFeeGasLimitsSchema } from "./utils/validators.mjs";
|
|
16
16
|
export type FetchFunction = (input: RequestInfo | URL | string, init?: RequestInit) => Promise<any>;
|
|
17
17
|
/**
|
|
18
18
|
* The types of assets that a user can send
|
|
@@ -196,6 +196,15 @@ export declare enum StatusTypes {
|
|
|
196
196
|
PENDING = "PENDING",
|
|
197
197
|
COMPLETE = "COMPLETE"
|
|
198
198
|
}
|
|
199
|
+
export declare enum FeatureId {
|
|
200
|
+
UNKNOWN = "unknown",
|
|
201
|
+
PERPS = "perps",
|
|
202
|
+
QUICK_BUY_FOLLOW_TRADING = "quick_buy_follow_trading",
|
|
203
|
+
QUICK_BUY_TOKEN_DETAILS = "quick_buy_token_details",
|
|
204
|
+
DAPP_SWAP = "dapp_swap",
|
|
205
|
+
BATCH_SELL = "batch_sell",
|
|
206
|
+
UNIFIED_SWAP_BRIDGE = "unified_swap_bridge"
|
|
207
|
+
}
|
|
199
208
|
/**
|
|
200
209
|
* These are types that components pass in. Since data is a mix of types when coming from the redux store, we need to use a generic type that can cover all the types.
|
|
201
210
|
* Payloads with this type are transformed into QuoteRequest by fetchBridgeQuotes right before fetching quotes
|
|
@@ -265,7 +274,8 @@ export declare enum ChainId {
|
|
|
265
274
|
SEI = 1329,
|
|
266
275
|
MONAD = 143,
|
|
267
276
|
HYPEREVM = 999,
|
|
268
|
-
MEGAETH = 4326
|
|
277
|
+
MEGAETH = 4326,
|
|
278
|
+
ARC = 5042
|
|
269
279
|
}
|
|
270
280
|
export type FeatureFlagsPlatformConfig = Infer<typeof PlatformConfigSchema>;
|
|
271
281
|
export type TokenFeature = Infer<typeof TokenFeatureSchema>;
|
package/dist/types.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2CAA2C,EAAE,sCAAsC;AACjG,OAAO,KAAK,EAAE,+CAA+C,EAAE,oCAAoC;AACnG,OAAO,KAAK,EACV,oCAAoC,EACpC,6CAA6C,EAC7C,kCAAkC,EACnC,qCAAqC;AACtC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EACV,mDAAmD,EACnD,2CAA2C,EAC5C,qCAAqC;AACtC,OAAO,KAAK,EAAE,4CAA4C,EAAE,+CAA+C;AAC3G,OAAO,KAAK,EAAE,yCAAyC,EAAE,iDAAiD;AAC1G,OAAO,KAAK,EAAE,iCAAiC,EAAE,oCAAoC;AACrF,OAAO,KAAK,EAAE,KAAK,EAAE,8BAA8B;AACnD,OAAO,KAAK,EACV,aAAa,EACb,WAAW,EACX,a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zC,+CAA+C,CAAC;AACpD,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC;AAElC;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG,SAAS,CAC/C,OAAO,sBAAsB,EAC7B,uBAAuB,GAAG,cAAc,EACxC,sBAAsB,GAAG,aAAa,CACvC,CAAC"}
|
package/dist/types.mjs
CHANGED
|
@@ -31,6 +31,16 @@ export var StatusTypes;
|
|
|
31
31
|
StatusTypes["PENDING"] = "PENDING";
|
|
32
32
|
StatusTypes["COMPLETE"] = "COMPLETE";
|
|
33
33
|
})(StatusTypes || (StatusTypes = {}));
|
|
34
|
+
export var FeatureId;
|
|
35
|
+
(function (FeatureId) {
|
|
36
|
+
FeatureId["UNKNOWN"] = "unknown";
|
|
37
|
+
FeatureId["PERPS"] = "perps";
|
|
38
|
+
FeatureId["QUICK_BUY_FOLLOW_TRADING"] = "quick_buy_follow_trading";
|
|
39
|
+
FeatureId["QUICK_BUY_TOKEN_DETAILS"] = "quick_buy_token_details";
|
|
40
|
+
FeatureId["DAPP_SWAP"] = "dapp_swap";
|
|
41
|
+
FeatureId["BATCH_SELL"] = "batch_sell";
|
|
42
|
+
FeatureId["UNIFIED_SWAP_BRIDGE"] = "unified_swap_bridge";
|
|
43
|
+
})(FeatureId || (FeatureId = {}));
|
|
34
44
|
export var ChainId;
|
|
35
45
|
(function (ChainId) {
|
|
36
46
|
ChainId[ChainId["ETH"] = 1] = "ETH";
|
|
@@ -49,6 +59,7 @@ export var ChainId;
|
|
|
49
59
|
ChainId[ChainId["MONAD"] = 143] = "MONAD";
|
|
50
60
|
ChainId[ChainId["HYPEREVM"] = 999] = "HYPEREVM";
|
|
51
61
|
ChainId[ChainId["MEGAETH"] = 4326] = "MEGAETH";
|
|
62
|
+
ChainId[ChainId["ARC"] = 5042] = "ARC";
|
|
52
63
|
})(ChainId || (ChainId = {}));
|
|
53
64
|
export var RequestStatus;
|
|
54
65
|
(function (RequestStatus) {
|
package/dist/types.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA6DA;;GAEG;AACH,MAAM,CAAN,IAAY,SAYX;AAZD,WAAY,SAAS;IACnB,4DAA4D;IAC5D,8BAAiB,CAAA;IACjB,qBAAqB;IACrB,4BAAe,CAAA;IACf,kCAAkC;IAClC,wBAAW,CAAA;IACX;;;OAGG;IACH,gCAAmB,CAAA;AACrB,CAAC,EAZW,SAAS,KAAT,SAAS,QAYpB;AAkGD;;GAEG;AACH,MAAM,CAAN,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,wCAA2B,CAAA;IAC3B,wCAA2B,CAAA;AAC7B,CAAC,EAHW,SAAS,KAAT,SAAS,QAGpB;AAyED,MAAM,CAAN,IAAY,WAMX;AAND,WAAY,WAAW;IACrB,sCAAuB,CAAA;IACvB,kCAAmB,CAAA;IACnB,gCAAiB,CAAA;IACjB,kCAAmB,CAAA;IACnB,oCAAqB,CAAA;AACvB,CAAC,EANW,WAAW,KAAX,WAAW,QAMtB;AA0ED,MAAM,CAAN,IAAY,OAiBX;AAjBD,WAAY,OAAO;IACjB,mCAAO,CAAA;IACP,8CAAa,CAAA;IACb,oCAAQ,CAAA;IACR,6CAAa,CAAA;IACb,2CAAY,CAAA;IACZ,wCAAW,CAAA;IACX,iDAAgB,CAAA;IAChB,mDAAiB,CAAA;IACjB,2CAAa,CAAA;IACb,wDAAyB,CAAA;IACzB,gDAAoB,CAAA;IACpB,6CAAgB,CAAA;IAChB,sCAAU,CAAA;IACV,yCAAW,CAAA;IACX,+CAAc,CAAA;IACd,8CAAc,CAAA;AAChB,CAAC,EAjBW,OAAO,KAAP,OAAO,QAiBlB;AAQD,MAAM,CAAN,IAAY,aAIX;AAJD,WAAY,aAAa;IACvB,uDAAW,CAAA;IACX,uDAAW,CAAA;IACX,mDAAS,CAAA;AACX,CAAC,EAJW,aAAa,KAAb,aAAa,QAIxB","sourcesContent":["/* eslint-disable @typescript-eslint/naming-convention */\nimport type { AccountsControllerGetAccountByAddressAction } from '@metamask/accounts-controller';\nimport type { AssetsControllerGetExchangeRatesForBridgeAction } from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n MultichainAssetsRatesControllerGetStateAction,\n TokenRatesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n NetworkControllerFindNetworkClientIdByChainIdAction,\n NetworkControllerGetNetworkClientByIdAction,\n} from '@metamask/network-controller';\nimport type { AuthenticationControllerGetBearerTokenAction } from '@metamask/profile-sync-controller/auth';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SnapControllerHandleRequestAction } from '@metamask/snaps-controllers';\nimport type { Infer } from '@metamask/superstruct';\nimport type {\n CaipAccountId,\n CaipAssetId,\n CaipAssetType,\n CaipChainId,\n Hex,\n} from '@metamask/utils';\n\nimport type { BridgeController } from './bridge-controller';\nimport type { BridgeControllerMethodActions } from './bridge-controller-method-action-types';\nimport type { BRIDGE_CONTROLLER_NAME } from './constants/bridge';\nimport type {\n BitcoinTradeDataSchema,\n BridgeAssetSchema,\n ChainConfigurationSchema,\n ChainRankingSchema,\n FeatureId,\n FeeDataSchema,\n IntentSchema,\n PlatformConfigSchema,\n ProtocolSchema,\n QuoteResponseSchema,\n QuoteSchema,\n StepSchema,\n TokenFeatureSchema,\n QuoteStreamCompleteSchema,\n TronTradeDataSchema,\n TxDataSchema,\n BatchSellTradesResponseSchema,\n GaslessPropertiesSchema,\n SimulatedGasFeeLimitsSchema,\n TxFeeGasLimitsSchema,\n} from './utils/validators';\n\nexport type FetchFunction = (\n input: RequestInfo | URL | string,\n init?: RequestInit,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => Promise<any>;\n\n/**\n * The types of assets that a user can send\n */\nexport enum AssetType {\n /** The native asset for the current network, such as ETH */\n native = 'NATIVE',\n /** An ERC20 token */\n token = 'TOKEN',\n /** An ERC721 or ERC1155 token. */\n NFT = 'NFT',\n /**\n * A transaction interacting with a contract that isn't a token method\n * interaction will be marked as dealing with an unknown asset type.\n */\n unknown = 'UNKNOWN',\n}\n\nexport type ChainConfiguration = Infer<typeof ChainConfigurationSchema>;\n\nexport type ChainRanking = Infer<typeof ChainRankingSchema>;\n\nexport type L1GasFees = {\n l1GasFeesInHexWei?: string; // l1 fees for approval and trade in hex wei, appended by BridgeController.#appendL1GasFees\n};\n\nexport type NonEvmFees = {\n nonEvmFeesInNative?: string; // Non-EVM chain fees in native units (SOL for Solana, BTC for Bitcoin)\n};\n\n/**\n * The types of values for the token amount and its values when converted to the user's selected currency and USD\n */\nexport type TokenAmountValues = {\n /**\n * The amount of the token\n *\n * @example \"1.005\"\n */\n amount: string;\n /**\n * The amount of the token in the user's selected currency\n *\n * @example \"4.55\"\n */\n valueInCurrency: string | null;\n /**\n * The amount of the token in USD\n *\n * @example \"1.234\"\n */\n usd: string | null;\n};\n\n/**\n * Asset exchange rate values for a given chain and address\n */\nexport type ExchangeRate = { exchangeRate?: string; usdExchangeRate?: string };\n\n/**\n * Values derived from the quote response\n */\nexport type QuoteMetadata = {\n /**\n * If gas is included, this is the value of the src or dest token that was used to pay for the gas.\n * Show this value to indicate transaction fees for gasless quotes.\n */\n includedTxFees?: TokenAmountValues | null;\n /**\n * The gas fee for the bridge transaction.\n * effective is the gas fee that is shown to the user. If this value is not\n * included in the trade, the calculation falls back to the gasLimit (total)\n * total is the gas fee that is spent by the user, including refunds.\n * max is the max gas fee that will be used by the transaction.\n */\n gasFee: Record<'effective' | 'total' | 'max', TokenAmountValues>;\n /**\n * The total network fee required to submit the trade and any approvals. This includes\n * the relayer fee or other native fees. Should be used for balance checks and tx submission.\n * Note: This is only accurate for non-gasless transactions. Use {@link QuoteMetadata.includedTxFees} to\n * get the total network fee for gasless transactions.\n */\n totalNetworkFee: TokenAmountValues; // estimatedGasFees + relayerFees\n totalMaxNetworkFee: TokenAmountValues; // maxGasFees + relayerFees\n /**\n * The amount that the user will receive (destTokenAmount)\n */\n toTokenAmount: TokenAmountValues;\n /**\n * The minimum amount that the user will receive (minDestTokenAmount)\n */\n minToTokenAmount: TokenAmountValues;\n /**\n * If gas is included: {@link QuoteMetadata.toTokenAmount} - {@link QuoteMetadata.includedTxFees}.\n * Otherwise: {@link QuoteMetadata.toTokenAmount} - {@link QuoteMetadata.totalNetworkFee}.\n */\n adjustedReturn: Omit<TokenAmountValues, 'amount'>;\n /**\n * The amount that the user will send, including fees that are paid in the src token\n * {@link Quote.srcTokenAmount} + {@link Quote.feeData[FeeType.METABRIDGE].amount} + {@link Quote.feeData[FeeType.TX_FEE].amount}\n */\n sentAmount: TokenAmountValues;\n /**\n * The swap rate is the amount that the user will receive per amount sent. Accounts for fees paid in the src or dest token.\n * This is calculated as {@link QuoteMetadata.toTokenAmount} / {@link QuoteMetadata.sentAmount}.\n */\n swapRate: string;\n /**\n * The cost of the trade, which is the difference between the amount sent and the adjusted return.\n * This is calculated as {@link QuoteMetadata.sentAmount} - {@link QuoteMetadata.adjustedReturn}.\n */\n cost: Omit<TokenAmountValues, 'amount'>; // sentAmount - adjustedReturn\n};\n\n/**\n * Sort order set by the user\n */\nexport enum SortOrder {\n COST_ASC = 'cost_ascending',\n ETA_ASC = 'time_descending',\n}\n\n/**\n * This is the interface for the asset object returned by the bridge-api\n * This type is used in the QuoteResponse and in the fetchBridgeTokens response\n */\nexport type BridgeAsset = Infer<typeof BridgeAssetSchema>;\n\n/**\n * This is the interface for the token object used in the extension client\n * In addition to the {@link BridgeAsset} fields, it includes balance information\n */\nexport type BridgeToken = {\n address: string;\n symbol: string;\n image: string;\n decimals: number;\n chainId: number | Hex | ChainId | CaipChainId;\n balance: string; // raw balance\n // TODO deprecate this field and use balance instead\n string: string | undefined; // normalized balance as a stringified number\n tokenFiatAmount?: number | null;\n occurrences?: number;\n};\n\ntype DecimalChainId = string;\nexport type GasMultiplierByChainId = Record<DecimalChainId, number>;\n\nexport type FeatureFlagResponse = Infer<typeof PlatformConfigSchema>;\n\n// TODO move definition to validators.ts\n/**\n * This is the interface for the quote request sent to the bridge-api\n * and should only be used by the fetchBridgeQuotes utility function\n * Components and redux stores should use the {@link GenericQuoteRequest} type\n */\nexport type QuoteRequest<\n ChainIdType = ChainId | number,\n TokenAddressType = string,\n WalletAddressType = string,\n> = {\n walletAddress: WalletAddressType;\n destWalletAddress?: WalletAddressType;\n srcChainId: ChainIdType;\n destChainId: ChainIdType;\n srcTokenAddress: TokenAddressType;\n destTokenAddress: TokenAddressType;\n /**\n * This is the amount sent, in atomic amount\n */\n srcTokenAmount: string;\n slippage?: number;\n aggIds?: string[];\n bridgeIds?: string[];\n insufficientBal?: boolean;\n resetApproval?: boolean;\n refuel?: boolean;\n /**\n * Whether the response should include gasless swap quotes\n * This should be true if the user has opted in to STX on the client\n * and the current network has STX support\n */\n gasIncluded: boolean;\n /**\n * Whether to request quotes that use EIP-7702 delegated gasless execution\n */\n gasIncluded7702: boolean;\n /**\n * The fee that will be charged by MetaMask\n */\n fee?: number;\n};\n\nexport enum StatusTypes {\n SUBMITTED = 'SUBMITTED',\n UNKNOWN = 'UNKNOWN',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n COMPLETE = 'COMPLETE',\n}\n\n/**\n * These are types that components pass in. Since data is a mix of types when coming from the redux store, we need to use a generic type that can cover all the types.\n * Payloads with this type are transformed into QuoteRequest by fetchBridgeQuotes right before fetching quotes\n */\nexport type GenericQuoteRequest = QuoteRequest<\n Hex | CaipChainId | string | number, // chainIds\n Hex | CaipAssetId | string, // assetIds/addresses\n Hex | CaipAccountId | string // accountIds/addresses\n>;\n\nexport type Protocol = Infer<typeof ProtocolSchema>;\n\nexport type Step = Infer<typeof StepSchema>;\n\nexport type RefuelData = Step;\n\nexport type FeeData = Infer<typeof FeeDataSchema>;\n\nexport type Quote = Infer<typeof QuoteSchema>;\n\nexport type TxData = Infer<typeof TxDataSchema>;\n\nexport type Intent = Infer<typeof IntentSchema>;\nexport type IntentOrderLike = Intent['order'];\n\nexport type BitcoinTradeData = Infer<typeof BitcoinTradeDataSchema>;\n\nexport type TronTradeData = Infer<typeof TronTradeDataSchema>;\n/**\n * This is the type for the quote response from the bridge-api\n * TxDataType can be overriden to be a string when the quote is non-evm\n * ApprovalType can be overriden when you know the specific approval type (e.g., TxData for EVM-only contexts)\n */\nexport type QuoteResponse<\n TxDataType = TxData | string | BitcoinTradeData | TronTradeData,\n ApprovalType = TxData | TronTradeData,\n> = Infer<typeof QuoteResponseSchema> & {\n trade: TxDataType;\n approval?: ApprovalType;\n /**\n * Appended to the quote response based on the quote request\n */\n featureId?: FeatureId;\n /**\n * Appended to the quote response based on the quote request resetApproval flag\n * If defined, the quote's total network fee will include the reset approval's gas limit.\n */\n resetApproval?: TxData;\n /**\n * Appended to the quote if there are multiple quote requests in a batch. This\n * indicates which quoteRequest the quote is for\n */\n quoteRequestIndex?: number;\n};\n\nexport type BatchSellTradesRequest = {\n quotes: QuoteResponse[];\n stxEnabled: boolean;\n};\n\n/**\n * This is the bridge-api response for the obtainGaslessBatch method\n */\nexport type BatchSellTradesResponse = Infer<\n typeof BatchSellTradesResponseSchema\n>;\n\nexport type SimulatedGasFeeLimits = Infer<typeof SimulatedGasFeeLimitsSchema>;\nexport type TxFeeGasLimits = Infer<typeof TxFeeGasLimitsSchema>;\n\nexport type GaslessProperties = Infer<typeof GaslessPropertiesSchema>;\n\nexport enum ChainId {\n ETH = 1,\n OPTIMISM = 10,\n BSC = 56,\n POLYGON = 137,\n ZKSYNC = 324,\n BASE = 8453,\n ARBITRUM = 42161,\n AVALANCHE = 43114,\n LINEA = 59144,\n SOLANA = 1151111081099710,\n BTC = 20000000000001,\n TRON = 728126428,\n SEI = 1329,\n MONAD = 143,\n HYPEREVM = 999,\n MEGAETH = 4326,\n}\n\nexport type FeatureFlagsPlatformConfig = Infer<typeof PlatformConfigSchema>;\n\nexport type TokenFeature = Infer<typeof TokenFeatureSchema>;\n\nexport type QuoteStreamCompleteData = Infer<typeof QuoteStreamCompleteSchema>;\n\nexport enum RequestStatus {\n LOADING = 0,\n FETCHED = 1,\n ERROR = 2,\n}\n\nexport type BridgeControllerState = {\n quoteRequest: Partial<GenericQuoteRequest>[];\n quotes: (QuoteResponse & L1GasFees & NonEvmFees)[];\n /**\n * The time elapsed between the initial quote fetch and when the first valid quote was received\n */\n quotesInitialLoadTime: number | null;\n /**\n * The timestamp of when the latest quote fetch started\n */\n quotesLastFetched: number | null;\n /**\n * The status of the quote fetch, including fee calculations and validations\n * This is set to\n * - LOADING when the quote fetch starts\n * - FETCHED when the process completes successfully, including when quotes are empty\n * - ERROR when any errors occur\n *\n * When SSE is enabled, this is set to LOADING even when a quote is available. It is only\n * set to FETCHED when the stream is closed and all quotes have been received\n */\n quotesLoadingStatus: RequestStatus | null;\n quoteFetchError: string | null;\n /**\n * The number of times the quotes have been refreshed, starts at 0 and is\n * incremented at the end of each quote fetch\n */\n quotesRefreshCount: number;\n /**\n * Asset exchange rates for EVM and multichain assets that are not indexed by the assets controllers\n */\n assetExchangeRates: Record<CaipAssetType, ExchangeRate>;\n /**\n * When the src token is SOL, this needs to be subtracted from their balance to determine\n * the max amount that can be sent.\n */\n minimumBalanceForRentExemptionInLamports: string | null;\n /**\n * Security alerts for the destination token in the current quote request,\n * populated from `token_warning` SSE events.\n */\n tokenWarnings: TokenFeature[];\n /**\n * Client-supplied security classification for the destination token in the\n * current quote request, used as the `token_security_type_destination`\n * analytics property. Set via the `context` arg of\n * `updateBridgeQuoteRequestParams` and reset whenever the quote request is\n * reset. `null` when the client has no security data for the token.\n */\n tokenSecurityTypeDestination: string | null;\n /**\n * Metadata about the completed quote stream, populated from the `complete` SSE event.\n * Set to null at the start of each fetch and updated when the complete event is received.\n */\n quoteStreamComplete: QuoteStreamCompleteData | null;\n /**\n * Contains gasless transaction data and fees for BatchSell quotes, provided by the obtainGaslessBatch API\n */\n batchSellTrades: BatchSellTradesResponse | null;\n /**\n * The status of the batch sell trades fetch, including fee calculations and validations\n */\n batchSellTradesLoadingStatus: RequestStatus | null;\n};\n\n/**\n * @deprecated Use the separate method action types (e.g.,\n * `BridgeControllerFetchQuotesAction`) instead.\n */\nexport type BridgeControllerAction<\n FunctionName extends keyof BridgeController,\n> = {\n type: `${typeof BRIDGE_CONTROLLER_NAME}:${FunctionName}`;\n handler: BridgeController[FunctionName];\n};\n\nexport type BridgeControllerGetStateAction = ControllerGetStateAction<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState\n>;\n\nexport type BridgeControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState\n>;\n\nexport type BridgeControllerActions =\n | BridgeControllerGetStateAction\n | BridgeControllerMethodActions;\n\nexport type BridgeControllerEvents = BridgeControllerStateChangeEvent;\n\nexport type AllowedActions =\n | AccountsControllerGetAccountByAddressAction\n | AuthenticationControllerGetBearerTokenAction\n | CurrencyRateControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | MultichainAssetsRatesControllerGetStateAction\n | SnapControllerHandleRequestAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | RemoteFeatureFlagControllerGetStateAction\n | AssetsControllerGetExchangeRatesForBridgeAction;\nexport type AllowedEvents = never;\n\n/**\n * The messenger for the BridgeController.\n */\nexport type BridgeControllerMessenger = Messenger<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerActions | AllowedActions,\n BridgeControllerEvents | AllowedEvents\n>;\n"]}
|
|
1
|
+
{"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA4DA;;GAEG;AACH,MAAM,CAAN,IAAY,SAYX;AAZD,WAAY,SAAS;IACnB,4DAA4D;IAC5D,8BAAiB,CAAA;IACjB,qBAAqB;IACrB,4BAAe,CAAA;IACf,kCAAkC;IAClC,wBAAW,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-disable @typescript-eslint/naming-convention */\nimport type { AccountsControllerGetAccountByAddressAction } from '@metamask/accounts-controller';\nimport type { AssetsControllerGetExchangeRatesForBridgeAction } from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n MultichainAssetsRatesControllerGetStateAction,\n TokenRatesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n NetworkControllerFindNetworkClientIdByChainIdAction,\n NetworkControllerGetNetworkClientByIdAction,\n} from '@metamask/network-controller';\nimport type { AuthenticationControllerGetBearerTokenAction } from '@metamask/profile-sync-controller/auth';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SnapControllerHandleRequestAction } from '@metamask/snaps-controllers';\nimport type { Infer } from '@metamask/superstruct';\nimport type {\n CaipAccountId,\n CaipAssetId,\n CaipAssetType,\n CaipChainId,\n Hex,\n} from '@metamask/utils';\n\nimport type { BridgeController } from './bridge-controller';\nimport type { BridgeControllerMethodActions } from './bridge-controller-method-action-types';\nimport type { BRIDGE_CONTROLLER_NAME } from './constants/bridge';\nimport type {\n BitcoinTradeDataSchema,\n BridgeAssetSchema,\n ChainConfigurationSchema,\n ChainRankingSchema,\n FeeDataSchema,\n IntentSchema,\n PlatformConfigSchema,\n ProtocolSchema,\n QuoteResponseSchema,\n QuoteSchema,\n StepSchema,\n TokenFeatureSchema,\n QuoteStreamCompleteSchema,\n TronTradeDataSchema,\n TxDataSchema,\n BatchSellTradesResponseSchema,\n GaslessPropertiesSchema,\n SimulatedGasFeeLimitsSchema,\n TxFeeGasLimitsSchema,\n} from './utils/validators';\n\nexport type FetchFunction = (\n input: RequestInfo | URL | string,\n init?: RequestInit,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => Promise<any>;\n\n/**\n * The types of assets that a user can send\n */\nexport enum AssetType {\n /** The native asset for the current network, such as ETH */\n native = 'NATIVE',\n /** An ERC20 token */\n token = 'TOKEN',\n /** An ERC721 or ERC1155 token. */\n NFT = 'NFT',\n /**\n * A transaction interacting with a contract that isn't a token method\n * interaction will be marked as dealing with an unknown asset type.\n */\n unknown = 'UNKNOWN',\n}\n\nexport type ChainConfiguration = Infer<typeof ChainConfigurationSchema>;\n\nexport type ChainRanking = Infer<typeof ChainRankingSchema>;\n\nexport type L1GasFees = {\n l1GasFeesInHexWei?: string; // l1 fees for approval and trade in hex wei, appended by BridgeController.#appendL1GasFees\n};\n\nexport type NonEvmFees = {\n nonEvmFeesInNative?: string; // Non-EVM chain fees in native units (SOL for Solana, BTC for Bitcoin)\n};\n\n/**\n * The types of values for the token amount and its values when converted to the user's selected currency and USD\n */\nexport type TokenAmountValues = {\n /**\n * The amount of the token\n *\n * @example \"1.005\"\n */\n amount: string;\n /**\n * The amount of the token in the user's selected currency\n *\n * @example \"4.55\"\n */\n valueInCurrency: string | null;\n /**\n * The amount of the token in USD\n *\n * @example \"1.234\"\n */\n usd: string | null;\n};\n\n/**\n * Asset exchange rate values for a given chain and address\n */\nexport type ExchangeRate = { exchangeRate?: string; usdExchangeRate?: string };\n\n/**\n * Values derived from the quote response\n */\nexport type QuoteMetadata = {\n /**\n * If gas is included, this is the value of the src or dest token that was used to pay for the gas.\n * Show this value to indicate transaction fees for gasless quotes.\n */\n includedTxFees?: TokenAmountValues | null;\n /**\n * The gas fee for the bridge transaction.\n * effective is the gas fee that is shown to the user. If this value is not\n * included in the trade, the calculation falls back to the gasLimit (total)\n * total is the gas fee that is spent by the user, including refunds.\n * max is the max gas fee that will be used by the transaction.\n */\n gasFee: Record<'effective' | 'total' | 'max', TokenAmountValues>;\n /**\n * The total network fee required to submit the trade and any approvals. This includes\n * the relayer fee or other native fees. Should be used for balance checks and tx submission.\n * Note: This is only accurate for non-gasless transactions. Use {@link QuoteMetadata.includedTxFees} to\n * get the total network fee for gasless transactions.\n */\n totalNetworkFee: TokenAmountValues; // estimatedGasFees + relayerFees\n totalMaxNetworkFee: TokenAmountValues; // maxGasFees + relayerFees\n /**\n * The amount that the user will receive (destTokenAmount)\n */\n toTokenAmount: TokenAmountValues;\n /**\n * The minimum amount that the user will receive (minDestTokenAmount)\n */\n minToTokenAmount: TokenAmountValues;\n /**\n * If gas is included: {@link QuoteMetadata.toTokenAmount} - {@link QuoteMetadata.includedTxFees}.\n * Otherwise: {@link QuoteMetadata.toTokenAmount} - {@link QuoteMetadata.totalNetworkFee}.\n */\n adjustedReturn: Omit<TokenAmountValues, 'amount'>;\n /**\n * The amount that the user will send, including fees that are paid in the src token\n * {@link Quote.srcTokenAmount} + {@link Quote.feeData[FeeType.METABRIDGE].amount} + {@link Quote.feeData[FeeType.TX_FEE].amount}\n */\n sentAmount: TokenAmountValues;\n /**\n * The swap rate is the amount that the user will receive per amount sent. Accounts for fees paid in the src or dest token.\n * This is calculated as {@link QuoteMetadata.toTokenAmount} / {@link QuoteMetadata.sentAmount}.\n */\n swapRate: string;\n /**\n * The cost of the trade, which is the difference between the amount sent and the adjusted return.\n * This is calculated as {@link QuoteMetadata.sentAmount} - {@link QuoteMetadata.adjustedReturn}.\n */\n cost: Omit<TokenAmountValues, 'amount'>; // sentAmount - adjustedReturn\n};\n\n/**\n * Sort order set by the user\n */\nexport enum SortOrder {\n COST_ASC = 'cost_ascending',\n ETA_ASC = 'time_descending',\n}\n\n/**\n * This is the interface for the asset object returned by the bridge-api\n * This type is used in the QuoteResponse and in the fetchBridgeTokens response\n */\nexport type BridgeAsset = Infer<typeof BridgeAssetSchema>;\n\n/**\n * This is the interface for the token object used in the extension client\n * In addition to the {@link BridgeAsset} fields, it includes balance information\n */\nexport type BridgeToken = {\n address: string;\n symbol: string;\n image: string;\n decimals: number;\n chainId: number | Hex | ChainId | CaipChainId;\n balance: string; // raw balance\n // TODO deprecate this field and use balance instead\n string: string | undefined; // normalized balance as a stringified number\n tokenFiatAmount?: number | null;\n occurrences?: number;\n};\n\ntype DecimalChainId = string;\nexport type GasMultiplierByChainId = Record<DecimalChainId, number>;\n\nexport type FeatureFlagResponse = Infer<typeof PlatformConfigSchema>;\n\n// TODO move definition to validators.ts\n/**\n * This is the interface for the quote request sent to the bridge-api\n * and should only be used by the fetchBridgeQuotes utility function\n * Components and redux stores should use the {@link GenericQuoteRequest} type\n */\nexport type QuoteRequest<\n ChainIdType = ChainId | number,\n TokenAddressType = string,\n WalletAddressType = string,\n> = {\n walletAddress: WalletAddressType;\n destWalletAddress?: WalletAddressType;\n srcChainId: ChainIdType;\n destChainId: ChainIdType;\n srcTokenAddress: TokenAddressType;\n destTokenAddress: TokenAddressType;\n /**\n * This is the amount sent, in atomic amount\n */\n srcTokenAmount: string;\n slippage?: number;\n aggIds?: string[];\n bridgeIds?: string[];\n insufficientBal?: boolean;\n resetApproval?: boolean;\n refuel?: boolean;\n /**\n * Whether the response should include gasless swap quotes\n * This should be true if the user has opted in to STX on the client\n * and the current network has STX support\n */\n gasIncluded: boolean;\n /**\n * Whether to request quotes that use EIP-7702 delegated gasless execution\n */\n gasIncluded7702: boolean;\n /**\n * The fee that will be charged by MetaMask\n */\n fee?: number;\n};\n\nexport enum StatusTypes {\n SUBMITTED = 'SUBMITTED',\n UNKNOWN = 'UNKNOWN',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n COMPLETE = 'COMPLETE',\n}\n\nexport enum FeatureId {\n UNKNOWN = 'unknown',\n PERPS = 'perps',\n QUICK_BUY_FOLLOW_TRADING = 'quick_buy_follow_trading',\n QUICK_BUY_TOKEN_DETAILS = 'quick_buy_token_details',\n DAPP_SWAP = 'dapp_swap',\n BATCH_SELL = 'batch_sell',\n UNIFIED_SWAP_BRIDGE = 'unified_swap_bridge',\n}\n\n/**\n * These are types that components pass in. Since data is a mix of types when coming from the redux store, we need to use a generic type that can cover all the types.\n * Payloads with this type are transformed into QuoteRequest by fetchBridgeQuotes right before fetching quotes\n */\nexport type GenericQuoteRequest = QuoteRequest<\n Hex | CaipChainId | string | number, // chainIds\n Hex | CaipAssetId | string, // assetIds/addresses\n Hex | CaipAccountId | string // accountIds/addresses\n>;\n\nexport type Protocol = Infer<typeof ProtocolSchema>;\n\nexport type Step = Infer<typeof StepSchema>;\n\nexport type RefuelData = Step;\n\nexport type FeeData = Infer<typeof FeeDataSchema>;\n\nexport type Quote = Infer<typeof QuoteSchema>;\n\nexport type TxData = Infer<typeof TxDataSchema>;\n\nexport type Intent = Infer<typeof IntentSchema>;\nexport type IntentOrderLike = Intent['order'];\n\nexport type BitcoinTradeData = Infer<typeof BitcoinTradeDataSchema>;\n\nexport type TronTradeData = Infer<typeof TronTradeDataSchema>;\n/**\n * This is the type for the quote response from the bridge-api\n * TxDataType can be overriden to be a string when the quote is non-evm\n * ApprovalType can be overriden when you know the specific approval type (e.g., TxData for EVM-only contexts)\n */\nexport type QuoteResponse<\n TxDataType = TxData | string | BitcoinTradeData | TronTradeData,\n ApprovalType = TxData | TronTradeData,\n> = Infer<typeof QuoteResponseSchema> & {\n trade: TxDataType;\n approval?: ApprovalType;\n /**\n * Appended to the quote response based on the quote request\n */\n featureId?: FeatureId;\n /**\n * Appended to the quote response based on the quote request resetApproval flag\n * If defined, the quote's total network fee will include the reset approval's gas limit.\n */\n resetApproval?: TxData;\n /**\n * Appended to the quote if there are multiple quote requests in a batch. This\n * indicates which quoteRequest the quote is for\n */\n quoteRequestIndex?: number;\n};\n\nexport type BatchSellTradesRequest = {\n quotes: QuoteResponse[];\n stxEnabled: boolean;\n};\n\n/**\n * This is the bridge-api response for the obtainGaslessBatch method\n */\nexport type BatchSellTradesResponse = Infer<\n typeof BatchSellTradesResponseSchema\n>;\n\nexport type SimulatedGasFeeLimits = Infer<typeof SimulatedGasFeeLimitsSchema>;\nexport type TxFeeGasLimits = Infer<typeof TxFeeGasLimitsSchema>;\n\nexport type GaslessProperties = Infer<typeof GaslessPropertiesSchema>;\n\nexport enum ChainId {\n ETH = 1,\n OPTIMISM = 10,\n BSC = 56,\n POLYGON = 137,\n ZKSYNC = 324,\n BASE = 8453,\n ARBITRUM = 42161,\n AVALANCHE = 43114,\n LINEA = 59144,\n SOLANA = 1151111081099710,\n BTC = 20000000000001,\n TRON = 728126428,\n SEI = 1329,\n MONAD = 143,\n HYPEREVM = 999,\n MEGAETH = 4326,\n ARC = 5042,\n}\n\nexport type FeatureFlagsPlatformConfig = Infer<typeof PlatformConfigSchema>;\n\nexport type TokenFeature = Infer<typeof TokenFeatureSchema>;\n\nexport type QuoteStreamCompleteData = Infer<typeof QuoteStreamCompleteSchema>;\n\nexport enum RequestStatus {\n LOADING = 0,\n FETCHED = 1,\n ERROR = 2,\n}\n\nexport type BridgeControllerState = {\n quoteRequest: Partial<GenericQuoteRequest>[];\n quotes: (QuoteResponse & L1GasFees & NonEvmFees)[];\n /**\n * The time elapsed between the initial quote fetch and when the first valid quote was received\n */\n quotesInitialLoadTime: number | null;\n /**\n * The timestamp of when the latest quote fetch started\n */\n quotesLastFetched: number | null;\n /**\n * The status of the quote fetch, including fee calculations and validations\n * This is set to\n * - LOADING when the quote fetch starts\n * - FETCHED when the process completes successfully, including when quotes are empty\n * - ERROR when any errors occur\n *\n * When SSE is enabled, this is set to LOADING even when a quote is available. It is only\n * set to FETCHED when the stream is closed and all quotes have been received\n */\n quotesLoadingStatus: RequestStatus | null;\n quoteFetchError: string | null;\n /**\n * The number of times the quotes have been refreshed, starts at 0 and is\n * incremented at the end of each quote fetch\n */\n quotesRefreshCount: number;\n /**\n * Asset exchange rates for EVM and multichain assets that are not indexed by the assets controllers\n */\n assetExchangeRates: Record<CaipAssetType, ExchangeRate>;\n /**\n * When the src token is SOL, this needs to be subtracted from their balance to determine\n * the max amount that can be sent.\n */\n minimumBalanceForRentExemptionInLamports: string | null;\n /**\n * Security alerts for the destination token in the current quote request,\n * populated from `token_warning` SSE events.\n */\n tokenWarnings: TokenFeature[];\n /**\n * Client-supplied security classification for the destination token in the\n * current quote request, used as the `token_security_type_destination`\n * analytics property. Set via the `context` arg of\n * `updateBridgeQuoteRequestParams` and reset whenever the quote request is\n * reset. `null` when the client has no security data for the token.\n */\n tokenSecurityTypeDestination: string | null;\n /**\n * Metadata about the completed quote stream, populated from the `complete` SSE event.\n * Set to null at the start of each fetch and updated when the complete event is received.\n */\n quoteStreamComplete: QuoteStreamCompleteData | null;\n /**\n * Contains gasless transaction data and fees for BatchSell quotes, provided by the obtainGaslessBatch API\n */\n batchSellTrades: BatchSellTradesResponse | null;\n /**\n * The status of the batch sell trades fetch, including fee calculations and validations\n */\n batchSellTradesLoadingStatus: RequestStatus | null;\n};\n\n/**\n * @deprecated Use the separate method action types (e.g.,\n * `BridgeControllerFetchQuotesAction`) instead.\n */\nexport type BridgeControllerAction<\n FunctionName extends keyof BridgeController,\n> = {\n type: `${typeof BRIDGE_CONTROLLER_NAME}:${FunctionName}`;\n handler: BridgeController[FunctionName];\n};\n\nexport type BridgeControllerGetStateAction = ControllerGetStateAction<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState\n>;\n\nexport type BridgeControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState\n>;\n\nexport type BridgeControllerActions =\n | BridgeControllerGetStateAction\n | BridgeControllerMethodActions;\n\nexport type BridgeControllerEvents = BridgeControllerStateChangeEvent;\n\nexport type AllowedActions =\n | AccountsControllerGetAccountByAddressAction\n | AuthenticationControllerGetBearerTokenAction\n | CurrencyRateControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | MultichainAssetsRatesControllerGetStateAction\n | SnapControllerHandleRequestAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | RemoteFeatureFlagControllerGetStateAction\n | AssetsControllerGetExchangeRatesForBridgeAction;\nexport type AllowedEvents = never;\n\n/**\n * The messenger for the BridgeController.\n */\nexport type BridgeControllerMessenger = Messenger<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerActions | AllowedActions,\n BridgeControllerEvents | AllowedEvents\n>;\n"]}
|
|
@@ -12,7 +12,7 @@ export declare const formatFeatureFlags: (bridgeFeatureFlags: FeatureFlagsPlatfo
|
|
|
12
12
|
warning?: number | undefined;
|
|
13
13
|
error?: number | undefined;
|
|
14
14
|
} | undefined;
|
|
15
|
-
quoteRequestOverrides?: Record<
|
|
15
|
+
quoteRequestOverrides?: Record<string, {
|
|
16
16
|
aggIds?: string[] | undefined;
|
|
17
17
|
bridgeIds?: string[] | undefined;
|
|
18
18
|
fee?: number | undefined;
|
|
@@ -12,7 +12,7 @@ export declare const formatFeatureFlags: (bridgeFeatureFlags: FeatureFlagsPlatfo
|
|
|
12
12
|
warning?: number | undefined;
|
|
13
13
|
error?: number | undefined;
|
|
14
14
|
} | undefined;
|
|
15
|
-
quoteRequestOverrides?: Record<
|
|
15
|
+
quoteRequestOverrides?: Record<string, {
|
|
16
16
|
aggIds?: string[] | undefined;
|
|
17
17
|
bridgeIds?: string[] | undefined;
|
|
18
18
|
fee?: number | undefined;
|
package/dist/utils/fetch.cjs
CHANGED
|
@@ -224,6 +224,7 @@ const getQuoteResponseId = ({ srcAsset: { address: srcTokenAddress, chainId: src
|
|
|
224
224
|
* @param fetchFn - The fetch function to use
|
|
225
225
|
* @param quoteRequests - An array of GenericQuoteRequest objects
|
|
226
226
|
* @param signal - The abort signal
|
|
227
|
+
* @param featureId - The {@link FeatureId} for the experience that's requesting the quotes
|
|
227
228
|
* @param clientId - The client ID for metrics
|
|
228
229
|
* @param jwt - The JWT token for authentication
|
|
229
230
|
* @param bridgeApiBaseUrl - The base URL for the bridge API
|
|
@@ -236,7 +237,7 @@ const getQuoteResponseId = ({ srcAsset: { address: srcTokenAddress, chainId: src
|
|
|
236
237
|
* @param clientVersion - The client version for metrics (optional)
|
|
237
238
|
* @returns A list of bridge tx quote promises
|
|
238
239
|
*/
|
|
239
|
-
async function fetchBridgeQuoteStream(fetchFn, quoteRequests, signal, clientId, jwt, bridgeApiBaseUrl, serverEventHandlers, clientVersion) {
|
|
240
|
+
async function fetchBridgeQuoteStream(fetchFn, quoteRequests, signal, featureId, clientId, jwt, bridgeApiBaseUrl, serverEventHandlers, clientVersion) {
|
|
240
241
|
/**
|
|
241
242
|
* If the request includes multiple quote requests, it is a batch sell request.
|
|
242
243
|
* A batch sell consists of multiple swaps that are executed in a single tx submission.
|
|
@@ -257,6 +258,7 @@ async function fetchBridgeQuoteStream(fetchFn, quoteRequests, signal, clientId,
|
|
|
257
258
|
const matchingQuoteRequest = normalizedQuoteRequests[matchedQuoteRequestIdx];
|
|
258
259
|
return await serverEventHandlers.onValidQuoteReceived({
|
|
259
260
|
...quoteResponse,
|
|
261
|
+
featureId,
|
|
260
262
|
// Append the reset approval data to the quote response if the request has resetApproval set to true and the quote has an approval
|
|
261
263
|
resetApproval: matchingQuoteRequest.resetApproval &&
|
|
262
264
|
quoteResponse.approval &&
|
package/dist/utils/fetch.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":";;;AAAA,qEAAqE;AACrE,uDAAoD;AAcpD,yCAA+C;AAC/C,2DAI2B;AAC3B,mEAA0D;AAC1D,mDAA4C;AAE5C,iDAMsB;AAEf,MAAM,gBAAgB,GAAG,CAAC,EAC/B,QAAQ,EACR,aAAa,EACb,GAAG,GAKJ,EAAE,EAAE,CAAC,CAAC;IACL,aAAa,EAAE,QAAQ;IACvB,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,UAAU,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAClD,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;CAC9D,CAAC,CAAC;AAZU,QAAA,gBAAgB,oBAY1B;AAEH;;;;;;;;;;;;GAYG;AACI,KAAK,UAAU,iBAAiB,CACrC,OAA0B,EAC1B,QAAgB,EA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A,4CAA+B,EAAC,IAAI,CAAC,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,gCAAgC;QAChC,MAAM,IAAI,KAAK,CAAC,sCAAsC,KAAK,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;IAC7E,CAAC;AACH,CAAC;AA3CD,oDA2CC","sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\n\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n TokenFeature,\n QuoteStreamCompleteData,\n BatchSellTradesRequest,\n BatchSellTradesResponse,\n} from '../types';\nimport { getEthUsdtResetData } from './bridge';\nimport {\n formatAddressToAssetId,\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { fetchServerEvents } from './fetch-server-events';\nimport { isEvmTxData } from './trade-utils';\nimport type { FeatureId } from './validators';\nimport {\n validateQuoteResponse,\n validateSwapsTokenObject,\n validateTokenFeature,\n validateQuoteStreamComplete,\n validateBatchSellTradesResponse,\n} from './validators';\n\nexport const getClientHeaders = ({\n clientId,\n clientVersion,\n jwt,\n}: {\n clientId: string;\n clientVersion?: string;\n jwt?: string;\n}) => ({\n 'X-Client-Id': clientId,\n ...(jwt ? { Authorization: `Bearer ${jwt}` } : {}),\n ...(clientVersion ? { 'Client-Version': clientVersion } : {}),\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @deprecated Use the popular and search bridge-api endpoints instead\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param jwt - The JWT token for authentication\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @param clientVersion - The client version for metrics (optional)\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n jwt: string | undefined,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n clientVersion?: string,\n): Promise<Record<string, BridgeAsset>> {\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientHeaders({ clientId, clientVersion, jwt }),\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to QuoteRequest\n *\n * @param request - The quote request\n * @returns A QuoteRequest object\n */\nconst formatQuoteRequest = (request: GenericQuoteRequest): QuoteRequest => {\n const destWalletAddress = request.destWalletAddress ?? request.walletAddress;\n // Transform the generic quote request into QuoteRequest\n const normalizedRequest: QuoteRequest = {\n walletAddress: formatAddressToCaipReference(request.walletAddress),\n destWalletAddress: formatAddressToCaipReference(destWalletAddress),\n srcChainId: formatChainIdToDec(request.srcChainId),\n destChainId: formatChainIdToDec(request.destChainId),\n srcTokenAddress: formatAddressToCaipReference(request.srcTokenAddress),\n destTokenAddress: formatAddressToCaipReference(request.destTokenAddress),\n srcTokenAmount: request.srcTokenAmount,\n insufficientBal: Boolean(request.insufficientBal),\n resetApproval: Boolean(request.resetApproval),\n gasIncluded: Boolean(request.gasIncluded),\n gasIncluded7702: Boolean(request.gasIncluded7702),\n };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n if (request.fee !== undefined) {\n normalizedRequest.fee = request.fee;\n }\n if (request.aggIds && request.aggIds.length > 0) {\n normalizedRequest.aggIds = request.aggIds;\n }\n if (request.bridgeIds && request.bridgeIds.length > 0) {\n normalizedRequest.bridgeIds = request.bridgeIds;\n }\n\n return normalizedRequest;\n};\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n *\n * @param normalizedRequest - The normalized quote request\n * @returns A URLSearchParams object with the query parameters\n */\nconst formatQueryParams = (\n normalizedRequest: QuoteRequest,\n): URLSearchParams => {\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n return queryParams;\n};\n\n/**\n * Fetches quotes from the bridge-api's getQuote endpoint\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param jwt - The JWT token for authentication\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @param featureId - The feature ID to append to each quote\n * @param clientVersion - The client version for metrics (optional)\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal | null,\n clientId: string,\n jwt: string | undefined,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n featureId: FeatureId | null,\n clientVersion?: string,\n): Promise<{\n quotes: QuoteResponse[];\n validationFailures: string[];\n}> {\n const normalizedRequest = formatQuoteRequest(request);\n const queryParams = formatQueryParams(normalizedRequest);\n\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientHeaders({ clientId, clientVersion, jwt }),\n signal,\n });\n\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n const filteredQuotes = quotes\n .filter((quoteResponse: unknown): quoteResponse is QuoteResponse => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId =\n branch?.[0]?.quote?.bridgeId ??\n branch?.[0]?.quote?.bridges?.[0] ??\n (quoteResponse as QuoteResponse)?.quote?.bridgeId ??\n (quoteResponse as QuoteResponse)?.quote?.bridges?.[0] ??\n 'unknown';\n const pathString = path?.join('.') || 'unknown';\n uniqueValidationFailures.add([aggregatorId, pathString].join('|'));\n });\n }\n return false;\n }\n })\n .map((quote) => ({\n ...quote,\n featureId: featureId ?? undefined,\n // Append the reset approval data to the quote response if the request\n // has resetApproval set to true and the quote has an approval\n resetApproval:\n request.resetApproval && quote.approval && isEvmTxData(quote.approval)\n ? {\n ...quote.approval,\n data: getEthUsdtResetData(request.destChainId),\n }\n : undefined,\n }));\n\n const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n }\n\n return {\n quotes: filteredQuotes,\n validationFailures,\n };\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n clientVersion?: string;\n fetchFn: FetchFunction;\n signal?: AbortSignal;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, clientVersion, fetchFn, signal } =\n request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientHeaders({ clientId, clientVersion }),\n signal,\n })) as unknown as Record<CaipAssetType, { [currency: string]: number }>;\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce<\n Record<CaipAssetType, { [currency: string]: string }>\n >((acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n }, {});\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce<\n Record<CaipAssetType, { [currency: string]: string }>\n >((acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n }, {});\n });\n\n return combinedPrices;\n};\n\nconst getQuoteRequestId = ({\n srcChainId,\n destChainId,\n srcTokenAddress,\n destTokenAddress,\n}: QuoteRequest): string =>\n `${formatAddressToAssetId(srcTokenAddress, srcChainId)}-${formatAddressToAssetId(destTokenAddress, destChainId)}`;\n\nconst getQuoteResponseId = ({\n srcAsset: { address: srcTokenAddress, chainId: srcChainId },\n destAsset: { address: destTokenAddress, chainId: destChainId },\n}: QuoteResponse['quote']): string =>\n `${formatAddressToAssetId(srcTokenAddress, srcChainId)}-${formatAddressToAssetId(destTokenAddress, destChainId)}`;\n\n/**\n * Fetches quotes from the bridge-api\n *\n * @param fetchFn - The fetch function to use\n * @param quoteRequests - An array of GenericQuoteRequest objects\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param jwt - The JWT token for authentication\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @param serverEventHandlers - The server event handlers\n * @param serverEventHandlers.onQuoteValidationFailure - The function to handle quote validation failures\n * @param serverEventHandlers.onValidQuoteReceived - The function to handle valid quotes\n * @param serverEventHandlers.onTokenWarning - The function to handle token warning events\n * @param serverEventHandlers.onComplete - The function to handle the complete event emitted when the stream finishes\n * @param serverEventHandlers.onClose - The function to run when the stream is closed and there are no thrown errors\n * @param clientVersion - The client version for metrics (optional)\n * @returns A list of bridge tx quote promises\n */\nexport async function fetchBridgeQuoteStream(\n fetchFn: FetchFunction,\n quoteRequests: GenericQuoteRequest[],\n signal: AbortSignal | undefined,\n clientId: string,\n jwt: string | undefined,\n bridgeApiBaseUrl: string,\n serverEventHandlers: {\n onClose: () => void | Promise<void>;\n onQuoteValidationFailure: (validationFailures: string[]) => void;\n onValidQuoteReceived: (quotes: QuoteResponse) => Promise<void>;\n onTokenWarning: (warning: TokenFeature) => void;\n onComplete: (data: QuoteStreamCompleteData) => void;\n },\n clientVersion?: string,\n): Promise<void> {\n /**\n * If the request includes multiple quote requests, it is a batch sell request.\n * A batch sell consists of multiple swaps that are executed in a single tx submission.\n */\n const isBatchSellRequest = quoteRequests.length > 1;\n const normalizedQuoteRequests = quoteRequests.map(formatQuoteRequest);\n const quoteRequestIds = isBatchSellRequest\n ? normalizedQuoteRequests.map(getQuoteRequestId)\n : undefined;\n\n const onQuoteReceived = async (quoteResponse: unknown): Promise<void> => {\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n\n try {\n if (validateQuoteResponse(quoteResponse)) {\n // Fallback to 0 if the quote doesn't match any requests\n const matchedQuoteRequestIdx = Math.max(\n quoteRequestIds?.findIndex((id) => {\n return id === getQuoteResponseId(quoteResponse.quote);\n }) ?? 0,\n 0,\n );\n const matchingQuoteRequest =\n normalizedQuoteRequests[matchedQuoteRequestIdx];\n\n return await serverEventHandlers.onValidQuoteReceived({\n ...quoteResponse,\n // Append the reset approval data to the quote response if the request has resetApproval set to true and the quote has an approval\n resetApproval:\n matchingQuoteRequest.resetApproval &&\n quoteResponse.approval &&\n isEvmTxData(quoteResponse.approval)\n ? {\n ...quoteResponse.approval,\n data: getEthUsdtResetData(matchingQuoteRequest.destChainId),\n }\n : undefined,\n ...(isBatchSellRequest && {\n quoteRequestIndex: matchedQuoteRequestIdx,\n }),\n });\n }\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId =\n branch?.[0]?.quote?.bridgeId ??\n branch?.[0]?.quote?.bridges?.[0] ??\n (quoteResponse as QuoteResponse)?.quote?.bridgeId ??\n ((quoteResponse as QuoteResponse)?.quote?.bridges?.[0] ||\n ('unknown' as string));\n const pathString = path?.join('.') || 'unknown';\n uniqueValidationFailures.add([aggregatorId, pathString].join('|'));\n });\n }\n const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n return serverEventHandlers.onQuoteValidationFailure(validationFailures);\n }\n // Rethrow any unexpected errors\n throw error;\n }\n return undefined;\n };\n\n const onTokenWarningReceived = (data: unknown): void => {\n try {\n if (validateTokenFeature(data)) {\n serverEventHandlers.onTokenWarning(data);\n }\n } catch (error) {\n console.warn('Token warning validation failed', error);\n }\n };\n\n const onCompleteReceived = (data: unknown): void => {\n try {\n if (validateQuoteStreamComplete(data)) {\n serverEventHandlers.onComplete(data);\n }\n } catch (error) {\n console.warn('Quote stream complete validation failed', error);\n }\n };\n\n const onMessage = async (\n data: Record<string, unknown>,\n eventName?: string,\n ): Promise<void> => {\n switch (eventName) {\n case 'quote':\n return await onQuoteReceived(data);\n case 'token_warning':\n return onTokenWarningReceived(data);\n case 'complete':\n return onCompleteReceived(data);\n default:\n return undefined;\n }\n };\n\n const sharedFetchOptions = {\n signal,\n onMessage,\n onError: (error: unknown) => {\n // Rethrow error to prevent silent fetch failures\n throw error;\n },\n onClose: async () => {\n await serverEventHandlers.onClose();\n },\n fetchFn,\n };\n\n if (isBatchSellRequest) {\n const urlStream = `${bridgeApiBaseUrl}/getBatchQuoteStream`;\n await fetchServerEvents(urlStream, {\n method: 'POST',\n body: JSON.stringify({ requests: normalizedQuoteRequests }),\n headers: {\n ...getClientHeaders({ clientId, clientVersion, jwt }),\n 'Content-Type': 'application/json',\n },\n ...sharedFetchOptions,\n });\n return;\n }\n\n const queryParams = formatQueryParams(normalizedQuoteRequests[0]);\n const urlStream = `${bridgeApiBaseUrl}/getQuoteStream?${queryParams}`;\n await fetchServerEvents(urlStream, {\n headers: {\n ...getClientHeaders({ clientId, clientVersion, jwt }),\n 'Content-Type': 'text/event-stream',\n },\n ...sharedFetchOptions,\n });\n}\n\nexport const formatBatchSellTradesRequest = (\n quotes: (QuoteResponse | null)[],\n stxEnabled: boolean,\n): BatchSellTradesRequest => ({\n quotes: quotes\n .filter((quote): quote is QuoteResponse => quote !== null)\n .map(\n ({\n trade,\n approval,\n quote,\n estimatedProcessingTimeInSeconds,\n quoteId,\n }) => ({\n trade,\n approval,\n quote,\n estimatedProcessingTimeInSeconds,\n quoteId,\n }),\n ),\n stxEnabled,\n});\n\n/**\n * Fetches quotes from the bridge-api's getQuote endpoint\n *\n * @param quotes - The quotes to fetch the gasless transaction data and fees for. May contain null values if a quote is not available for a swap\n * @param stxEnabled - Flag to estimate gas cost more precisely for the batch sell feature.\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param jwt - The JWT token for authentication\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @param clientVersion - The client version for metrics (optional)\n * @returns The batch sell trades and the total network fee\n */\nexport async function fetchBatchSellTrades(\n quotes: (QuoteResponse | null)[],\n stxEnabled: boolean,\n signal: AbortSignal | null,\n clientId: string,\n jwt: string | undefined,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n clientVersion?: string,\n): Promise<BatchSellTradesResponse> {\n const url = `${bridgeApiBaseUrl}/obtainGaslessBatch`;\n const request: BatchSellTradesRequest = formatBatchSellTradesRequest(\n quotes,\n stxEnabled,\n );\n const batchSellTradesResponse = await fetchFn(url, {\n headers: {\n ...getClientHeaders({\n clientId,\n clientVersion,\n jwt,\n }),\n 'Content-Type': 'application/json',\n },\n signal,\n method: 'POST',\n body: JSON.stringify(request),\n });\n\n if (!batchSellTradesResponse.ok) {\n throw new Error(\n `Failed to fetch batch sell trades. ${batchSellTradesResponse.statusText}`,\n );\n }\n\n try {\n const data = await batchSellTradesResponse.json();\n validateBatchSellTradesResponse(data);\n return data;\n } catch (error: unknown) {\n // TODO validation failure event\n throw new Error(`Invalid batch simulation response. ${error?.toString()}`);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":";;;AAAA,qEAAqE;AACrE,uDAAoD;AAepD,yCAA+C;AAC/C,2DAI2B;AAC3B,mEAA0D;AAC1D,mDAA4C;AAC5C,iDAMsB;AAEf,MAAM,gBAAgB,GAAG,CAAC,EAC/B,QAAQ,EACR,aAAa,EACb,GAAG,GAKJ,EAAE,EAAE,CAAC,CAAC;IACL,aAAa,EAAE,QAAQ;IACvB,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,UAAU,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAClD,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;CAC9D,CAAC,CAAC;AAZU,QAAA,gBAAgB,oBAY1B;AAEH;;;;;;;;;;;;GAYG;AACI,KAAK,UAAU,iBAAiB,CACrC,OAA0B,EAC1B,QAAgB,EAChB,GAAuB,EACvB,OAAsB,EACtB,gBAAwB,EACxB,aAAsB;IAEtB,MAAM,GAAG,GAAG,GAAG,gBAAgB,sBAAsB,IAAA,oCAAkB,EAAC,OAAO,CAAC,EAAE,CAAC;IAEnF,uGAAuG;IACvG,uEAAuE;IACvE,6IAA6I;IAC7I,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE;QAChC,OAAO,EAAE,IAAA,wBAAgB,EAAC,EAAE,QAAQ,EAAE,aAAa,EAAE,GAAG,EAAE,CAAC;KAC5D,CAA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ACR,KAAK;QACL,gCAAgC;QAChC,OAAO;KACR,CAAC,CACH;IACH,UAAU;CACX,CAAC,CAAC;AAtBU,QAAA,4BAA4B,gCAsBtC;AAEH;;;;;;;;;;;;GAYG;AACI,KAAK,UAAU,oBAAoB,CACxC,MAAgC,EAChC,UAAmB,EACnB,MAA0B,EAC1B,QAAgB,EAChB,GAAuB,EACvB,OAAsB,EACtB,gBAAwB,EACxB,aAAsB;IAEtB,MAAM,GAAG,GAAG,GAAG,gBAAgB,qBAAqB,CAAC;IACrD,MAAM,OAAO,GAA2B,IAAA,oCAA4B,EAClE,MAAM,EACN,UAAU,CACX,CAAC;IACF,MAAM,uBAAuB,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE;QACjD,OAAO,EAAE;YACP,GAAG,IAAA,wBAAgB,EAAC;gBAClB,QAAQ;gBACR,aAAa;gBACb,GAAG;aACJ,CAAC;YACF,cAAc,EAAE,kBAAkB;SACnC;QACD,MAAM;QACN,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;KAC9B,CAAC,CAAC;IAEH,IAAI,CAAC,uBAAuB,CAAC,EAAE,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CACb,sCAAsC,uBAAuB,CAAC,UAAU,EAAE,CAC3E,CAAC;IACJ,CAAC;IAED,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,uBAAuB,CAAC,IAAI,EAAE,CAAC;QAClD,IAAA,4CAA+B,EAAC,IAAI,CAAC,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,gCAAgC;QAChC,MAAM,IAAI,KAAK,CAAC,sCAAsC,KAAK,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;IAC7E,CAAC;AACH,CAAC;AA3CD,oDA2CC","sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\n\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n TokenFeature,\n QuoteStreamCompleteData,\n BatchSellTradesRequest,\n BatchSellTradesResponse,\n FeatureId,\n} from '../types';\nimport { getEthUsdtResetData } from './bridge';\nimport {\n formatAddressToAssetId,\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { fetchServerEvents } from './fetch-server-events';\nimport { isEvmTxData } from './trade-utils';\nimport {\n validateQuoteResponse,\n validateSwapsTokenObject,\n validateTokenFeature,\n validateQuoteStreamComplete,\n validateBatchSellTradesResponse,\n} from './validators';\n\nexport const getClientHeaders = ({\n clientId,\n clientVersion,\n jwt,\n}: {\n clientId: string;\n clientVersion?: string;\n jwt?: string;\n}) => ({\n 'X-Client-Id': clientId,\n ...(jwt ? { Authorization: `Bearer ${jwt}` } : {}),\n ...(clientVersion ? { 'Client-Version': clientVersion } : {}),\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @deprecated Use the popular and search bridge-api endpoints instead\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param jwt - The JWT token for authentication\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @param clientVersion - The client version for metrics (optional)\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n jwt: string | undefined,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n clientVersion?: string,\n): Promise<Record<string, BridgeAsset>> {\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientHeaders({ clientId, clientVersion, jwt }),\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to QuoteRequest\n *\n * @param request - The quote request\n * @returns A QuoteRequest object\n */\nconst formatQuoteRequest = (request: GenericQuoteRequest): QuoteRequest => {\n const destWalletAddress = request.destWalletAddress ?? request.walletAddress;\n // Transform the generic quote request into QuoteRequest\n const normalizedRequest: QuoteRequest = {\n walletAddress: formatAddressToCaipReference(request.walletAddress),\n destWalletAddress: formatAddressToCaipReference(destWalletAddress),\n srcChainId: formatChainIdToDec(request.srcChainId),\n destChainId: formatChainIdToDec(request.destChainId),\n srcTokenAddress: formatAddressToCaipReference(request.srcTokenAddress),\n destTokenAddress: formatAddressToCaipReference(request.destTokenAddress),\n srcTokenAmount: request.srcTokenAmount,\n insufficientBal: Boolean(request.insufficientBal),\n resetApproval: Boolean(request.resetApproval),\n gasIncluded: Boolean(request.gasIncluded),\n gasIncluded7702: Boolean(request.gasIncluded7702),\n };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n if (request.fee !== undefined) {\n normalizedRequest.fee = request.fee;\n }\n if (request.aggIds && request.aggIds.length > 0) {\n normalizedRequest.aggIds = request.aggIds;\n }\n if (request.bridgeIds && request.bridgeIds.length > 0) {\n normalizedRequest.bridgeIds = request.bridgeIds;\n }\n\n return normalizedRequest;\n};\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n *\n * @param normalizedRequest - The normalized quote request\n * @returns A URLSearchParams object with the query parameters\n */\nconst formatQueryParams = (\n normalizedRequest: QuoteRequest,\n): URLSearchParams => {\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n return queryParams;\n};\n\n/**\n * Fetches quotes from the bridge-api's getQuote endpoint\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param jwt - The JWT token for authentication\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @param featureId - The feature ID to append to each quote\n * @param clientVersion - The client version for metrics (optional)\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal | null,\n clientId: string,\n jwt: string | undefined,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n featureId: FeatureId | null,\n clientVersion?: string,\n): Promise<{\n quotes: QuoteResponse[];\n validationFailures: string[];\n}> {\n const normalizedRequest = formatQuoteRequest(request);\n const queryParams = formatQueryParams(normalizedRequest);\n\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientHeaders({ clientId, clientVersion, jwt }),\n signal,\n });\n\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n const filteredQuotes = quotes\n .filter((quoteResponse: unknown): quoteResponse is QuoteResponse => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId =\n branch?.[0]?.quote?.bridgeId ??\n branch?.[0]?.quote?.bridges?.[0] ??\n (quoteResponse as QuoteResponse)?.quote?.bridgeId ??\n (quoteResponse as QuoteResponse)?.quote?.bridges?.[0] ??\n 'unknown';\n const pathString = path?.join('.') || 'unknown';\n uniqueValidationFailures.add([aggregatorId, pathString].join('|'));\n });\n }\n return false;\n }\n })\n .map((quote) => ({\n ...quote,\n featureId: featureId ?? undefined,\n // Append the reset approval data to the quote response if the request\n // has resetApproval set to true and the quote has an approval\n resetApproval:\n request.resetApproval && quote.approval && isEvmTxData(quote.approval)\n ? {\n ...quote.approval,\n data: getEthUsdtResetData(request.destChainId),\n }\n : undefined,\n }));\n\n const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n }\n\n return {\n quotes: filteredQuotes,\n validationFailures,\n };\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n clientVersion?: string;\n fetchFn: FetchFunction;\n signal?: AbortSignal;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, clientVersion, fetchFn, signal } =\n request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientHeaders({ clientId, clientVersion }),\n signal,\n })) as unknown as Record<CaipAssetType, { [currency: string]: number }>;\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce<\n Record<CaipAssetType, { [currency: string]: string }>\n >((acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n }, {});\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce<\n Record<CaipAssetType, { [currency: string]: string }>\n >((acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n }, {});\n });\n\n return combinedPrices;\n};\n\nconst getQuoteRequestId = ({\n srcChainId,\n destChainId,\n srcTokenAddress,\n destTokenAddress,\n}: QuoteRequest): string =>\n `${formatAddressToAssetId(srcTokenAddress, srcChainId)}-${formatAddressToAssetId(destTokenAddress, destChainId)}`;\n\nconst getQuoteResponseId = ({\n srcAsset: { address: srcTokenAddress, chainId: srcChainId },\n destAsset: { address: destTokenAddress, chainId: destChainId },\n}: QuoteResponse['quote']): string =>\n `${formatAddressToAssetId(srcTokenAddress, srcChainId)}-${formatAddressToAssetId(destTokenAddress, destChainId)}`;\n\n/**\n * Fetches quotes from the bridge-api\n *\n * @param fetchFn - The fetch function to use\n * @param quoteRequests - An array of GenericQuoteRequest objects\n * @param signal - The abort signal\n * @param featureId - The {@link FeatureId} for the experience that's requesting the quotes\n * @param clientId - The client ID for metrics\n * @param jwt - The JWT token for authentication\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @param serverEventHandlers - The server event handlers\n * @param serverEventHandlers.onQuoteValidationFailure - The function to handle quote validation failures\n * @param serverEventHandlers.onValidQuoteReceived - The function to handle valid quotes\n * @param serverEventHandlers.onTokenWarning - The function to handle token warning events\n * @param serverEventHandlers.onComplete - The function to handle the complete event emitted when the stream finishes\n * @param serverEventHandlers.onClose - The function to run when the stream is closed and there are no thrown errors\n * @param clientVersion - The client version for metrics (optional)\n * @returns A list of bridge tx quote promises\n */\nexport async function fetchBridgeQuoteStream(\n fetchFn: FetchFunction,\n quoteRequests: GenericQuoteRequest[],\n signal: AbortSignal | undefined,\n featureId: FeatureId,\n clientId: string,\n jwt: string | undefined,\n bridgeApiBaseUrl: string,\n serverEventHandlers: {\n onClose: () => void | Promise<void>;\n onQuoteValidationFailure: (validationFailures: string[]) => void;\n onValidQuoteReceived: (quotes: QuoteResponse) => Promise<void>;\n onTokenWarning: (warning: TokenFeature) => void;\n onComplete: (data: QuoteStreamCompleteData) => void;\n },\n clientVersion?: string,\n): Promise<void> {\n /**\n * If the request includes multiple quote requests, it is a batch sell request.\n * A batch sell consists of multiple swaps that are executed in a single tx submission.\n */\n const isBatchSellRequest = quoteRequests.length > 1;\n const normalizedQuoteRequests = quoteRequests.map(formatQuoteRequest);\n const quoteRequestIds = isBatchSellRequest\n ? normalizedQuoteRequests.map(getQuoteRequestId)\n : undefined;\n\n const onQuoteReceived = async (quoteResponse: unknown): Promise<void> => {\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n\n try {\n if (validateQuoteResponse(quoteResponse)) {\n // Fallback to 0 if the quote doesn't match any requests\n const matchedQuoteRequestIdx = Math.max(\n quoteRequestIds?.findIndex((id) => {\n return id === getQuoteResponseId(quoteResponse.quote);\n }) ?? 0,\n 0,\n );\n const matchingQuoteRequest =\n normalizedQuoteRequests[matchedQuoteRequestIdx];\n\n return await serverEventHandlers.onValidQuoteReceived({\n ...quoteResponse,\n featureId,\n // Append the reset approval data to the quote response if the request has resetApproval set to true and the quote has an approval\n resetApproval:\n matchingQuoteRequest.resetApproval &&\n quoteResponse.approval &&\n isEvmTxData(quoteResponse.approval)\n ? {\n ...quoteResponse.approval,\n data: getEthUsdtResetData(matchingQuoteRequest.destChainId),\n }\n : undefined,\n ...(isBatchSellRequest && {\n quoteRequestIndex: matchedQuoteRequestIdx,\n }),\n });\n }\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId =\n branch?.[0]?.quote?.bridgeId ??\n branch?.[0]?.quote?.bridges?.[0] ??\n (quoteResponse as QuoteResponse)?.quote?.bridgeId ??\n ((quoteResponse as QuoteResponse)?.quote?.bridges?.[0] ||\n ('unknown' as string));\n const pathString = path?.join('.') || 'unknown';\n uniqueValidationFailures.add([aggregatorId, pathString].join('|'));\n });\n }\n const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n return serverEventHandlers.onQuoteValidationFailure(validationFailures);\n }\n // Rethrow any unexpected errors\n throw error;\n }\n return undefined;\n };\n\n const onTokenWarningReceived = (data: unknown): void => {\n try {\n if (validateTokenFeature(data)) {\n serverEventHandlers.onTokenWarning(data);\n }\n } catch (error) {\n console.warn('Token warning validation failed', error);\n }\n };\n\n const onCompleteReceived = (data: unknown): void => {\n try {\n if (validateQuoteStreamComplete(data)) {\n serverEventHandlers.onComplete(data);\n }\n } catch (error) {\n console.warn('Quote stream complete validation failed', error);\n }\n };\n\n const onMessage = async (\n data: Record<string, unknown>,\n eventName?: string,\n ): Promise<void> => {\n switch (eventName) {\n case 'quote':\n return await onQuoteReceived(data);\n case 'token_warning':\n return onTokenWarningReceived(data);\n case 'complete':\n return onCompleteReceived(data);\n default:\n return undefined;\n }\n };\n\n const sharedFetchOptions = {\n signal,\n onMessage,\n onError: (error: unknown) => {\n // Rethrow error to prevent silent fetch failures\n throw error;\n },\n onClose: async () => {\n await serverEventHandlers.onClose();\n },\n fetchFn,\n };\n\n if (isBatchSellRequest) {\n const urlStream = `${bridgeApiBaseUrl}/getBatchQuoteStream`;\n await fetchServerEvents(urlStream, {\n method: 'POST',\n body: JSON.stringify({ requests: normalizedQuoteRequests }),\n headers: {\n ...getClientHeaders({ clientId, clientVersion, jwt }),\n 'Content-Type': 'application/json',\n },\n ...sharedFetchOptions,\n });\n return;\n }\n\n const queryParams = formatQueryParams(normalizedQuoteRequests[0]);\n const urlStream = `${bridgeApiBaseUrl}/getQuoteStream?${queryParams}`;\n await fetchServerEvents(urlStream, {\n headers: {\n ...getClientHeaders({ clientId, clientVersion, jwt }),\n 'Content-Type': 'text/event-stream',\n },\n ...sharedFetchOptions,\n });\n}\n\nexport const formatBatchSellTradesRequest = (\n quotes: (QuoteResponse | null)[],\n stxEnabled: boolean,\n): BatchSellTradesRequest => ({\n quotes: quotes\n .filter((quote): quote is QuoteResponse => quote !== null)\n .map(\n ({\n trade,\n approval,\n quote,\n estimatedProcessingTimeInSeconds,\n quoteId,\n }) => ({\n trade,\n approval,\n quote,\n estimatedProcessingTimeInSeconds,\n quoteId,\n }),\n ),\n stxEnabled,\n});\n\n/**\n * Fetches quotes from the bridge-api's getQuote endpoint\n *\n * @param quotes - The quotes to fetch the gasless transaction data and fees for. May contain null values if a quote is not available for a swap\n * @param stxEnabled - Flag to estimate gas cost more precisely for the batch sell feature.\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param jwt - The JWT token for authentication\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @param clientVersion - The client version for metrics (optional)\n * @returns The batch sell trades and the total network fee\n */\nexport async function fetchBatchSellTrades(\n quotes: (QuoteResponse | null)[],\n stxEnabled: boolean,\n signal: AbortSignal | null,\n clientId: string,\n jwt: string | undefined,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n clientVersion?: string,\n): Promise<BatchSellTradesResponse> {\n const url = `${bridgeApiBaseUrl}/obtainGaslessBatch`;\n const request: BatchSellTradesRequest = formatBatchSellTradesRequest(\n quotes,\n stxEnabled,\n );\n const batchSellTradesResponse = await fetchFn(url, {\n headers: {\n ...getClientHeaders({\n clientId,\n clientVersion,\n jwt,\n }),\n 'Content-Type': 'application/json',\n },\n signal,\n method: 'POST',\n body: JSON.stringify(request),\n });\n\n if (!batchSellTradesResponse.ok) {\n throw new Error(\n `Failed to fetch batch sell trades. ${batchSellTradesResponse.statusText}`,\n );\n }\n\n try {\n const data = await batchSellTradesResponse.json();\n validateBatchSellTradesResponse(data);\n return data;\n } catch (error: unknown) {\n // TODO validation failure event\n throw new Error(`Invalid batch simulation response. ${error?.toString()}`);\n }\n}\n"]}
|