@metamask-previews/transaction-pay-controller 30.4.3-preview-46de95678 → 30.4.3-preview-6ebaf4e52
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 +6 -0
- package/dist/strategy/across/across-quotes.js +1 -1
- package/dist/strategy/across/across-quotes.js.map +1 -1
- package/dist/types.d.ts +7 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/quote-recipient.d.ts +2 -1
- package/dist/utils/quote-recipient.d.ts.map +1 -1
- package/dist/utils/quote-recipient.js +3 -2
- package/dist/utils/quote-recipient.js.map +1 -1
- package/dist/utils/quotes.d.ts.map +1 -1
- package/dist/utils/quotes.js +26 -5
- package/dist/utils/quotes.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- **BREAKING:** Request and submit post-quote quotes from the transaction's own `from`, so `accountOverride` only receives the output and never signs ([#10992](https://github.com/MetaMask/core/pull/10992))
|
|
13
|
+
- Previously `accountOverride` also sent post-quote quotes, so an account that cannot sign, such as a hardware wallet, could not receive a withdrawal.
|
|
14
|
+
- Clients must keep the post-quote source funds on the transaction's `from`. For example, a Money Account withdrawal that needs a quote must no longer transfer the withdrawn mUSD to `accountOverride` in its nested calls.
|
|
15
|
+
|
|
10
16
|
## [30.4.3]
|
|
11
17
|
|
|
12
18
|
### Changed
|
|
@@ -52,7 +52,7 @@ async function getSingleQuote(request, fullRequest) {
|
|
|
52
52
|
: normalizedRequest.isPostQuote === true;
|
|
53
53
|
const amount = useExactInput ? sourceTokenAmount : targetAmountMinimum;
|
|
54
54
|
const tradeType = useExactInput ? 'exactInput' : 'exactOutput';
|
|
55
|
-
const destination = getAcrossDestinationForRequest(transaction, request, from);
|
|
55
|
+
const destination = getAcrossDestinationForRequest(transaction, request, request.accountOverride ?? from);
|
|
56
56
|
const quote = await requestAcrossApproval({
|
|
57
57
|
actions: destination.actions,
|
|
58
58
|
amount,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"across-quotes.js","sourceRoot":"","sources":["../../../src/strategy/across/across-quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,kCAAkC,CAAC;AAG1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAShD,OAAO,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,EACL,sBAAsB,EACtB,WAAW,GACZ,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAElE,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAExD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,0CAA0C,EAAE,MAAM,yBAAyB,CAAC;AACrF,OAAO,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAC9E,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAS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SACV,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import { successfulFetch, toHex } from '@metamask/controller-utils';\nimport {\n TransactionType,\n hasTransactionType,\n} from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { TransactionPayStrategy } from '../../constants.js';\nimport { projectLogger } from '../../logger.js';\nimport type {\n Amount,\n FiatRates,\n PayStrategyGetQuotesRequest,\n QuoteRequest,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types.js';\nimport { getFiatValueFromUsd, sumAmounts } from '../../utils/amounts.js';\nimport {\n getPayStrategiesConfig,\n getSlippage,\n} from '../../utils/feature-flags.js';\nimport { resolveGasStationCost } from '../../utils/gas-payment.js';\nimport { calculateGasCost } from '../../utils/gas.js';\nimport { estimateQuoteGasLimits } from '../../utils/quote-gas.js';\nimport type { QuoteGasTransaction } from '../../utils/quote-gas.js';\nimport { getTokenFiatRate } from '../../utils/token.js';\nimport type { AcrossDestination } from './across-actions.js';\nimport { getAcrossDestination } from './across-actions.js';\nimport { hasUnsupportedTransactionAuthorizationList } from './authorization-list.js';\nimport { normalizeAcrossRequest, validateAcrossPerpsQuote } from './perps.js';\nimport { isAcrossQuoteRequest } from './requests.js';\nimport {\n getAcrossOrderedTransactions,\n getOriginalTransactionGas,\n} from './transactions.js';\nimport type {\n AcrossAction,\n AcrossActionRequestBody,\n AcrossGasLimits,\n AcrossQuote,\n AcrossSwapApprovalResponse,\n} from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'across-strategy');\n\nconst UNSUPPORTED_AUTHORIZATION_LIST_ERROR =\n 'Across does not support type-4/EIP-7702 authorization lists yet';\n\ntype AcrossQuoteWithoutMetaMask = Omit<AcrossQuote, 'metamask'>;\n\n/**\n * Fetch Across quotes.\n *\n * @param request - Request object.\n * @returns Array of quotes.\n */\nexport async function getAcrossQuotes(\n request: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>[]> {\n const { requests } = request;\n\n log('Fetching quotes', requests);\n\n try {\n const normalizedRequests = requests.filter(isAcrossQuoteRequest);\n\n if (normalizedRequests.length === 0) {\n return [];\n }\n\n if (\n hasUnsupportedTransactionAuthorizationList(\n request.transaction,\n normalizedRequests,\n )\n ) {\n throw new Error(UNSUPPORTED_AUTHORIZATION_LIST_ERROR);\n }\n\n return await Promise.all(\n normalizedRequests.map((singleRequest) =>\n getQuoteWithGasStationHandling(singleRequest, request),\n ),\n );\n } catch (error) {\n log('Error fetching quotes', { error });\n throw new Error(`Failed to fetch Across quotes: ${String(error)}`);\n }\n}\n\nasync function getSingleQuote(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n const { messenger, signal, transaction } = fullRequest;\n const normalizedRequest = normalizeAcrossRequest(request, transaction);\n const {\n from,\n isMaxAmount,\n sourceChainId,\n sourceTokenAddress,\n sourceTokenAmount,\n targetAmountMinimum,\n targetChainId,\n targetTokenAddress,\n } = normalizedRequest;\n\n const config = getPayStrategiesConfig(messenger);\n const slippageDecimal = getSlippage(\n messenger,\n sourceChainId,\n sourceTokenAddress,\n );\n\n const useExactInput = isMaxAmount\n ? true\n : normalizedRequest.isPostQuote === true;\n const amount = useExactInput ? sourceTokenAmount : targetAmountMinimum;\n const tradeType = useExactInput ? 'exactInput' : 'exactOutput';\n const destination = getAcrossDestinationForRequest(\n transaction,\n request,\n from,\n );\n\n const quote = await requestAcrossApproval({\n actions: destination.actions,\n amount,\n apiBase: config.across.apiBase,\n depositor: from,\n destinationChainId: targetChainId,\n inputToken: sourceTokenAddress,\n originChainId: sourceChainId,\n outputToken: targetTokenAddress,\n recipient: destination.recipient,\n signal,\n refundAddress: normalizedRequest.refundTo,\n slippage: slippageDecimal,\n tradeType,\n });\n\n validateAcrossPerpsQuote(normalizedRequest, quote);\n\n const originalQuote: AcrossQuoteWithoutMetaMask = {\n quote,\n request: {\n actions: destination.actions,\n amount,\n tradeType,\n },\n };\n\n return await normalizeQuote(originalQuote, normalizedRequest, fullRequest);\n}\n\nfunction getAcrossDestinationForRequest(\n transaction: TransactionMeta,\n request: QuoteRequest,\n recipient: Hex,\n): AcrossDestination {\n if (request.isPostQuote) {\n return {\n actions: [],\n recipient,\n };\n }\n\n return getAcrossDestination(transaction, request);\n}\n\nasync function getQuoteWithGasStationHandling(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n // Phase 1 uses the requested source amount to discover whether Across will\n // pay source-chain gas with the source token, and what the max gas cost is.\n // Phase 2 repeats the quote with that max gas cost reserved from the source\n // amount, so execution can fund both the Across deposit and token-paid gas.\n const phase1Quote = await getSingleQuote(request, fullRequest);\n\n if (\n (!request.isMaxAmount && !request.isPostQuote) ||\n !phase1Quote.fees.isSourceGasFeeToken\n ) {\n return phase1Quote;\n }\n\n const requiresSourceGasReservation =\n request.isPostQuote === true &&\n hasTransactionType(fullRequest.transaction, [\n TransactionType.predictWithdraw,\n ]);\n\n const adjustedSourceAmount = new BigNumber(request.sourceTokenAmount)\n .minus(phase1Quote.fees.sourceNetwork.max.raw)\n .integerValue(BigNumber.ROUND_DOWN);\n\n if (!adjustedSourceAmount.isGreaterThan(0)) {\n log('Insufficient balance after gas subtraction for Across quote');\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw source amount cannot cover source gas fee token',\n );\n }\n return phase1Quote;\n }\n\n log('Subtracting gas from source for Across quote', {\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n gasCostRaw: phase1Quote.fees.sourceNetwork.max.raw,\n originalSourceAmount: request.sourceTokenAmount,\n });\n\n try {\n const phase2Quote = await getSingleQuote(\n {\n ...request,\n sourceTokenAmount: adjustedSourceAmount.toFixed(\n 0,\n BigNumber.ROUND_DOWN,\n ),\n },\n fullRequest,\n );\n\n if (!phase2Quote.fees.isSourceGasFeeToken) {\n log('Across phase 2 lost gas fee token eligibility');\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw quote lost source gas fee token eligibility',\n );\n }\n return phase1Quote;\n }\n\n const phase2GasCost = new BigNumber(phase2Quote.fees.sourceNetwork.max.raw);\n\n if (\n adjustedSourceAmount\n .plus(phase2GasCost)\n .isGreaterThan(request.sourceTokenAmount)\n ) {\n log('Across phase 2 quote exceeds original source amount', {\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n gasCostRaw: phase2GasCost.toString(10),\n originalSourceAmount: request.sourceTokenAmount,\n });\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw source gas fee token quote exceeds source amount',\n );\n }\n return phase1Quote;\n }\n\n return phase2Quote;\n } catch (error) {\n log(\n requiresSourceGasReservation\n ? 'Across phase 2 quote failed after source gas reservation'\n : 'Across phase 2 quote failed, falling back to phase 1',\n { error },\n );\n if (requiresSourceGasReservation) {\n throw error;\n }\n return phase1Quote;\n }\n}\n\ntype AcrossApprovalRequest = {\n actions: AcrossAction[];\n amount: string;\n apiBase: string;\n depositor: Hex;\n destinationChainId: Hex;\n inputToken: Hex;\n originChainId: Hex;\n outputToken: Hex;\n recipient: Hex;\n refundAddress?: Hex;\n signal?: AbortSignal;\n slippage?: number;\n tradeType: 'exactInput' | 'exactOutput';\n};\n\nasync function requestAcrossApproval(\n request: AcrossApprovalRequest,\n): Promise<AcrossSwapApprovalResponse> {\n const {\n actions,\n amount,\n apiBase,\n depositor,\n destinationChainId,\n inputToken,\n originChainId,\n outputToken,\n recipient,\n refundAddress,\n signal,\n slippage,\n tradeType,\n } = request;\n\n const params = new URLSearchParams();\n params.set('tradeType', tradeType);\n params.set('amount', amount);\n params.set('inputToken', inputToken);\n params.set('outputToken', outputToken);\n params.set('originChainId', String(parseInt(originChainId, 16)));\n params.set('destinationChainId', String(parseInt(destinationChainId, 16)));\n params.set('depositor', depositor);\n params.set('recipient', recipient);\n\n if (refundAddress !== undefined) {\n params.set('refundAddress', refundAddress);\n }\n\n if (slippage !== undefined) {\n params.set('slippage', String(slippage));\n }\n\n const body: AcrossActionRequestBody = { actions };\n const url = `${apiBase}/swap/approval?${params.toString()}`;\n const options: RequestInit = {\n body: JSON.stringify(body),\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n signal,\n };\n\n const response = await successfulFetch(url, options);\n\n return (await response.json()) as AcrossSwapApprovalResponse;\n}\n\nasync function normalizeQuote(\n original: AcrossQuoteWithoutMetaMask,\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n const { messenger } = fullRequest;\n const { quote } = original;\n\n const { usdToFiatRate, sourceFiatRate, targetFiatRate } = getFiatRates(\n messenger,\n quote,\n );\n\n const dustUsd = calculateDustUsd(quote, request, targetFiatRate);\n const dust = getFiatValueFromUsd(dustUsd, usdToFiatRate);\n\n const {\n gasLimits,\n is7702,\n isGasFeeToken: isSourceGasFeeToken,\n requiresAuthorizationList,\n sourceNetwork,\n } = await calculateSourceNetworkCost(\n quote,\n messenger,\n request,\n fullRequest.transaction,\n fullRequest.accountSupports7702,\n );\n\n const targetNetwork = getFiatValueFromUsd(new BigNumber(0), usdToFiatRate);\n\n const inputAmountRaw = quote.inputAmount ?? '0';\n const outputAmountRaw = new BigNumber(\n quote.expectedOutputAmount ??\n quote.minOutputAmount ??\n request.targetAmountMinimum ??\n '0',\n ).toString(10);\n\n const sourceAmount = getAmountFromTokenAmount({\n amountRaw: inputAmountRaw,\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n });\n\n const providerUsd = calculateProviderUsd(\n quote,\n inputAmountRaw,\n sourceFiatRate,\n targetFiatRate,\n quote.expectedOutputAmount,\n );\n const provider = getFiatValueFromUsd(providerUsd, usdToFiatRate);\n const metaMaskFee = getFiatValueFromUsd(\n new BigNumber(quote.fees?.app?.amountUsd ?? '0').abs(),\n usdToFiatRate,\n );\n\n const targetAmount = getAmountFromTokenAmount({\n amountRaw: outputAmountRaw,\n decimals: quote.outputToken.decimals,\n fiatRate: targetFiatRate,\n });\n\n const metamask = {\n gasLimits,\n is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n };\n\n return {\n dust,\n estimatedDuration: quote.expectedFillTime ?? 0,\n fees: {\n isSourceGasFeeToken,\n metaMask: metaMaskFee,\n provider,\n sourceNetwork,\n targetNetwork,\n },\n isInputBased: original.request.tradeType === 'exactInput',\n original: {\n ...original,\n metamask,\n },\n request,\n sourceAmount,\n targetAmount,\n strategy: TransactionPayStrategy.Across,\n };\n}\n\nfunction getFiatRates(\n messenger: TransactionPayControllerMessenger,\n quote: AcrossSwapApprovalResponse,\n): {\n sourceFiatRate: FiatRates;\n targetFiatRate: FiatRates;\n usdToFiatRate: BigNumber;\n} {\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n quote.inputToken.address,\n toHex(quote.inputToken.chainId),\n );\n\n if (!sourceFiatRate) {\n throw new Error('Source token fiat rate not found');\n }\n\n const targetFiatRate =\n getTokenFiatRate(\n messenger,\n quote.outputToken.address,\n toHex(quote.outputToken.chainId),\n ) ?? sourceFiatRate;\n\n const usdToFiatRate = new BigNumber(sourceFiatRate.fiatRate).dividedBy(\n sourceFiatRate.usdRate,\n );\n\n return { sourceFiatRate, targetFiatRate, usdToFiatRate };\n}\n\nfunction calculateDustUsd(\n quote: AcrossSwapApprovalResponse,\n request: QuoteRequest,\n targetFiatRate: FiatRates,\n): BigNumber {\n const expectedOutputRaw = quote.expectedOutputAmount;\n\n if (expectedOutputRaw === undefined) {\n return new BigNumber(0);\n }\n\n const expectedOutput = new BigNumber(expectedOutputRaw);\n const minimumOutput = new BigNumber(\n quote.minOutputAmount ?? request.targetAmountMinimum ?? '0',\n );\n\n const dustRaw = expectedOutput.minus(minimumOutput).isNegative()\n ? new BigNumber(0)\n : expectedOutput.minus(minimumOutput);\n const dustHuman = dustRaw.shiftedBy(-quote.outputToken.decimals);\n\n return dustHuman.multipliedBy(targetFiatRate.usdRate);\n}\n\nfunction calculateProviderUsd(\n quote: AcrossSwapApprovalResponse,\n inputAmountRaw: string,\n sourceFiatRate: FiatRates,\n targetFiatRate: FiatRates,\n expectedOutputRaw?: string,\n): BigNumber {\n const totalFeeUsd = quote.fees?.total?.amountUsd;\n\n if (totalFeeUsd !== undefined) {\n return new BigNumber(totalFeeUsd).abs();\n }\n\n if (expectedOutputRaw === undefined) {\n return new BigNumber(0);\n }\n\n const expectedOutput = new BigNumber(expectedOutputRaw);\n\n if (expectedOutput.lte(0)) {\n return new BigNumber(0);\n }\n\n const inputAmountUsd = new BigNumber(inputAmountRaw)\n .shiftedBy(-quote.inputToken.decimals)\n .multipliedBy(sourceFiatRate.usdRate);\n const expectedOutputUsd = expectedOutput\n .shiftedBy(-quote.outputToken.decimals)\n .multipliedBy(targetFiatRate.usdRate);\n const providerFeeUsd = inputAmountUsd.minus(expectedOutputUsd);\n\n return providerFeeUsd.isNegative() ? new BigNumber(0) : providerFeeUsd;\n}\n\nfunction getAmountFromTokenAmount({\n amountRaw,\n decimals,\n fiatRate,\n}: {\n amountRaw: string;\n decimals: number;\n fiatRate: FiatRates;\n}): Amount {\n const rawValue = new BigNumber(amountRaw);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\n\n const usd = humanValue.multipliedBy(fiatRate.usdRate).toString(10);\n const fiat = humanValue.multipliedBy(fiatRate.fiatRate).toString(10);\n\n return {\n fiat,\n human,\n raw,\n usd,\n };\n}\n\nasync function calculateSourceNetworkCost(\n quote: AcrossSwapApprovalResponse,\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n transaction: TransactionMeta,\n accountSupports7702: boolean,\n): Promise<{\n sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n gasLimits: AcrossGasLimits;\n isGasFeeToken?: boolean;\n is7702: boolean;\n requiresAuthorizationList?: true;\n}> {\n const acrossFallbackGas =\n getPayStrategiesConfig(messenger).across.fallbackGas;\n const { from, sourceChainId, sourceTokenAddress } = request;\n const orderedTransactions = getAcrossOrderedTransactions({ quote });\n const { swapTx } = quote;\n const swapChainId = toHex(swapTx.chainId);\n const isPredictWithdraw =\n request.isPostQuote === true &&\n hasTransactionType(transaction, [TransactionType.predictWithdraw]);\n const relaxPrefundedSourceEstimate =\n isPredictWithdraw &&\n new BigNumber(request.sourceTokenAmount).gt(request.sourceBalanceRaw);\n const gasEstimateTransactions = orderedTransactions.map(\n (orderedTransaction) => ({\n chainId: toHex(orderedTransaction.chainId),\n data: orderedTransaction.data,\n from,\n gas: orderedTransaction.gas,\n to: orderedTransaction.to,\n value: orderedTransaction.value ?? '0x0',\n }),\n );\n\n const gasEstimates = await estimateAcrossQuoteGasLimits({\n fallbackGas: acrossFallbackGas,\n fallbackOnSimulationFailure: relaxPrefundedSourceEstimate,\n messenger,\n transactions: gasEstimateTransactions,\n });\n\n const { batchGasLimit, is7702, requiresAuthorizationList, totalGasEstimate } =\n gasEstimates;\n\n let sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n let gasLimits: AcrossGasLimits;\n\n if (is7702) {\n if (!batchGasLimit) {\n throw new Error('Across combined batch gas estimate missing');\n }\n\n const estimate = calculateGasCost({\n chainId: swapChainId,\n gas: batchGasLimit.estimate,\n maxFeePerGas: swapTx.maxFeePerGas,\n maxPriorityFeePerGas: swapTx.maxPriorityFeePerGas,\n messenger,\n });\n const max = calculateGasCost({\n chainId: swapChainId,\n gas: batchGasLimit.max,\n isMax: true,\n maxFeePerGas: swapTx.maxFeePerGas,\n maxPriorityFeePerGas: swapTx.maxPriorityFeePerGas,\n messenger,\n });\n\n sourceNetwork = {\n estimate,\n max,\n };\n gasLimits = [\n {\n estimate: batchGasLimit.estimate,\n max: batchGasLimit.max,\n },\n ];\n } else {\n const transactionGasLimits = orderedTransactions.map(\n (orderedTransaction, index) => ({\n gasEstimate: gasEstimates.gasLimits[index],\n orderedTransaction,\n }),\n );\n\n const estimate = sumAmounts(\n transactionGasLimits.map(({ gasEstimate, orderedTransaction }) =>\n calculateGasCost({\n chainId: toHex(orderedTransaction.chainId),\n gas: gasEstimate.estimate,\n maxFeePerGas: orderedTransaction.maxFeePerGas,\n maxPriorityFeePerGas: orderedTransaction.maxPriorityFeePerGas,\n messenger,\n }),\n ),\n );\n\n const max = sumAmounts(\n transactionGasLimits.map(({ gasEstimate, orderedTransaction }) =>\n calculateGasCost({\n chainId: toHex(orderedTransaction.chainId),\n gas: gasEstimate.max,\n isMax: true,\n maxFeePerGas: orderedTransaction.maxFeePerGas,\n maxPriorityFeePerGas: orderedTransaction.maxPriorityFeePerGas,\n messenger,\n }),\n ),\n );\n\n sourceNetwork = {\n estimate,\n max,\n };\n gasLimits = transactionGasLimits.map(({ gasEstimate }) => ({\n estimate: gasEstimate.estimate,\n max: gasEstimate.max,\n }));\n }\n\n const result = {\n sourceNetwork,\n is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n gasLimits,\n totalGasEstimate,\n totalGasLimit: gasEstimates.totalGasLimit,\n };\n\n const finalResult = request.isPostQuote\n ? combinePostQuoteGas(result, transaction, swapTx, messenger)\n : result;\n\n const firstTransaction = orderedTransactions[0];\n\n // Predict withdraws always consult the gas station: the user's source token\n // lives in the Safe, so a healthy native balance does not mean they can\n // actually pay gas. They do require an EIP-7702 capable account, since the\n // withdraw is submitted as a 7702 batch.\n const { amount: gasFeeTokenCost, isAvailable } = await resolveGasStationCost({\n accountSupports7702: isPredictWithdraw ? accountSupports7702 : undefined,\n firstStepData: {\n data: firstTransaction.data,\n to: firstTransaction.to,\n value: firstTransaction.value,\n },\n messenger,\n nativeGasCostRaw: isPredictWithdraw\n ? undefined\n : finalResult.sourceNetwork.max.raw,\n request: {\n from,\n sourceChainId,\n sourceTokenAddress,\n },\n totalGasEstimate: finalResult.totalGasEstimate,\n totalItemCount: Math.max(\n orderedTransactions.length + (request.isPostQuote ? 1 : 0),\n finalResult.gasLimits.length,\n ),\n });\n\n let gasFeeTokenNetwork:\n | TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork']\n | undefined;\n\n if (gasFeeTokenCost) {\n gasFeeTokenNetwork = {\n estimate: gasFeeTokenCost,\n max: gasFeeTokenCost,\n };\n } else if (isAvailable && isPredictWithdraw) {\n gasFeeTokenNetwork = calculateSourceGasFeeTokenNetworkFallback({\n messenger,\n nativeSourceNetwork: finalResult.sourceNetwork,\n quote,\n request,\n });\n }\n\n if (!gasFeeTokenNetwork) {\n return finalResult;\n }\n\n log('Using gas fee token for Across source network', {\n gasFeeTokenCost: gasFeeTokenNetwork.max,\n });\n\n return {\n isGasFeeToken: true,\n sourceNetwork: gasFeeTokenNetwork,\n is7702: finalResult.is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n gasLimits: finalResult.gasLimits,\n };\n}\n\nfunction calculateSourceGasFeeTokenNetworkFallback({\n messenger,\n nativeSourceNetwork,\n quote,\n request,\n}: {\n messenger: TransactionPayControllerMessenger;\n nativeSourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n quote: AcrossSwapApprovalResponse;\n request: QuoteRequest;\n}): TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'] | undefined {\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n request.sourceTokenAddress,\n request.sourceChainId,\n );\n\n if (!sourceFiatRate) {\n return undefined;\n }\n\n const estimate = calculateSourceGasFeeTokenAmountFallback({\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n nativeGasCost: nativeSourceNetwork.estimate,\n });\n const max = calculateSourceGasFeeTokenAmountFallback({\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n nativeGasCost: nativeSourceNetwork.max,\n });\n\n if (!estimate || !max) {\n return undefined;\n }\n\n return { estimate, max };\n}\n\nfunction calculateSourceGasFeeTokenAmountFallback({\n decimals,\n fiatRate,\n nativeGasCost,\n}: {\n decimals: number;\n fiatRate: FiatRates;\n nativeGasCost: Amount;\n}): Amount | undefined {\n const usdRate = new BigNumber(fiatRate.usdRate);\n const nativeGasUsd = new BigNumber(nativeGasCost.usd);\n\n if (\n !usdRate.isFinite() ||\n !usdRate.isGreaterThan(0) ||\n !nativeGasUsd.isFinite() ||\n !nativeGasUsd.isGreaterThan(0)\n ) {\n return undefined;\n }\n\n const amountRaw = nativeGasUsd\n .dividedBy(usdRate)\n .shiftedBy(decimals)\n .integerValue(BigNumber.ROUND_CEIL)\n .toFixed(0);\n\n return getAmountFromTokenAmount({\n amountRaw,\n decimals,\n fiatRate,\n });\n}\n\nasync function estimateAcrossQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure,\n messenger,\n transactions,\n}: {\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure: boolean;\n messenger: TransactionPayControllerMessenger;\n transactions: QuoteGasTransaction[];\n}): Promise<Awaited<ReturnType<typeof estimateQuoteGasLimits>>> {\n try {\n const gasEstimates = await estimateQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure,\n messenger,\n transactions,\n });\n\n if (\n fallbackOnSimulationFailure &&\n fallbackGas !== undefined &&\n gasEstimates.is7702 &&\n gasEstimates.batchGasLimit !== undefined &&\n gasEstimates.batchGasLimit.max > fallbackGas.max\n ) {\n // Prefunded Predict withdraws can produce inflated 7702 batch estimates\n // because the source account does not yet hold the funds. Keep the gas\n // reservation bounded by the configured Across fallback for this path.\n return {\n ...gasEstimates,\n batchGasLimit: fallbackGas,\n gasLimits: [fallbackGas],\n totalGasEstimate: fallbackGas.estimate,\n totalGasLimit: fallbackGas.max,\n };\n }\n\n return gasEstimates;\n } catch (error) {\n if (!fallbackOnSimulationFailure || transactions.length <= 1) {\n throw error;\n }\n\n const perTransactionGasEstimates = await Promise.all(\n transactions.map((transaction) =>\n estimateQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure: true,\n messenger,\n transactions: [transaction],\n }),\n ),\n );\n const gasLimits = perTransactionGasEstimates.map(\n (estimate) => estimate.gasLimits[0],\n );\n const totalGasEstimate = gasLimits.reduce(\n (total, gasLimit) => total + gasLimit.estimate,\n 0,\n );\n const totalGasLimit = gasLimits.reduce(\n (total, gasLimit) => total + gasLimit.max,\n 0,\n );\n\n return {\n gasLimits,\n is7702: false,\n totalGasEstimate,\n totalGasLimit,\n usedBatch: false,\n };\n }\n}\n\nfunction combinePostQuoteGas(\n gasResult: {\n sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n gasLimits: AcrossGasLimits;\n is7702: boolean;\n requiresAuthorizationList?: true;\n totalGasEstimate: number;\n totalGasLimit: number;\n },\n transaction: TransactionMeta,\n swapTx: AcrossSwapApprovalResponse['swapTx'],\n messenger: TransactionPayControllerMessenger,\n): typeof gasResult {\n const originalTxGas = getOriginalTransactionGas(transaction);\n\n if (originalTxGas === undefined) {\n return gasResult;\n }\n\n const gasLimits = gasResult.is7702\n ? [\n {\n estimate: gasResult.gasLimits[0].estimate + originalTxGas,\n max: gasResult.gasLimits[0].max + originalTxGas,\n },\n ]\n : [\n {\n estimate: originalTxGas,\n max: originalTxGas,\n },\n ...gasResult.gasLimits,\n ];\n\n const totalGasEstimate = gasResult.totalGasEstimate + originalTxGas;\n const totalGasLimit = gasResult.totalGasLimit + originalTxGas;\n const originalSourceNetwork = calculateOriginalSourceNetworkCost({\n gas: originalTxGas,\n messenger,\n swapTx,\n transaction,\n });\n\n return {\n ...gasResult,\n sourceNetwork: {\n estimate: sumAmounts([\n gasResult.sourceNetwork.estimate,\n originalSourceNetwork.estimate,\n ]),\n max: sumAmounts([gasResult.sourceNetwork.max, originalSourceNetwork.max]),\n },\n gasLimits,\n totalGasEstimate,\n totalGasLimit,\n };\n}\n\nfunction calculateOriginalSourceNetworkCost({\n gas,\n messenger,\n swapTx,\n transaction,\n}: {\n gas: number;\n messenger: TransactionPayControllerMessenger;\n swapTx: AcrossSwapApprovalResponse['swapTx'];\n transaction: TransactionMeta;\n}): TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'] {\n const originalTransactionWithGas = transaction.nestedTransactions?.find(\n (tx) => tx.gas,\n );\n const maxFeePerGas =\n originalTransactionWithGas?.maxFeePerGas ??\n transaction.txParams.maxFeePerGas;\n const maxPriorityFeePerGas =\n originalTransactionWithGas?.maxPriorityFeePerGas ??\n transaction.txParams.maxPriorityFeePerGas;\n\n return {\n estimate: calculateGasCost({\n chainId: transaction.chainId ?? toHex(swapTx.chainId),\n gas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n }),\n max: calculateGasCost({\n chainId: transaction.chainId ?? toHex(swapTx.chainId),\n gas,\n isMax: true,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n }),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"across-quotes.js","sourceRoot":"","sources":["../../../src/strategy/across/across-quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,kCAAkC,CAAC;AAG1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAShD,OAAO,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,EACL,sBAAsB,EACtB,WAAW,GACZ,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAElE,OAAO,E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C,OAAO;QACL,QAAQ,EAAE,gBAAgB,CAAC;YACzB,OAAO,EAAE,WAAW,CAAC,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC;YACrD,GAAG;YACH,YAAY;YACZ,oBAAoB;YACpB,SAAS;SACV,CAAC;QACF,GAAG,EAAE,gBAAgB,CAAC;YACpB,OAAO,EAAE,WAAW,CAAC,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC;YACrD,GAAG;YACH,KAAK,EAAE,IAAI;YACX,YAAY;YACZ,oBAAoB;YACpB,SAAS;SACV,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import { successfulFetch, toHex } from '@metamask/controller-utils';\nimport {\n TransactionType,\n hasTransactionType,\n} from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { TransactionPayStrategy } from '../../constants.js';\nimport { projectLogger } from '../../logger.js';\nimport type {\n Amount,\n FiatRates,\n PayStrategyGetQuotesRequest,\n QuoteRequest,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types.js';\nimport { getFiatValueFromUsd, sumAmounts } from '../../utils/amounts.js';\nimport {\n getPayStrategiesConfig,\n getSlippage,\n} from '../../utils/feature-flags.js';\nimport { resolveGasStationCost } from '../../utils/gas-payment.js';\nimport { calculateGasCost } from '../../utils/gas.js';\nimport { estimateQuoteGasLimits } from '../../utils/quote-gas.js';\nimport type { QuoteGasTransaction } from '../../utils/quote-gas.js';\nimport { getTokenFiatRate } from '../../utils/token.js';\nimport type { AcrossDestination } from './across-actions.js';\nimport { getAcrossDestination } from './across-actions.js';\nimport { hasUnsupportedTransactionAuthorizationList } from './authorization-list.js';\nimport { normalizeAcrossRequest, validateAcrossPerpsQuote } from './perps.js';\nimport { isAcrossQuoteRequest } from './requests.js';\nimport {\n getAcrossOrderedTransactions,\n getOriginalTransactionGas,\n} from './transactions.js';\nimport type {\n AcrossAction,\n AcrossActionRequestBody,\n AcrossGasLimits,\n AcrossQuote,\n AcrossSwapApprovalResponse,\n} from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'across-strategy');\n\nconst UNSUPPORTED_AUTHORIZATION_LIST_ERROR =\n 'Across does not support type-4/EIP-7702 authorization lists yet';\n\ntype AcrossQuoteWithoutMetaMask = Omit<AcrossQuote, 'metamask'>;\n\n/**\n * Fetch Across quotes.\n *\n * @param request - Request object.\n * @returns Array of quotes.\n */\nexport async function getAcrossQuotes(\n request: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>[]> {\n const { requests } = request;\n\n log('Fetching quotes', requests);\n\n try {\n const normalizedRequests = requests.filter(isAcrossQuoteRequest);\n\n if (normalizedRequests.length === 0) {\n return [];\n }\n\n if (\n hasUnsupportedTransactionAuthorizationList(\n request.transaction,\n normalizedRequests,\n )\n ) {\n throw new Error(UNSUPPORTED_AUTHORIZATION_LIST_ERROR);\n }\n\n return await Promise.all(\n normalizedRequests.map((singleRequest) =>\n getQuoteWithGasStationHandling(singleRequest, request),\n ),\n );\n } catch (error) {\n log('Error fetching quotes', { error });\n throw new Error(`Failed to fetch Across quotes: ${String(error)}`);\n }\n}\n\nasync function getSingleQuote(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n const { messenger, signal, transaction } = fullRequest;\n const normalizedRequest = normalizeAcrossRequest(request, transaction);\n const {\n from,\n isMaxAmount,\n sourceChainId,\n sourceTokenAddress,\n sourceTokenAmount,\n targetAmountMinimum,\n targetChainId,\n targetTokenAddress,\n } = normalizedRequest;\n\n const config = getPayStrategiesConfig(messenger);\n const slippageDecimal = getSlippage(\n messenger,\n sourceChainId,\n sourceTokenAddress,\n );\n\n const useExactInput = isMaxAmount\n ? true\n : normalizedRequest.isPostQuote === true;\n const amount = useExactInput ? sourceTokenAmount : targetAmountMinimum;\n const tradeType = useExactInput ? 'exactInput' : 'exactOutput';\n const destination = getAcrossDestinationForRequest(\n transaction,\n request,\n request.accountOverride ?? from,\n );\n\n const quote = await requestAcrossApproval({\n actions: destination.actions,\n amount,\n apiBase: config.across.apiBase,\n depositor: from,\n destinationChainId: targetChainId,\n inputToken: sourceTokenAddress,\n originChainId: sourceChainId,\n outputToken: targetTokenAddress,\n recipient: destination.recipient,\n signal,\n refundAddress: normalizedRequest.refundTo,\n slippage: slippageDecimal,\n tradeType,\n });\n\n validateAcrossPerpsQuote(normalizedRequest, quote);\n\n const originalQuote: AcrossQuoteWithoutMetaMask = {\n quote,\n request: {\n actions: destination.actions,\n amount,\n tradeType,\n },\n };\n\n return await normalizeQuote(originalQuote, normalizedRequest, fullRequest);\n}\n\nfunction getAcrossDestinationForRequest(\n transaction: TransactionMeta,\n request: QuoteRequest,\n recipient: Hex,\n): AcrossDestination {\n if (request.isPostQuote) {\n return {\n actions: [],\n recipient,\n };\n }\n\n return getAcrossDestination(transaction, request);\n}\n\nasync function getQuoteWithGasStationHandling(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n // Phase 1 uses the requested source amount to discover whether Across will\n // pay source-chain gas with the source token, and what the max gas cost is.\n // Phase 2 repeats the quote with that max gas cost reserved from the source\n // amount, so execution can fund both the Across deposit and token-paid gas.\n const phase1Quote = await getSingleQuote(request, fullRequest);\n\n if (\n (!request.isMaxAmount && !request.isPostQuote) ||\n !phase1Quote.fees.isSourceGasFeeToken\n ) {\n return phase1Quote;\n }\n\n const requiresSourceGasReservation =\n request.isPostQuote === true &&\n hasTransactionType(fullRequest.transaction, [\n TransactionType.predictWithdraw,\n ]);\n\n const adjustedSourceAmount = new BigNumber(request.sourceTokenAmount)\n .minus(phase1Quote.fees.sourceNetwork.max.raw)\n .integerValue(BigNumber.ROUND_DOWN);\n\n if (!adjustedSourceAmount.isGreaterThan(0)) {\n log('Insufficient balance after gas subtraction for Across quote');\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw source amount cannot cover source gas fee token',\n );\n }\n return phase1Quote;\n }\n\n log('Subtracting gas from source for Across quote', {\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n gasCostRaw: phase1Quote.fees.sourceNetwork.max.raw,\n originalSourceAmount: request.sourceTokenAmount,\n });\n\n try {\n const phase2Quote = await getSingleQuote(\n {\n ...request,\n sourceTokenAmount: adjustedSourceAmount.toFixed(\n 0,\n BigNumber.ROUND_DOWN,\n ),\n },\n fullRequest,\n );\n\n if (!phase2Quote.fees.isSourceGasFeeToken) {\n log('Across phase 2 lost gas fee token eligibility');\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw quote lost source gas fee token eligibility',\n );\n }\n return phase1Quote;\n }\n\n const phase2GasCost = new BigNumber(phase2Quote.fees.sourceNetwork.max.raw);\n\n if (\n adjustedSourceAmount\n .plus(phase2GasCost)\n .isGreaterThan(request.sourceTokenAmount)\n ) {\n log('Across phase 2 quote exceeds original source amount', {\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n gasCostRaw: phase2GasCost.toString(10),\n originalSourceAmount: request.sourceTokenAmount,\n });\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw source gas fee token quote exceeds source amount',\n );\n }\n return phase1Quote;\n }\n\n return phase2Quote;\n } catch (error) {\n log(\n requiresSourceGasReservation\n ? 'Across phase 2 quote failed after source gas reservation'\n : 'Across phase 2 quote failed, falling back to phase 1',\n { error },\n );\n if (requiresSourceGasReservation) {\n throw error;\n }\n return phase1Quote;\n }\n}\n\ntype AcrossApprovalRequest = {\n actions: AcrossAction[];\n amount: string;\n apiBase: string;\n depositor: Hex;\n destinationChainId: Hex;\n inputToken: Hex;\n originChainId: Hex;\n outputToken: Hex;\n recipient: Hex;\n refundAddress?: Hex;\n signal?: AbortSignal;\n slippage?: number;\n tradeType: 'exactInput' | 'exactOutput';\n};\n\nasync function requestAcrossApproval(\n request: AcrossApprovalRequest,\n): Promise<AcrossSwapApprovalResponse> {\n const {\n actions,\n amount,\n apiBase,\n depositor,\n destinationChainId,\n inputToken,\n originChainId,\n outputToken,\n recipient,\n refundAddress,\n signal,\n slippage,\n tradeType,\n } = request;\n\n const params = new URLSearchParams();\n params.set('tradeType', tradeType);\n params.set('amount', amount);\n params.set('inputToken', inputToken);\n params.set('outputToken', outputToken);\n params.set('originChainId', String(parseInt(originChainId, 16)));\n params.set('destinationChainId', String(parseInt(destinationChainId, 16)));\n params.set('depositor', depositor);\n params.set('recipient', recipient);\n\n if (refundAddress !== undefined) {\n params.set('refundAddress', refundAddress);\n }\n\n if (slippage !== undefined) {\n params.set('slippage', String(slippage));\n }\n\n const body: AcrossActionRequestBody = { actions };\n const url = `${apiBase}/swap/approval?${params.toString()}`;\n const options: RequestInit = {\n body: JSON.stringify(body),\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n signal,\n };\n\n const response = await successfulFetch(url, options);\n\n return (await response.json()) as AcrossSwapApprovalResponse;\n}\n\nasync function normalizeQuote(\n original: AcrossQuoteWithoutMetaMask,\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n const { messenger } = fullRequest;\n const { quote } = original;\n\n const { usdToFiatRate, sourceFiatRate, targetFiatRate } = getFiatRates(\n messenger,\n quote,\n );\n\n const dustUsd = calculateDustUsd(quote, request, targetFiatRate);\n const dust = getFiatValueFromUsd(dustUsd, usdToFiatRate);\n\n const {\n gasLimits,\n is7702,\n isGasFeeToken: isSourceGasFeeToken,\n requiresAuthorizationList,\n sourceNetwork,\n } = await calculateSourceNetworkCost(\n quote,\n messenger,\n request,\n fullRequest.transaction,\n fullRequest.accountSupports7702,\n );\n\n const targetNetwork = getFiatValueFromUsd(new BigNumber(0), usdToFiatRate);\n\n const inputAmountRaw = quote.inputAmount ?? '0';\n const outputAmountRaw = new BigNumber(\n quote.expectedOutputAmount ??\n quote.minOutputAmount ??\n request.targetAmountMinimum ??\n '0',\n ).toString(10);\n\n const sourceAmount = getAmountFromTokenAmount({\n amountRaw: inputAmountRaw,\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n });\n\n const providerUsd = calculateProviderUsd(\n quote,\n inputAmountRaw,\n sourceFiatRate,\n targetFiatRate,\n quote.expectedOutputAmount,\n );\n const provider = getFiatValueFromUsd(providerUsd, usdToFiatRate);\n const metaMaskFee = getFiatValueFromUsd(\n new BigNumber(quote.fees?.app?.amountUsd ?? '0').abs(),\n usdToFiatRate,\n );\n\n const targetAmount = getAmountFromTokenAmount({\n amountRaw: outputAmountRaw,\n decimals: quote.outputToken.decimals,\n fiatRate: targetFiatRate,\n });\n\n const metamask = {\n gasLimits,\n is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n };\n\n return {\n dust,\n estimatedDuration: quote.expectedFillTime ?? 0,\n fees: {\n isSourceGasFeeToken,\n metaMask: metaMaskFee,\n provider,\n sourceNetwork,\n targetNetwork,\n },\n isInputBased: original.request.tradeType === 'exactInput',\n original: {\n ...original,\n metamask,\n },\n request,\n sourceAmount,\n targetAmount,\n strategy: TransactionPayStrategy.Across,\n };\n}\n\nfunction getFiatRates(\n messenger: TransactionPayControllerMessenger,\n quote: AcrossSwapApprovalResponse,\n): {\n sourceFiatRate: FiatRates;\n targetFiatRate: FiatRates;\n usdToFiatRate: BigNumber;\n} {\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n quote.inputToken.address,\n toHex(quote.inputToken.chainId),\n );\n\n if (!sourceFiatRate) {\n throw new Error('Source token fiat rate not found');\n }\n\n const targetFiatRate =\n getTokenFiatRate(\n messenger,\n quote.outputToken.address,\n toHex(quote.outputToken.chainId),\n ) ?? sourceFiatRate;\n\n const usdToFiatRate = new BigNumber(sourceFiatRate.fiatRate).dividedBy(\n sourceFiatRate.usdRate,\n );\n\n return { sourceFiatRate, targetFiatRate, usdToFiatRate };\n}\n\nfunction calculateDustUsd(\n quote: AcrossSwapApprovalResponse,\n request: QuoteRequest,\n targetFiatRate: FiatRates,\n): BigNumber {\n const expectedOutputRaw = quote.expectedOutputAmount;\n\n if (expectedOutputRaw === undefined) {\n return new BigNumber(0);\n }\n\n const expectedOutput = new BigNumber(expectedOutputRaw);\n const minimumOutput = new BigNumber(\n quote.minOutputAmount ?? request.targetAmountMinimum ?? '0',\n );\n\n const dustRaw = expectedOutput.minus(minimumOutput).isNegative()\n ? new BigNumber(0)\n : expectedOutput.minus(minimumOutput);\n const dustHuman = dustRaw.shiftedBy(-quote.outputToken.decimals);\n\n return dustHuman.multipliedBy(targetFiatRate.usdRate);\n}\n\nfunction calculateProviderUsd(\n quote: AcrossSwapApprovalResponse,\n inputAmountRaw: string,\n sourceFiatRate: FiatRates,\n targetFiatRate: FiatRates,\n expectedOutputRaw?: string,\n): BigNumber {\n const totalFeeUsd = quote.fees?.total?.amountUsd;\n\n if (totalFeeUsd !== undefined) {\n return new BigNumber(totalFeeUsd).abs();\n }\n\n if (expectedOutputRaw === undefined) {\n return new BigNumber(0);\n }\n\n const expectedOutput = new BigNumber(expectedOutputRaw);\n\n if (expectedOutput.lte(0)) {\n return new BigNumber(0);\n }\n\n const inputAmountUsd = new BigNumber(inputAmountRaw)\n .shiftedBy(-quote.inputToken.decimals)\n .multipliedBy(sourceFiatRate.usdRate);\n const expectedOutputUsd = expectedOutput\n .shiftedBy(-quote.outputToken.decimals)\n .multipliedBy(targetFiatRate.usdRate);\n const providerFeeUsd = inputAmountUsd.minus(expectedOutputUsd);\n\n return providerFeeUsd.isNegative() ? new BigNumber(0) : providerFeeUsd;\n}\n\nfunction getAmountFromTokenAmount({\n amountRaw,\n decimals,\n fiatRate,\n}: {\n amountRaw: string;\n decimals: number;\n fiatRate: FiatRates;\n}): Amount {\n const rawValue = new BigNumber(amountRaw);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\n\n const usd = humanValue.multipliedBy(fiatRate.usdRate).toString(10);\n const fiat = humanValue.multipliedBy(fiatRate.fiatRate).toString(10);\n\n return {\n fiat,\n human,\n raw,\n usd,\n };\n}\n\nasync function calculateSourceNetworkCost(\n quote: AcrossSwapApprovalResponse,\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n transaction: TransactionMeta,\n accountSupports7702: boolean,\n): Promise<{\n sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n gasLimits: AcrossGasLimits;\n isGasFeeToken?: boolean;\n is7702: boolean;\n requiresAuthorizationList?: true;\n}> {\n const acrossFallbackGas =\n getPayStrategiesConfig(messenger).across.fallbackGas;\n const { from, sourceChainId, sourceTokenAddress } = request;\n const orderedTransactions = getAcrossOrderedTransactions({ quote });\n const { swapTx } = quote;\n const swapChainId = toHex(swapTx.chainId);\n const isPredictWithdraw =\n request.isPostQuote === true &&\n hasTransactionType(transaction, [TransactionType.predictWithdraw]);\n const relaxPrefundedSourceEstimate =\n isPredictWithdraw &&\n new BigNumber(request.sourceTokenAmount).gt(request.sourceBalanceRaw);\n const gasEstimateTransactions = orderedTransactions.map(\n (orderedTransaction) => ({\n chainId: toHex(orderedTransaction.chainId),\n data: orderedTransaction.data,\n from,\n gas: orderedTransaction.gas,\n to: orderedTransaction.to,\n value: orderedTransaction.value ?? '0x0',\n }),\n );\n\n const gasEstimates = await estimateAcrossQuoteGasLimits({\n fallbackGas: acrossFallbackGas,\n fallbackOnSimulationFailure: relaxPrefundedSourceEstimate,\n messenger,\n transactions: gasEstimateTransactions,\n });\n\n const { batchGasLimit, is7702, requiresAuthorizationList, totalGasEstimate } =\n gasEstimates;\n\n let sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n let gasLimits: AcrossGasLimits;\n\n if (is7702) {\n if (!batchGasLimit) {\n throw new Error('Across combined batch gas estimate missing');\n }\n\n const estimate = calculateGasCost({\n chainId: swapChainId,\n gas: batchGasLimit.estimate,\n maxFeePerGas: swapTx.maxFeePerGas,\n maxPriorityFeePerGas: swapTx.maxPriorityFeePerGas,\n messenger,\n });\n const max = calculateGasCost({\n chainId: swapChainId,\n gas: batchGasLimit.max,\n isMax: true,\n maxFeePerGas: swapTx.maxFeePerGas,\n maxPriorityFeePerGas: swapTx.maxPriorityFeePerGas,\n messenger,\n });\n\n sourceNetwork = {\n estimate,\n max,\n };\n gasLimits = [\n {\n estimate: batchGasLimit.estimate,\n max: batchGasLimit.max,\n },\n ];\n } else {\n const transactionGasLimits = orderedTransactions.map(\n (orderedTransaction, index) => ({\n gasEstimate: gasEstimates.gasLimits[index],\n orderedTransaction,\n }),\n );\n\n const estimate = sumAmounts(\n transactionGasLimits.map(({ gasEstimate, orderedTransaction }) =>\n calculateGasCost({\n chainId: toHex(orderedTransaction.chainId),\n gas: gasEstimate.estimate,\n maxFeePerGas: orderedTransaction.maxFeePerGas,\n maxPriorityFeePerGas: orderedTransaction.maxPriorityFeePerGas,\n messenger,\n }),\n ),\n );\n\n const max = sumAmounts(\n transactionGasLimits.map(({ gasEstimate, orderedTransaction }) =>\n calculateGasCost({\n chainId: toHex(orderedTransaction.chainId),\n gas: gasEstimate.max,\n isMax: true,\n maxFeePerGas: orderedTransaction.maxFeePerGas,\n maxPriorityFeePerGas: orderedTransaction.maxPriorityFeePerGas,\n messenger,\n }),\n ),\n );\n\n sourceNetwork = {\n estimate,\n max,\n };\n gasLimits = transactionGasLimits.map(({ gasEstimate }) => ({\n estimate: gasEstimate.estimate,\n max: gasEstimate.max,\n }));\n }\n\n const result = {\n sourceNetwork,\n is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n gasLimits,\n totalGasEstimate,\n totalGasLimit: gasEstimates.totalGasLimit,\n };\n\n const finalResult = request.isPostQuote\n ? combinePostQuoteGas(result, transaction, swapTx, messenger)\n : result;\n\n const firstTransaction = orderedTransactions[0];\n\n // Predict withdraws always consult the gas station: the user's source token\n // lives in the Safe, so a healthy native balance does not mean they can\n // actually pay gas. They do require an EIP-7702 capable account, since the\n // withdraw is submitted as a 7702 batch.\n const { amount: gasFeeTokenCost, isAvailable } = await resolveGasStationCost({\n accountSupports7702: isPredictWithdraw ? accountSupports7702 : undefined,\n firstStepData: {\n data: firstTransaction.data,\n to: firstTransaction.to,\n value: firstTransaction.value,\n },\n messenger,\n nativeGasCostRaw: isPredictWithdraw\n ? undefined\n : finalResult.sourceNetwork.max.raw,\n request: {\n from,\n sourceChainId,\n sourceTokenAddress,\n },\n totalGasEstimate: finalResult.totalGasEstimate,\n totalItemCount: Math.max(\n orderedTransactions.length + (request.isPostQuote ? 1 : 0),\n finalResult.gasLimits.length,\n ),\n });\n\n let gasFeeTokenNetwork:\n | TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork']\n | undefined;\n\n if (gasFeeTokenCost) {\n gasFeeTokenNetwork = {\n estimate: gasFeeTokenCost,\n max: gasFeeTokenCost,\n };\n } else if (isAvailable && isPredictWithdraw) {\n gasFeeTokenNetwork = calculateSourceGasFeeTokenNetworkFallback({\n messenger,\n nativeSourceNetwork: finalResult.sourceNetwork,\n quote,\n request,\n });\n }\n\n if (!gasFeeTokenNetwork) {\n return finalResult;\n }\n\n log('Using gas fee token for Across source network', {\n gasFeeTokenCost: gasFeeTokenNetwork.max,\n });\n\n return {\n isGasFeeToken: true,\n sourceNetwork: gasFeeTokenNetwork,\n is7702: finalResult.is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n gasLimits: finalResult.gasLimits,\n };\n}\n\nfunction calculateSourceGasFeeTokenNetworkFallback({\n messenger,\n nativeSourceNetwork,\n quote,\n request,\n}: {\n messenger: TransactionPayControllerMessenger;\n nativeSourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n quote: AcrossSwapApprovalResponse;\n request: QuoteRequest;\n}): TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'] | undefined {\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n request.sourceTokenAddress,\n request.sourceChainId,\n );\n\n if (!sourceFiatRate) {\n return undefined;\n }\n\n const estimate = calculateSourceGasFeeTokenAmountFallback({\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n nativeGasCost: nativeSourceNetwork.estimate,\n });\n const max = calculateSourceGasFeeTokenAmountFallback({\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n nativeGasCost: nativeSourceNetwork.max,\n });\n\n if (!estimate || !max) {\n return undefined;\n }\n\n return { estimate, max };\n}\n\nfunction calculateSourceGasFeeTokenAmountFallback({\n decimals,\n fiatRate,\n nativeGasCost,\n}: {\n decimals: number;\n fiatRate: FiatRates;\n nativeGasCost: Amount;\n}): Amount | undefined {\n const usdRate = new BigNumber(fiatRate.usdRate);\n const nativeGasUsd = new BigNumber(nativeGasCost.usd);\n\n if (\n !usdRate.isFinite() ||\n !usdRate.isGreaterThan(0) ||\n !nativeGasUsd.isFinite() ||\n !nativeGasUsd.isGreaterThan(0)\n ) {\n return undefined;\n }\n\n const amountRaw = nativeGasUsd\n .dividedBy(usdRate)\n .shiftedBy(decimals)\n .integerValue(BigNumber.ROUND_CEIL)\n .toFixed(0);\n\n return getAmountFromTokenAmount({\n amountRaw,\n decimals,\n fiatRate,\n });\n}\n\nasync function estimateAcrossQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure,\n messenger,\n transactions,\n}: {\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure: boolean;\n messenger: TransactionPayControllerMessenger;\n transactions: QuoteGasTransaction[];\n}): Promise<Awaited<ReturnType<typeof estimateQuoteGasLimits>>> {\n try {\n const gasEstimates = await estimateQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure,\n messenger,\n transactions,\n });\n\n if (\n fallbackOnSimulationFailure &&\n fallbackGas !== undefined &&\n gasEstimates.is7702 &&\n gasEstimates.batchGasLimit !== undefined &&\n gasEstimates.batchGasLimit.max > fallbackGas.max\n ) {\n // Prefunded Predict withdraws can produce inflated 7702 batch estimates\n // because the source account does not yet hold the funds. Keep the gas\n // reservation bounded by the configured Across fallback for this path.\n return {\n ...gasEstimates,\n batchGasLimit: fallbackGas,\n gasLimits: [fallbackGas],\n totalGasEstimate: fallbackGas.estimate,\n totalGasLimit: fallbackGas.max,\n };\n }\n\n return gasEstimates;\n } catch (error) {\n if (!fallbackOnSimulationFailure || transactions.length <= 1) {\n throw error;\n }\n\n const perTransactionGasEstimates = await Promise.all(\n transactions.map((transaction) =>\n estimateQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure: true,\n messenger,\n transactions: [transaction],\n }),\n ),\n );\n const gasLimits = perTransactionGasEstimates.map(\n (estimate) => estimate.gasLimits[0],\n );\n const totalGasEstimate = gasLimits.reduce(\n (total, gasLimit) => total + gasLimit.estimate,\n 0,\n );\n const totalGasLimit = gasLimits.reduce(\n (total, gasLimit) => total + gasLimit.max,\n 0,\n );\n\n return {\n gasLimits,\n is7702: false,\n totalGasEstimate,\n totalGasLimit,\n usedBatch: false,\n };\n }\n}\n\nfunction combinePostQuoteGas(\n gasResult: {\n sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n gasLimits: AcrossGasLimits;\n is7702: boolean;\n requiresAuthorizationList?: true;\n totalGasEstimate: number;\n totalGasLimit: number;\n },\n transaction: TransactionMeta,\n swapTx: AcrossSwapApprovalResponse['swapTx'],\n messenger: TransactionPayControllerMessenger,\n): typeof gasResult {\n const originalTxGas = getOriginalTransactionGas(transaction);\n\n if (originalTxGas === undefined) {\n return gasResult;\n }\n\n const gasLimits = gasResult.is7702\n ? [\n {\n estimate: gasResult.gasLimits[0].estimate + originalTxGas,\n max: gasResult.gasLimits[0].max + originalTxGas,\n },\n ]\n : [\n {\n estimate: originalTxGas,\n max: originalTxGas,\n },\n ...gasResult.gasLimits,\n ];\n\n const totalGasEstimate = gasResult.totalGasEstimate + originalTxGas;\n const totalGasLimit = gasResult.totalGasLimit + originalTxGas;\n const originalSourceNetwork = calculateOriginalSourceNetworkCost({\n gas: originalTxGas,\n messenger,\n swapTx,\n transaction,\n });\n\n return {\n ...gasResult,\n sourceNetwork: {\n estimate: sumAmounts([\n gasResult.sourceNetwork.estimate,\n originalSourceNetwork.estimate,\n ]),\n max: sumAmounts([gasResult.sourceNetwork.max, originalSourceNetwork.max]),\n },\n gasLimits,\n totalGasEstimate,\n totalGasLimit,\n };\n}\n\nfunction calculateOriginalSourceNetworkCost({\n gas,\n messenger,\n swapTx,\n transaction,\n}: {\n gas: number;\n messenger: TransactionPayControllerMessenger;\n swapTx: AcrossSwapApprovalResponse['swapTx'];\n transaction: TransactionMeta;\n}): TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'] {\n const originalTransactionWithGas = transaction.nestedTransactions?.find(\n (tx) => tx.gas,\n );\n const maxFeePerGas =\n originalTransactionWithGas?.maxFeePerGas ??\n transaction.txParams.maxFeePerGas;\n const maxPriorityFeePerGas =\n originalTransactionWithGas?.maxPriorityFeePerGas ??\n transaction.txParams.maxPriorityFeePerGas;\n\n return {\n estimate: calculateGasCost({\n chainId: transaction.chainId ?? toHex(swapTx.chainId),\n gas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n }),\n max: calculateGasCost({\n chainId: transaction.chainId ?? toHex(swapTx.chainId),\n gas,\n isMax: true,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n }),\n };\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -374,6 +374,11 @@ export type FiatRates = {
|
|
|
374
374
|
};
|
|
375
375
|
/** Request for a quote to retrieve a required token. */
|
|
376
376
|
export type QuoteRequest = {
|
|
377
|
+
/**
|
|
378
|
+
* Selected account receiving post-quote output.
|
|
379
|
+
* See {@link TransactionConfig.accountOverride}.
|
|
380
|
+
*/
|
|
381
|
+
accountOverride?: Hex;
|
|
377
382
|
/**
|
|
378
383
|
* Whether the target transaction is executed atomically with the Relay
|
|
379
384
|
* quote. See {@link TransactionConfig.atomic}.
|
|
@@ -485,8 +490,8 @@ export type PayStrategyGetQuotesRequest = {
|
|
|
485
490
|
/** Selected fiat payment method ID, if applicable. */
|
|
486
491
|
fiatPaymentMethod?: string;
|
|
487
492
|
/**
|
|
488
|
-
*
|
|
489
|
-
*
|
|
493
|
+
* Account sending the quotes: `txParams.from` for post-quote flows,
|
|
494
|
+
* otherwise `accountOverride ?? txParams.from`. Pre-computed by the quote
|
|
490
495
|
* orchestrator so that individual strategies do not need to re-derive it.
|
|
491
496
|
*/
|
|
492
497
|
from: Hex;
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,KAAK,EACV,8BAA8B,EAC9B,gCAAgC,EACjC,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AAC5E,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAC1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EACV,+BAA+B,EAC/B,uCAAuC,EACvC,4BAA4B,EAC5B,YAAY,EACb,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,mDAAmD,EAAE,MAAM,8BAA8B,CAAC;AACxG,OAAO,KAAK,EAAE,2CAA2C,EAAE,MAAM,8BAA8B,CAAC;AAChG,OAAO,KAAK,EAAE,uDAAuD,EAAE,MAAM,8BAA8B,CAAC;AAC5G,OAAO,KAAK,EAAE,KAAK,IAAI,UAAU,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,KAAK,EACV,6BAA6B,EAC7B,qCAAqC,EACtC,MAAM,4BAA4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,CAAC;QAAE,UAAU,EAAE,GAAG,CAAA;KAAE,CAAC,CAAC;CACpC,CAAC;AAEF,0CAA0C;AAC1C,MAAM,MAAM,MAAM,GAAG,SAAS,GAAG;IAC/B,gEAAgE;IAChE,KAAK,EAAE,MAAM,CAAC;IAEd,gEAAgE;IAChE,GAAG,EAAE,MAAM,CAAC;CACb,CAAC"}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA8PA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type { AccountsControllerGetStateAction } from '@metamask/accounts-controller';\nimport type {\n AssetsControllerGetStateAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringControllerUnlockEvent,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkConfigurationByChainIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuoteWithFeesAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SentinelApiServiceActions } from '@metamask/sentinel-api-service';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n BatchTransactionParams,\n TransactionControllerAddTransactionAction,\n TransactionControllerGetGasFeeTokensAction,\n TransactionControllerGetStateAction,\n TransactionControllerStateChangeEvent,\n TransactionControllerUpdateTransactionAction,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n CONTROLLER_NAME,\n PaymentOverride,\n TransactionPayClientId,\n TransactionPayStrategy,\n} from './constants.js';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types.js';\n\nexport type AllowedActions =\n | AccountsControllerGetStateAction\n | AssetsControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByChainIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuoteWithFeesAction\n | RemoteFeatureFlagControllerGetStateAction\n | SentinelApiServiceActions\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | KeyringControllerUnlockEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction (or `paymentOverride` batch) is executed\n * atomically with the Relay quote. Defaults to `true` (embedded in the quote\n * and executed by the Relay solver). When `false`, Pay does not embed the\n * target/override calls in the quote; the quote only bridges the required\n * asset to `recipient`, and the calls are submitted separately after Relay\n * completion. Used by flows whose second-leg amount is only known after\n * Relay settles (EXACT_INPUT max flows) or that require the second leg to\n * originate from a different signer than the Relay solver.\n * For max deposits enabled by `payStrategies.relay.atomicMaxEnabled`, this\n * is a subsidy hint: atomic quotes are retried non-atomically if not\n * subsidized, and subsidized non-atomic quotes are upgraded to atomic.\n */\n atomic?: boolean;\n\n /**\n * Whether the source of funds is HyperLiquid (HyperCore).\n * When true, the Relay strategy uses the HyperLiquid 2-step withdrawal\n * flow: (1) authorize nonce-mapping, (2) sendAsset to Relay solver.\n */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n */\n isPostQuote?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request. Use this for post-quote flows where the user's funds originate\n * from a smart contract account (e.g. Predict Safe proxy) so that refunds\n * go back to that account rather than the EOA.\n */\n refundTo?: Hex;\n};\n\n/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Request passed to {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataRequest = {\n /** Amount of the source token in human-readable format. */\n amount: string;\n\n /** Metadata of the original transaction. */\n transaction: TransactionMeta;\n\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Response returned by {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataResponse = {\n /** Batch transaction params to prepend to the submit batch. */\n calls: BatchTransactionParams[];\n\n /** Optional recipient address for the funding token transfer. */\n recipient?: Hex;\n\n /** Optional EIP-7702 authorization list from delegation. */\n authorizationList?: AuthorizationList;\n};\n\n/**\n * Callback invoked during submit when `paymentOverride` is defined.\n * Returns batch transaction params to prepend to the submit batch.\n */\nexport type GetPaymentOverrideDataCallback = (\n request: GetPaymentOverrideDataRequest,\n) => Promise<GetPaymentOverrideDataResponse>;\n\nexport type GetAmountDataRequest = {\n /** Raw token amount (atomic units) to encode into calldata. */\n amount: string;\n\n /** Metadata of the transaction whose nested calls need updating. */\n transaction: TransactionMeta;\n};\n\nexport type GetAmountDataResponse = {\n /** Per-nested-call data updates; empty when no update is needed. */\n updates: { nestedTransactionIndex: number; data: Hex }[];\n};\n\n/**\n * Optional callback that re-encodes nested transaction calldata for a given\n * token amount. Used by transaction types with non-standard nested data\n * (e.g. vault approve + deposit) that cannot be derived from the amount alone\n * without client-side context (vault config, RPC providers, etc.).\n */\nexport type GetAmountDataCallback = (\n request: GetAmountDataRequest,\n) => Promise<GetAmountDataResponse>;\n\n/** Request passed to {@link GetBalanceCallback}. */\nexport type GetBalanceRequest = {\n /** Metadata of the transaction whose source balance is being resolved. */\n transaction: TransactionMeta;\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Balance override returned by {@link GetBalanceCallback}. */\nexport type GetBalanceResponse = {\n /** Balance in atomic format without factoring token decimals. */\n balanceRaw: string;\n};\n\n/**\n * Optional client-supplied callback that overrides the built-in\n * pay-token / required-token balance lookup used for `isMaxAmount`\n * source-amount calculation. Enables alternate balance sources\n * (perps, predict, money-account, post-quote, etc.) without adding\n * conditional branches inside the controller. MUST be synchronous:\n * it runs inside the controller state-update block.\n * Return `undefined` to fall back to the built-in token balance.\n */\nexport type GetBalanceCallback = (\n request: GetBalanceRequest,\n) => GetBalanceResponse | undefined;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /**\n * Identifies the MetaMask client, sent as the `X-Client-Id` header on\n * requests to the intents API so the server can distinguish Mobile from\n * Extension traffic.\n */\n clientId?: TransactionPayClientId;\n\n /** Optional callback to re-encode nested transaction calldata for a given amount. */\n getAmountData?: GetAmountDataCallback;\n\n /** Optional callback to override the source balance used for max-amount calculation. */\n getBalance?: GetBalanceCallback;\n\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** Optional fiat execution configuration. */\n fiatOptions?: TransactionPayFiatOptions;\n\n /**\n * Optional callback invoked during quote execution when `paymentOverride` is defined.\n * Returns additional transactions to be submitted alongside the quote batch.\n */\n getPaymentOverrideData?: GetPaymentOverrideDataCallback;\n\n /** Callback to select the PayStrategy for a transaction. */\n getStrategy?: (transaction: TransactionMeta) => TransactionPayStrategy;\n\n /** Callback to select ordered PayStrategies for a transaction. */\n getStrategies?: (transaction: TransactionMeta) => TransactionPayStrategy[];\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Callbacks for the Polymarket relayer; required only for the Polymarket deposit-wallet flow. */\n polymarket?: PolymarketCallbacks;\n\n /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** Optional fiat execution configuration. */\nexport type TransactionPayFiatOptions = {\n /** Test funding source used to bypass fiat on-ramp execution during local QA. */\n testFundingSource?: Hex;\n\n /** Optional human amount to transfer from the test funding source. */\n testAmountOverride?: string;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Fiat payment method state. */\n fiatPayment?: TransactionFiatPayment;\n\n /** Whether quotes are currently being retrieved. */\n isLoading: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n * Used when funds need to be moved after a transaction completes\n * (e.g., bridging output to a different token/chain).\n */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /**\n * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Most relevant structured validation error from the latest quote attempt. */\n quoteError?: QuoteErrorInfo;\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */\n caipAssetId?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/**\n * Machine-readable discriminator for a quote validation failure.\n *\n * Used for analytics and tests. Human-readable copy is carried by `message`\n * and `detail` on {@link QuoteErrorInfo}.\n */\nexport type QuoteErrorReason =\n /**\n * @deprecated No longer emitted. An unreadable live balance is treated as\n * unknown rather than insufficient, so it no longer blocks the quote. Kept\n * so existing consumers and historical analytics still type-check.\n */\n | 'balance-unavailable'\n | 'insufficient-source-balance'\n | 'insufficient-transfer-balance'\n | 'no-quotes'\n | 'simulation-failed';\n\n/**\n * Structured description of why a quote failed validation.\n *\n * `message` and `detail` are formatted (English) copy ready to display; `reason`\n * is a machine-readable discriminator for analytics and tests.\n */\nexport type QuoteErrorInfo = {\n /** Short, display-ready summary of the failure. */\n message: string;\n\n /** Machine-readable discriminator for the failure. */\n reason: QuoteErrorReason;\n\n /** Optional display-ready detail rows (e.g. Required / Current / Missing). */\n detail?: string[];\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether this quote is the direct mUSD-to-Money-Account fiat flow. */\n isDirectMusdMoneyAccount?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** Optional recipient address for Relay requests. When set, overrides the default `from` address. */\n recipient?: Hex;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /** Whether to skip processTransactions in relay-quotes. Defaults to `isPostQuote`. */\n skipProcessTransactions?: boolean;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n\n /**\n * One-time HyperLiquid activation fee (USD) reserved from the source amount\n * for an unactivated HyperCore account. The source amount sent to the\n * provider is reduced by this amount so HyperLiquid retains enough balance\n * for the fee, and the amount is surfaced as part of the provider fee.\n */\n hyperliquidActivationFeeUsd?: string;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Whether fees are subtracted from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Whether the reported fees are already included in the source amount. */\n areFeesIncludedInSourceAmount?: boolean;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /**\n * Whether the target calls could not be embedded in the quote and must be\n * submitted separately, on the target chain, once the quote settles.\n *\n * Set by the strategy at quote time, since only it knows whether the provider\n * accepted the calls. {@link TransactionConfig.atomic} is a hint rather than\n * a guarantee: a quote requested atomically still falls back to a second leg\n * when the provider cannot execute the calls itself.\n */\n requiresSecondLeg?: boolean;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /**\n * Resolved wallet address for the transaction.\n * This is `accountOverride ?? txParams.from`, pre-computed by the quote\n * orchestrator so that individual strategies do not need to re-derive it.\n */\n from: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** ID of the transaction whose refresh interval is being resolved. */\n transactionId: string;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Whether the selected quotes subtract fees from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n isSubsidized,\n}: {\n transaction: TransactionMeta;\n isSubsidized?: boolean;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** Client-supplied callbacks for the Polymarket relayer protocol. */\nexport type PolymarketCallbacks = {\n /** Derive the deposit-wallet address (CREATE2) for the given EOA. */\n getDepositWalletAddress: (params: { eoa: Hex }) => Promise<Hex>;\n\n /** Sign and broadcast a deposit-wallet batch, returning the source hash. */\n submitDepositWalletBatch: (params: {\n eoa: Hex;\n depositWallet: Hex;\n calls: { target: Hex; data: Hex; value: string }[];\n }) => Promise<{ sourceHash: Hex }>;\n};\n\n/** Single amount in alternate formats. */\nexport type Amount = FiatValue & {\n /** Amount in human-readable format factoring token decimals. */\n human: string;\n\n /** Amount in atomic format without factoring token decimals. */\n raw: string;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA8PA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type { AccountsControllerGetStateAction } from '@metamask/accounts-controller';\nimport type {\n AssetsControllerGetStateAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringControllerUnlockEvent,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkConfigurationByChainIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuoteWithFeesAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SentinelApiServiceActions } from '@metamask/sentinel-api-service';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n BatchTransactionParams,\n TransactionControllerAddTransactionAction,\n TransactionControllerGetGasFeeTokensAction,\n TransactionControllerGetStateAction,\n TransactionControllerStateChangeEvent,\n TransactionControllerUpdateTransactionAction,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n CONTROLLER_NAME,\n PaymentOverride,\n TransactionPayClientId,\n TransactionPayStrategy,\n} from './constants.js';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types.js';\n\nexport type AllowedActions =\n | AccountsControllerGetStateAction\n | AssetsControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByChainIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuoteWithFeesAction\n | RemoteFeatureFlagControllerGetStateAction\n | SentinelApiServiceActions\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | KeyringControllerUnlockEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction (or `paymentOverride` batch) is executed\n * atomically with the Relay quote. Defaults to `true` (embedded in the quote\n * and executed by the Relay solver). When `false`, Pay does not embed the\n * target/override calls in the quote; the quote only bridges the required\n * asset to `recipient`, and the calls are submitted separately after Relay\n * completion. Used by flows whose second-leg amount is only known after\n * Relay settles (EXACT_INPUT max flows) or that require the second leg to\n * originate from a different signer than the Relay solver.\n * For max deposits enabled by `payStrategies.relay.atomicMaxEnabled`, this\n * is a subsidy hint: atomic quotes are retried non-atomically if not\n * subsidized, and subsidized non-atomic quotes are upgraded to atomic.\n */\n atomic?: boolean;\n\n /**\n * Whether the source of funds is HyperLiquid (HyperCore).\n * When true, the Relay strategy uses the HyperLiquid 2-step withdrawal\n * flow: (1) authorize nonce-mapping, (2) sendAsset to Relay solver.\n */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n */\n isPostQuote?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request. Use this for post-quote flows where the user's funds originate\n * from a smart contract account (e.g. Predict Safe proxy) so that refunds\n * go back to that account rather than the EOA.\n */\n refundTo?: Hex;\n};\n\n/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Request passed to {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataRequest = {\n /** Amount of the source token in human-readable format. */\n amount: string;\n\n /** Metadata of the original transaction. */\n transaction: TransactionMeta;\n\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Response returned by {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataResponse = {\n /** Batch transaction params to prepend to the submit batch. */\n calls: BatchTransactionParams[];\n\n /** Optional recipient address for the funding token transfer. */\n recipient?: Hex;\n\n /** Optional EIP-7702 authorization list from delegation. */\n authorizationList?: AuthorizationList;\n};\n\n/**\n * Callback invoked during submit when `paymentOverride` is defined.\n * Returns batch transaction params to prepend to the submit batch.\n */\nexport type GetPaymentOverrideDataCallback = (\n request: GetPaymentOverrideDataRequest,\n) => Promise<GetPaymentOverrideDataResponse>;\n\nexport type GetAmountDataRequest = {\n /** Raw token amount (atomic units) to encode into calldata. */\n amount: string;\n\n /** Metadata of the transaction whose nested calls need updating. */\n transaction: TransactionMeta;\n};\n\nexport type GetAmountDataResponse = {\n /** Per-nested-call data updates; empty when no update is needed. */\n updates: { nestedTransactionIndex: number; data: Hex }[];\n};\n\n/**\n * Optional callback that re-encodes nested transaction calldata for a given\n * token amount. Used by transaction types with non-standard nested data\n * (e.g. vault approve + deposit) that cannot be derived from the amount alone\n * without client-side context (vault config, RPC providers, etc.).\n */\nexport type GetAmountDataCallback = (\n request: GetAmountDataRequest,\n) => Promise<GetAmountDataResponse>;\n\n/** Request passed to {@link GetBalanceCallback}. */\nexport type GetBalanceRequest = {\n /** Metadata of the transaction whose source balance is being resolved. */\n transaction: TransactionMeta;\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Balance override returned by {@link GetBalanceCallback}. */\nexport type GetBalanceResponse = {\n /** Balance in atomic format without factoring token decimals. */\n balanceRaw: string;\n};\n\n/**\n * Optional client-supplied callback that overrides the built-in\n * pay-token / required-token balance lookup used for `isMaxAmount`\n * source-amount calculation. Enables alternate balance sources\n * (perps, predict, money-account, post-quote, etc.) without adding\n * conditional branches inside the controller. MUST be synchronous:\n * it runs inside the controller state-update block.\n * Return `undefined` to fall back to the built-in token balance.\n */\nexport type GetBalanceCallback = (\n request: GetBalanceRequest,\n) => GetBalanceResponse | undefined;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /**\n * Identifies the MetaMask client, sent as the `X-Client-Id` header on\n * requests to the intents API so the server can distinguish Mobile from\n * Extension traffic.\n */\n clientId?: TransactionPayClientId;\n\n /** Optional callback to re-encode nested transaction calldata for a given amount. */\n getAmountData?: GetAmountDataCallback;\n\n /** Optional callback to override the source balance used for max-amount calculation. */\n getBalance?: GetBalanceCallback;\n\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** Optional fiat execution configuration. */\n fiatOptions?: TransactionPayFiatOptions;\n\n /**\n * Optional callback invoked during quote execution when `paymentOverride` is defined.\n * Returns additional transactions to be submitted alongside the quote batch.\n */\n getPaymentOverrideData?: GetPaymentOverrideDataCallback;\n\n /** Callback to select the PayStrategy for a transaction. */\n getStrategy?: (transaction: TransactionMeta) => TransactionPayStrategy;\n\n /** Callback to select ordered PayStrategies for a transaction. */\n getStrategies?: (transaction: TransactionMeta) => TransactionPayStrategy[];\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Callbacks for the Polymarket relayer; required only for the Polymarket deposit-wallet flow. */\n polymarket?: PolymarketCallbacks;\n\n /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** Optional fiat execution configuration. */\nexport type TransactionPayFiatOptions = {\n /** Test funding source used to bypass fiat on-ramp execution during local QA. */\n testFundingSource?: Hex;\n\n /** Optional human amount to transfer from the test funding source. */\n testAmountOverride?: string;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Fiat payment method state. */\n fiatPayment?: TransactionFiatPayment;\n\n /** Whether quotes are currently being retrieved. */\n isLoading: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n * Used when funds need to be moved after a transaction completes\n * (e.g., bridging output to a different token/chain).\n */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /**\n * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Most relevant structured validation error from the latest quote attempt. */\n quoteError?: QuoteErrorInfo;\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */\n caipAssetId?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/**\n * Machine-readable discriminator for a quote validation failure.\n *\n * Used for analytics and tests. Human-readable copy is carried by `message`\n * and `detail` on {@link QuoteErrorInfo}.\n */\nexport type QuoteErrorReason =\n /**\n * @deprecated No longer emitted. An unreadable live balance is treated as\n * unknown rather than insufficient, so it no longer blocks the quote. Kept\n * so existing consumers and historical analytics still type-check.\n */\n | 'balance-unavailable'\n | 'insufficient-source-balance'\n | 'insufficient-transfer-balance'\n | 'no-quotes'\n | 'simulation-failed';\n\n/**\n * Structured description of why a quote failed validation.\n *\n * `message` and `detail` are formatted (English) copy ready to display; `reason`\n * is a machine-readable discriminator for analytics and tests.\n */\nexport type QuoteErrorInfo = {\n /** Short, display-ready summary of the failure. */\n message: string;\n\n /** Machine-readable discriminator for the failure. */\n reason: QuoteErrorReason;\n\n /** Optional display-ready detail rows (e.g. Required / Current / Missing). */\n detail?: string[];\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /**\n * Selected account receiving post-quote output.\n * See {@link TransactionConfig.accountOverride}.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether this quote is the direct mUSD-to-Money-Account fiat flow. */\n isDirectMusdMoneyAccount?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** Optional recipient address for Relay requests. When set, overrides the default `from` address. */\n recipient?: Hex;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /** Whether to skip processTransactions in relay-quotes. Defaults to `isPostQuote`. */\n skipProcessTransactions?: boolean;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n\n /**\n * One-time HyperLiquid activation fee (USD) reserved from the source amount\n * for an unactivated HyperCore account. The source amount sent to the\n * provider is reduced by this amount so HyperLiquid retains enough balance\n * for the fee, and the amount is surfaced as part of the provider fee.\n */\n hyperliquidActivationFeeUsd?: string;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Whether fees are subtracted from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Whether the reported fees are already included in the source amount. */\n areFeesIncludedInSourceAmount?: boolean;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /**\n * Whether the target calls could not be embedded in the quote and must be\n * submitted separately, on the target chain, once the quote settles.\n *\n * Set by the strategy at quote time, since only it knows whether the provider\n * accepted the calls. {@link TransactionConfig.atomic} is a hint rather than\n * a guarantee: a quote requested atomically still falls back to a second leg\n * when the provider cannot execute the calls itself.\n */\n requiresSecondLeg?: boolean;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /**\n * Account sending the quotes: `txParams.from` for post-quote flows,\n * otherwise `accountOverride ?? txParams.from`. Pre-computed by the quote\n * orchestrator so that individual strategies do not need to re-derive it.\n */\n from: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** ID of the transaction whose refresh interval is being resolved. */\n transactionId: string;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Whether the selected quotes subtract fees from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n isSubsidized,\n}: {\n transaction: TransactionMeta;\n isSubsidized?: boolean;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** Client-supplied callbacks for the Polymarket relayer protocol. */\nexport type PolymarketCallbacks = {\n /** Derive the deposit-wallet address (CREATE2) for the given EOA. */\n getDepositWalletAddress: (params: { eoa: Hex }) => Promise<Hex>;\n\n /** Sign and broadcast a deposit-wallet batch, returning the source hash. */\n submitDepositWalletBatch: (params: {\n eoa: Hex;\n depositWallet: Hex;\n calls: { target: Hex; data: Hex; value: string }[];\n }) => Promise<{ sourceHash: Hex }>;\n};\n\n/** Single amount in alternate formats. */\nexport type Amount = FiatValue & {\n /** Amount in human-readable format factoring token decimals. */\n human: string;\n\n /** Amount in atomic format without factoring token decimals. */\n raw: string;\n};\n"]}
|
|
@@ -5,7 +5,8 @@ import type { QuoteRequest, TransactionPayControllerMessenger } from '../types.j
|
|
|
5
5
|
* Resolve the quote recipient used by both Relay and Server.
|
|
6
6
|
*
|
|
7
7
|
* Non-atomic execution must be funded on its execution account. Ordinary
|
|
8
|
-
* post-quote withdrawals pay the selected receiving account in
|
|
8
|
+
* post-quote withdrawals pay the selected receiving account in
|
|
9
|
+
* `request.accountOverride`, falling back to `request.from`.
|
|
9
10
|
* Deposits default to the original transaction's execution account.
|
|
10
11
|
*
|
|
11
12
|
* @param options - Recipient resolution options.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"quote-recipient.d.ts","sourceRoot":"","sources":["../../src/utils/quote-recipient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,KAAK,EACV,YAAY,EACZ,iCAAiC,EAClC,MAAM,aAAa,CAAC;AAGrB
|
|
1
|
+
{"version":3,"file":"quote-recipient.d.ts","sourceRoot":"","sources":["../../src/utils/quote-recipient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,KAAK,EACV,YAAY,EACZ,iCAAiC,EAClC,MAAM,aAAa,CAAC;AAGrB;;;;;;;;;;;;;GAaG;AACH,wBAAsB,qBAAqB,CAAC,EAC1C,SAAS,EACT,OAAO,EACP,WAAW,GACZ,EAAE;IACD,SAAS,EAAE,iCAAiC,CAAC;IAC7C,OAAO,EAAE,YAAY,CAAC;IACtB,WAAW,EAAE,eAAe,CAAC;CAC9B,GAAG,OAAO,CAAC,GAAG,CAAC,CA+Bf"}
|
|
@@ -3,7 +3,8 @@ import { getPostQuotePaymentOverrideData } from './post-quote-payment-override.j
|
|
|
3
3
|
* Resolve the quote recipient used by both Relay and Server.
|
|
4
4
|
*
|
|
5
5
|
* Non-atomic execution must be funded on its execution account. Ordinary
|
|
6
|
-
* post-quote withdrawals pay the selected receiving account in
|
|
6
|
+
* post-quote withdrawals pay the selected receiving account in
|
|
7
|
+
* `request.accountOverride`, falling back to `request.from`.
|
|
7
8
|
* Deposits default to the original transaction's execution account.
|
|
8
9
|
*
|
|
9
10
|
* @param options - Recipient resolution options.
|
|
@@ -33,7 +34,7 @@ export async function resolveQuoteRecipient({ messenger, request, transaction, }
|
|
|
33
34
|
if (request.isPostQuote) {
|
|
34
35
|
// Ordinary withdrawals pay the selected receiving account, which can differ
|
|
35
36
|
// from the account executing the source withdrawal.
|
|
36
|
-
return request.from;
|
|
37
|
+
return request.accountOverride ?? request.from;
|
|
37
38
|
}
|
|
38
39
|
// Deposits default to the execution account, which can differ from the payer.
|
|
39
40
|
return executionAccount;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"quote-recipient.js","sourceRoot":"","sources":["../../src/utils/quote-recipient.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,+BAA+B,EAAE,MAAM,kCAAkC,CAAC;AAEnF
|
|
1
|
+
{"version":3,"file":"quote-recipient.js","sourceRoot":"","sources":["../../src/utils/quote-recipient.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,+BAA+B,EAAE,MAAM,kCAAkC,CAAC;AAEnF;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,EAC1C,SAAS,EACT,OAAO,EACP,WAAW,GAKZ;IACC,MAAM,gBAAgB,GAAG,WAAW,CAAC,QAAQ,CAAC,IAAW,CAAC;IAE1D,IAAI,OAAO,CAAC,MAAM,KAAK,KAAK,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;QACpD,0EAA0E;QAC1E,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,+BAA+B,CAAC;YAC1D,SAAS;YACT,WAAW;SACZ,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,KAAK,KAAK,EAAE,CAAC;QAC7B,wEAAwE;QACxE,OAAO,gBAAgB,CAAC;IAC1B,CAAC;IAED,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;QACtB,4EAA4E;QAC5E,OAAO,OAAO,CAAC,SAAS,CAAC;IAC3B,CAAC;IAED,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;QACxB,4EAA4E;QAC5E,oDAAoD;QACpD,OAAO,OAAO,CAAC,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;IACjD,CAAC;IAED,8EAA8E;IAC9E,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport type {\n QuoteRequest,\n TransactionPayControllerMessenger,\n} from '../types.js';\nimport { getPostQuotePaymentOverrideData } from './post-quote-payment-override.js';\n\n/**\n * Resolve the quote recipient used by both Relay and Server.\n *\n * Non-atomic execution must be funded on its execution account. Ordinary\n * post-quote withdrawals pay the selected receiving account in\n * `request.accountOverride`, falling back to `request.from`.\n * Deposits default to the original transaction's execution account.\n *\n * @param options - Recipient resolution options.\n * @param options.messenger - Controller messenger.\n * @param options.request - Quote request.\n * @param options.transaction - Original transaction metadata.\n * @returns The recipient to use for the quote body.\n */\nexport async function resolveQuoteRecipient({\n messenger,\n request,\n transaction,\n}: {\n messenger: TransactionPayControllerMessenger;\n request: QuoteRequest;\n transaction: TransactionMeta;\n}): Promise<Hex> {\n const executionAccount = transaction.txParams.from as Hex;\n\n if (request.atomic === false && request.isPostQuote) {\n // The client identifies the account executing target-side override calls.\n const { recipient } = await getPostQuotePaymentOverrideData({\n messenger,\n transaction,\n });\n\n return recipient;\n }\n\n if (request.atomic === false) {\n // Fund the original execution account before submitting its second leg.\n return executionAccount;\n }\n\n if (request.recipient) {\n // Preserve an explicit payout recipient once second-leg funding is handled.\n return request.recipient;\n }\n\n if (request.isPostQuote) {\n // Ordinary withdrawals pay the selected receiving account, which can differ\n // from the account executing the source withdrawal.\n return request.accountOverride ?? request.from;\n }\n\n // Deposits default to the execution account, which can differ from the payer.\n return executionAccount;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"quotes.d.ts","sourceRoot":"","sources":["../../src/utils/quotes.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAIxE,OAAO,EAAmB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAE1E,OAAO,KAAK,EAGV,eAAe,EACf,kB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B,EAAE,EACzE,UAAU,CAAC,EAAE,kBAAkB,GAC9B,OAAO,CAAC,IAAI,CAAC,CA+Df"}
|
package/dist/utils/quotes.js
CHANGED
|
@@ -35,7 +35,7 @@ export async function updateQuotes(request) {
|
|
|
35
35
|
}
|
|
36
36
|
log('Updating quotes', { transactionId });
|
|
37
37
|
const { accountOverride, atomic, fiatPayment, isHyperliquidSource, isMaxAmount, isPolymarketDepositWallet, isPostQuote, isQuoteRequired, paymentOverride, paymentToken: originalPaymentToken, refundTo, sourceAmounts, tokens, } = transactionData;
|
|
38
|
-
const from =
|
|
38
|
+
const from = getFrom(transaction, transactionData);
|
|
39
39
|
const controller = abortPreviousAndCreateController(transactionId);
|
|
40
40
|
const { signal } = controller;
|
|
41
41
|
updateTransactionData(transactionId, (data) => {
|
|
@@ -44,7 +44,8 @@ export async function updateQuotes(request) {
|
|
|
44
44
|
});
|
|
45
45
|
try {
|
|
46
46
|
const paymentToken = await refreshPaymentTokenBalance({
|
|
47
|
-
|
|
47
|
+
// Post-quote payment tokens are received by `accountOverride`.
|
|
48
|
+
from: accountOverride ?? transaction.txParams.from,
|
|
48
49
|
messenger,
|
|
49
50
|
paymentToken: originalPaymentToken,
|
|
50
51
|
signal,
|
|
@@ -62,6 +63,7 @@ export async function updateQuotes(request) {
|
|
|
62
63
|
// loaded.
|
|
63
64
|
const latestSourceAmounts = getSourceAmounts(messenger, transactionId) ?? sourceAmounts;
|
|
64
65
|
const requests = buildQuoteRequests({
|
|
66
|
+
accountOverride,
|
|
65
67
|
atomic,
|
|
66
68
|
from,
|
|
67
69
|
isHyperliquidSource,
|
|
@@ -129,6 +131,21 @@ export async function updateQuotes(request) {
|
|
|
129
131
|
}
|
|
130
132
|
return true;
|
|
131
133
|
}
|
|
134
|
+
/**
|
|
135
|
+
* Get the account that sends quotes for a transaction.
|
|
136
|
+
*
|
|
137
|
+
* @param transaction - Transaction metadata.
|
|
138
|
+
* @param transactionData - Transaction pay data.
|
|
139
|
+
* @returns The quote sender address.
|
|
140
|
+
*/
|
|
141
|
+
function getFrom(transaction, transactionData) {
|
|
142
|
+
const transactionFrom = transaction.txParams.from;
|
|
143
|
+
// Post-quote output goes to `accountOverride`, so the funds holder sends.
|
|
144
|
+
if (transactionData.isPostQuote) {
|
|
145
|
+
return transactionFrom;
|
|
146
|
+
}
|
|
147
|
+
return transactionData.accountOverride ?? transactionFrom;
|
|
148
|
+
}
|
|
132
149
|
/**
|
|
133
150
|
* Sync batch transactions to the transaction meta.
|
|
134
151
|
*
|
|
@@ -260,6 +277,7 @@ function getSourceAmounts(messenger, transactionId) {
|
|
|
260
277
|
* Build quote requests required to retrieve quotes.
|
|
261
278
|
*
|
|
262
279
|
* @param request - Request parameters.
|
|
280
|
+
* @param request.accountOverride - Optional account receiving post-quote output.
|
|
263
281
|
* @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.
|
|
264
282
|
* @param request.from - Address from which the transaction is sent.
|
|
265
283
|
* @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.
|
|
@@ -274,12 +292,13 @@ function getSourceAmounts(messenger, transactionId) {
|
|
|
274
292
|
* @param request.transactionId - ID of the transaction.
|
|
275
293
|
* @returns Array of quote requests.
|
|
276
294
|
*/
|
|
277
|
-
function buildQuoteRequests({ atomic, from, isHyperliquidSource, isMaxAmount, isPolymarketDepositWallet, isPostQuote, paymentOverride, paymentToken, refundTo, sourceAmounts, tokens, transactionId, }) {
|
|
295
|
+
function buildQuoteRequests({ accountOverride, atomic, from, isHyperliquidSource, isMaxAmount, isPolymarketDepositWallet, isPostQuote, paymentOverride, paymentToken, refundTo, sourceAmounts, tokens, transactionId, }) {
|
|
278
296
|
if (!paymentToken) {
|
|
279
297
|
return [];
|
|
280
298
|
}
|
|
281
299
|
if (isPostQuote) {
|
|
282
300
|
return buildPostQuoteRequests({
|
|
301
|
+
accountOverride,
|
|
283
302
|
atomic,
|
|
284
303
|
destinationToken: paymentToken,
|
|
285
304
|
from,
|
|
@@ -321,6 +340,7 @@ function buildQuoteRequests({ atomic, from, isHyperliquidSource, isMaxAmount, is
|
|
|
321
340
|
* and the target is the user's selected destination token (paymentToken).
|
|
322
341
|
*
|
|
323
342
|
* @param request - Request parameters.
|
|
343
|
+
* @param request.accountOverride - Optional account receiving the output.
|
|
324
344
|
* @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.
|
|
325
345
|
* @param request.destinationToken - Destination token (paymentToken in post-quote mode).
|
|
326
346
|
* @param request.from - Address from which the transaction is sent.
|
|
@@ -333,7 +353,7 @@ function buildQuoteRequests({ atomic, from, isHyperliquidSource, isMaxAmount, is
|
|
|
333
353
|
* @param request.transactionId - ID of the transaction.
|
|
334
354
|
* @returns Array of quote requests for post-quote flow.
|
|
335
355
|
*/
|
|
336
|
-
function buildPostQuoteRequests({ atomic, destinationToken, from, isHyperliquidSource, isMaxAmount, isPolymarketDepositWallet, paymentOverride, refundTo, sourceAmounts, transactionId, }) {
|
|
356
|
+
function buildPostQuoteRequests({ accountOverride, atomic, destinationToken, from, isHyperliquidSource, isMaxAmount, isPolymarketDepositWallet, paymentOverride, refundTo, sourceAmounts, transactionId, }) {
|
|
337
357
|
// Find the source amount where targetTokenAddress matches the destination token
|
|
338
358
|
const sourceAmount = sourceAmounts?.find((amount) => amount.targetTokenAddress.toLowerCase() ===
|
|
339
359
|
destinationToken.address.toLowerCase());
|
|
@@ -347,6 +367,7 @@ function buildPostQuoteRequests({ atomic, destinationToken, from, isHyperliquidS
|
|
|
347
367
|
return [];
|
|
348
368
|
}
|
|
349
369
|
const request = {
|
|
370
|
+
accountOverride,
|
|
350
371
|
atomic,
|
|
351
372
|
from,
|
|
352
373
|
isHyperliquidSource,
|
|
@@ -405,7 +426,7 @@ async function refreshPaymentTokenBalance({ from, messenger, paymentToken, signa
|
|
|
405
426
|
* Retrieve quotes for a transaction.
|
|
406
427
|
*
|
|
407
428
|
* @param transaction - Transaction metadata.
|
|
408
|
-
* @param from -
|
|
429
|
+
* @param from - Sending wallet address (`txParams.from` for post-quote, otherwise `accountOverride ?? txParams.from`).
|
|
409
430
|
* @param requests - Quote requests.
|
|
410
431
|
* @param paymentToken - Selected payment token, if any.
|
|
411
432
|
* @param isQuoteRequired - Whether a quote is always required for the transaction.
|
package/dist/utils/quotes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"quotes.js","sourceRoot":"","sources":["../../src/utils/quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAIrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAmB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAc7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,wBAAwB,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,aAAa;AAEzD,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;AAExD,MAAM,qBAAqB,GAAG,IAAI,GAAG,EAA2B,CAAC;AAUjE;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,OAA4B;IAE5B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OAAO,EAAE,CAAC;gBACpB,MAAM,WAAW,CAAC;YACpB,CAAC;YAED,KAAK,KAAK,YAAY,CAAC,WAAW,CAAC;gBACjC,CAAC,CAAC,WAAW,CAAC,IAAI;gBAClB,CAAC,CAAC,EAAE,OAAO,EAAG,WAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;YAErE,IACE,YAAY,CAAC,WAAW,CAAC;gBACzB,WAAW,CAAC,IAAI,CAAC,MAAM,KAAK,6BAA6B;gBACzD,WAAW,CAAC,MAAM,EAAE,MAAM,EAC1B,CAAC;gBACD,GAAG,CAAC,oDAAoD,EAAE;oBACxD,QAAQ,EAAE,IAAI;oBACd,aAAa;iBACd,CAAC,CAAC;gBACH,OAAO;oBACL,iBAAiB,EAAE,EAAE;oBACrB,KAAK,EAAE,WAAW,CAAC,IAAI;oBACvB,MAAM,EAAE,WAAW,CAAC,MAAqC;iBAC1D,CAAC;YACJ,CAAC;YAED,GAAG,CAAC,8BAA8B,EAAE;gBAClC,KAAK,EAAE,WAAW;gBAClB,QAAQ,EAAE,IAAI;gBACd,aAAa;aACd,CAAC,CAAC;YACH,SAAS;QACX,CAAC;IACH,CAAC;IAED,GAAG,CAAC,qBAAqB,EAAE,EAAE,aAAa,EAAE,CAAC,CAAC;IAE9C,OAAO;QACL,iBAAiB,EAAE,EAAE;QACrB,KAAK;QACL,MAAM,EAAE,EAAE;KACX,CAAC;AACJ,CAAC","sourcesContent":["import { TransactionStatus } from '@metamask/transaction-controller';\nimport type { BatchTransaction } from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { PaymentOverride, TransactionPayStrategy } from '../constants.js';\nimport { projectLogger } from '../logger.js';\nimport type {\n QuoteRequest,\n QuoteErrorInfo,\n TransactionData,\n GetBalanceCallback,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPaySourceAmount,\n TransactionPayTotals,\n TransactionPaymentToken,\n UpdateTransactionDataCallback,\n} from '../types.js';\nimport { accountSupports7702 } from './7702.js';\nimport { buildNoOpQuote } from './no-op-quote.js';\nimport { updateSourceAmounts } from './source-amounts.js';\nimport {\n checkStrategyQuoteSupport,\n checkStrategySupport,\n getStrategiesByName,\n getStrategyByName,\n} from './strategy.js';\nimport {\n computeTokenAmounts,\n getLiveTokenBalance,\n getTokenFiatRate,\n} from './token.js';\nimport { calculateTotals } from './totals.js';\nimport { getTransaction, updateTransaction } from './transaction.js';\nimport { isQuoteError } from './validation.js';\n\nconst DEFAULT_REFRESH_INTERVAL = 30 * 1000; // 30 Seconds\n\nconst log = createModuleLogger(projectLogger, 'quotes');\n\nconst inFlightQuoteRequests = new Map<string, AbortController>();\n\nexport type UpdateQuotesRequest = {\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[];\n messenger: TransactionPayControllerMessenger;\n transactionData: TransactionData | undefined;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n};\n\n/**\n * Update the quotes for a specific transaction.\n *\n * Calls for the same `transactionId` are serialised: a fresh call aborts any\n * previous in-flight call so a slower stale response cannot overwrite a newer\n * one in state.\n *\n * @param request - Request parameters.\n * @returns Boolean indicating if the quotes were updated. Returns `false` when\n * the call was aborted by a subsequent call for the same transaction.\n */\nexport async function updateQuotes(\n request: UpdateQuotesRequest,\n): Promise<boolean> {\n const {\n getStrategies,\n messenger,\n transactionData,\n transactionId,\n updateTransactionData,\n } = request;\n\n const transaction = getTransaction(transactionId, messenger);\n\n if (!transaction || !transactionData) {\n throw new Error('Transaction not found');\n }\n\n if (transaction?.status !== TransactionStatus.unapproved) {\n return false;\n }\n\n log('Updating quotes', { transactionId });\n\n const {\n accountOverride,\n atomic,\n fiatPayment,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n isQuoteRequired,\n paymentOverride,\n paymentToken: originalPaymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n } = transactionData;\n\n const from = accountOverride ?? (transaction.txParams.from as Hex);\n\n const controller = abortPreviousAndCreateController(transactionId);\n const { signal } = controller;\n\n updateTransactionData(transactionId, (data) => {\n data.isLoading = true;\n data.quoteError = undefined;\n });\n\n try {\n const paymentToken = await refreshPaymentTokenBalance({\n from,\n messenger,\n paymentToken: originalPaymentToken,\n signal,\n transactionId,\n updateTransactionData,\n });\n\n if (signal.aborted) {\n log('Quote request aborted before building requests', { transactionId });\n return false;\n }\n\n // Refreshing the balance above re-derives max source amounts, so read the\n // latest values instead of the snapshot taken before the refresh. Using\n // the snapshot quotes a max amount against a stale balance, which requests\n // a zero source amount when the token was selected before its balance\n // loaded.\n const latestSourceAmounts =\n getSourceAmounts(messenger, transactionId) ?? sourceAmounts;\n\n const requests = buildQuoteRequests({\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount: isMaxAmount ?? false,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts: latestSourceAmounts,\n tokens,\n transactionId,\n });\n\n const supports7702 = accountSupports7702(messenger, from);\n\n const { batchTransactions, error, quotes } = await getQuotes(\n transaction,\n from,\n requests,\n paymentToken,\n isQuoteRequired ?? false,\n supports7702,\n getStrategies,\n messenger,\n fiatPayment?.selectedPaymentMethodId,\n signal,\n );\n\n if (signal.aborted) {\n log('Quote request aborted before persisting results', { transactionId });\n return false;\n }\n\n // No-op quotes mark direct routes. They have no fees or amounts and the\n // transaction is signed and submitted locally, so totals and transaction\n // sync must treat them as \"no quotes\".\n const executableQuotes = quotes.filter(\n (quote) => quote.strategy !== TransactionPayStrategy.None,\n );\n\n const totals = calculateTotals({\n fiatPaymentAmount: fiatPayment?.amountFiat,\n messenger,\n quotes: executableQuotes,\n tokens,\n transaction,\n });\n\n log('Calculated totals', { transactionId, totals });\n\n syncTransaction({\n batchTransactions,\n selectedFiatPayment: fiatPayment?.selectedPaymentMethodId,\n hasQuotes: executableQuotes.length > 0,\n isPostQuote,\n messenger,\n paymentToken,\n strategy: executableQuotes[0]?.strategy,\n totals,\n transactionId,\n });\n\n updateTransactionData(transactionId, (data) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n data.quotes = quotes as never;\n data.quoteError = error;\n data.quotesLastUpdated = Date.now();\n data.totals = totals;\n });\n } catch (error) {\n if (signal.aborted) {\n log('Quote request aborted', { transactionId, reason: signal.reason });\n return false;\n }\n throw error;\n } finally {\n if (!signal.aborted) {\n updateTransactionData(transactionId, (data) => {\n data.isLoading = false;\n });\n }\n clearControllerIfCurrent(transactionId, controller);\n }\n\n return true;\n}\n\n/**\n * Sync batch transactions to the transaction meta.\n *\n * @param request - Request object.\n * @param request.batchTransactions - Batch transactions to sync.\n * @param request.hasQuotes - Whether MM Pay produced any quotes for this transaction.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.messenger - Messenger instance.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.selectedFiatPayment - Selected fiat payment method ID.\n * @param request.strategy - Strategy of the executable quotes.\n * @param request.totals - Calculated totals.\n * @param request.transactionId - ID of the transaction to sync.\n */\nfunction syncTransaction({\n batchTransactions,\n hasQuotes,\n isPostQuote,\n messenger,\n paymentToken,\n selectedFiatPayment,\n strategy,\n totals,\n transactionId,\n}: {\n batchTransactions: BatchTransaction[];\n selectedFiatPayment?: string;\n hasQuotes: boolean;\n isPostQuote?: boolean;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n strategy?: TransactionPayStrategy;\n totals: TransactionPayTotals;\n transactionId: string;\n}): void {\n if (!paymentToken && !selectedFiatPayment) {\n return;\n }\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Update transaction pay data',\n },\n (tx: TransactionMeta) => {\n tx.batchTransactions = batchTransactions;\n tx.batchTransactionsOptions = {};\n\n // When MM Pay has produced quotes, it owns submission of this transaction\n // via its strategy publish hook, so the parent must be marked externally\n // signed to skip the local `KeyringController:signTransaction` call.\n // When there are no quotes (e.g. user selected the target token as the\n // payment token in a Predict flow), the transaction falls back to normal\n // local signing, so the flag is cleared to allow that.\n // If gas is sponsored, TC owns this field — it is set based on the\n // Sentinel simulation result and must not be cleared here. Same-token\n // flows (e.g. Monad mUSD withdrawal via a Money Account) produce no\n // quotes but still need external sign because the account cannot sign\n // locally.\n if (!tx.isGasFeeSponsored) {\n tx.isExternalSign = hasQuotes;\n }\n\n tx.metamaskPay = {\n bridgeFeeFiat: totals.fees.provider.usd,\n chainId: paymentToken?.chainId,\n isPostQuote,\n networkFeeFiat: totals.fees.sourceNetwork.estimate.usd,\n strategy,\n targetFiat: totals.targetAmount.usd,\n tokenAddress: paymentToken?.address,\n totalFiat: totals.total.usd,\n };\n },\n );\n}\n\n/**\n * Refresh source amounts and quotes for all transactions if expired.\n *\n * @param messenger - Messenger instance.\n * @param updateTransactionData - Callback to update transaction data.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n * @param getBalance - Optional callback to override the source balance used for max-amount calculation.\n */\nexport async function refreshQuotes(\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n getBalance?: GetBalanceCallback,\n): Promise<void> {\n const state = messenger.call('TransactionPayController:getState');\n const transactionIds = Object.keys(state.transactionData);\n\n for (const transactionId of transactionIds) {\n const transactionData = state.transactionData[transactionId];\n const { isLoading, quotes, quotesLastUpdated } = transactionData;\n\n if (isLoading || !quotes?.length) {\n continue;\n }\n\n // No-op quotes mark direct routes and have nothing to refresh. They are\n // regenerated whenever the transaction data changes.\n if (\n quotes.every((quote) => quote.strategy === TransactionPayStrategy.None)\n ) {\n continue;\n }\n\n const strategyName = quotes[0].strategy;\n const strategy = getStrategyByName(strategyName);\n\n const refreshInterval =\n (await strategy.getRefreshInterval?.({\n chainId: quotes[0].request.sourceChainId,\n messenger,\n transactionId,\n })) ?? DEFAULT_REFRESH_INTERVAL;\n\n const isExpired = Date.now() - (quotesLastUpdated ?? 0) > refreshInterval;\n\n if (!isExpired) {\n continue;\n }\n\n updateTransactionData(transactionId, (data) =>\n updateSourceAmounts(\n transactionId,\n /* oxlint-disable typescript/no-unnecessary-type-assertion */\n data as never,\n /* oxlint-enable typescript/no-unnecessary-type-assertion */\n messenger,\n getBalance,\n ),\n );\n\n const latestTransactionData = messenger.call(\n 'TransactionPayController:getState',\n ).transactionData[transactionId];\n\n const isUpdated = await updateQuotes({\n getStrategies,\n messenger,\n transactionData: latestTransactionData,\n transactionId,\n updateTransactionData,\n });\n\n if (isUpdated) {\n log('Refreshed quotes', { transactionId, strategy: strategyName });\n }\n }\n}\n\nfunction abortPreviousAndCreateController(\n transactionId: string,\n): AbortController {\n const previous = inFlightQuoteRequests.get(transactionId);\n\n if (previous && !previous.signal.aborted) {\n log('Aborting previous quote request', { transactionId });\n previous.abort(new Error('Superseded by newer quote request'));\n }\n\n const controller = new AbortController();\n inFlightQuoteRequests.set(transactionId, controller);\n return controller;\n}\n\nfunction clearControllerIfCurrent(\n transactionId: string,\n controller: AbortController,\n): void {\n if (inFlightQuoteRequests.get(transactionId) === controller) {\n inFlightQuoteRequests.delete(transactionId);\n }\n}\n\n/**\n * Read the current source amounts for a transaction from controller state.\n *\n * @param messenger - Messenger instance.\n * @param transactionId - ID of the transaction.\n * @returns The source amounts, or `undefined` if the transaction has none.\n */\nfunction getSourceAmounts(\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n): TransactionPaySourceAmount[] | undefined {\n return messenger.call('TransactionPayController:getState').transactionData[\n transactionId\n ]?.sourceAmounts;\n}\n\n/**\n * Build quote requests required to retrieve quotes.\n *\n * @param request - Request parameters.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction.\n * @param request.tokens - Required tokens for the transaction.\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests.\n */\nfunction buildQuoteRequests({\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n transactionId,\n}: {\n atomic?: boolean;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n isPostQuote?: boolean;\n paymentOverride?: PaymentOverride;\n paymentToken: TransactionPaymentToken | undefined;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n tokens: TransactionPayRequiredToken[];\n transactionId: string;\n}): QuoteRequest[] {\n if (!paymentToken) {\n return [];\n }\n\n if (isPostQuote) {\n return buildPostQuoteRequests({\n atomic,\n destinationToken: paymentToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n });\n }\n\n // Standard flow: source = paymentToken, target = required tokens\n const requests = (sourceAmounts ?? []).map((sourceAmount) => {\n const token = tokens.find(\n (singleToken) => singleToken.address === sourceAmount.targetTokenAddress,\n ) as TransactionPayRequiredToken;\n\n return {\n atomic,\n from,\n isMaxAmount,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: paymentToken.balanceRaw,\n sourceChainId: paymentToken.chainId,\n sourceTokenAddress: paymentToken.address,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: token.allowUnderMinimum ? '0' : token.amountRaw,\n targetChainId: token.chainId,\n targetTokenAddress: token.address,\n };\n });\n\n if (!requests.length) {\n log('No quote requests', { transactionId });\n }\n\n return requests;\n}\n\n/**\n * Build quote requests for post-quote flows.\n * In this flow, the source is the transaction's required token,\n * and the target is the user's selected destination token (paymentToken).\n *\n * @param request - Request parameters.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.destinationToken - Destination token (paymentToken in post-quote mode).\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction (includes source token info).\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests for post-quote flow.\n */\nfunction buildPostQuoteRequests({\n atomic,\n destinationToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n}: {\n atomic?: boolean;\n destinationToken: TransactionPaymentToken;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n paymentOverride?: PaymentOverride;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n transactionId: string;\n}): QuoteRequest[] {\n // Find the source amount where targetTokenAddress matches the destination token\n const sourceAmount = sourceAmounts?.find(\n (amount) =>\n amount.targetTokenAddress.toLowerCase() ===\n destinationToken.address.toLowerCase(),\n );\n\n // Same-token-same-chain cases are already filtered in source-amounts.ts\n if (\n !sourceAmount?.sourceBalanceRaw ||\n !sourceAmount.sourceChainId ||\n !sourceAmount.sourceTokenAddress\n ) {\n log('No valid source amount found for post-quote request', {\n transactionId,\n });\n return [];\n }\n\n const request: QuoteRequest = {\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote: true,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: sourceAmount.sourceBalanceRaw,\n sourceChainId: sourceAmount.sourceChainId,\n sourceTokenAddress: sourceAmount.sourceTokenAddress,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: '0',\n targetChainId: destinationToken.chainId,\n targetTokenAddress: destinationToken.address,\n };\n\n log('Post-quote request built', { transactionId, request });\n\n // Currently only single token post-quote flows are supported.\n // Multiple token support would require multiple quotes for each required token.\n return [request];\n}\n\nasync function refreshPaymentTokenBalance({\n from,\n messenger,\n paymentToken,\n signal,\n transactionId,\n updateTransactionData,\n}: {\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n signal: AbortSignal;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n}): Promise<TransactionPaymentToken | undefined> {\n if (!paymentToken) {\n return undefined;\n }\n\n try {\n const fiatRates = getTokenFiatRate(\n messenger,\n paymentToken.address,\n paymentToken.chainId,\n );\n\n if (!fiatRates) {\n return paymentToken;\n }\n\n const liveBalance = await getLiveTokenBalance(\n messenger,\n from,\n paymentToken.chainId,\n paymentToken.address,\n );\n\n if (signal.aborted) {\n log('Payment token balance refresh aborted', { transactionId });\n return paymentToken;\n }\n\n const {\n raw: balanceRaw,\n human: balanceHuman,\n usd: balanceUsd,\n fiat: balanceFiat,\n } = computeTokenAmounts(liveBalance, paymentToken.decimals, fiatRates);\n\n const updatedToken = {\n ...paymentToken,\n balanceFiat,\n balanceHuman,\n balanceRaw,\n balanceUsd,\n };\n\n updateTransactionData(transactionId, (data) => {\n data.paymentToken = updatedToken;\n });\n\n log('Refreshed payment token balance', { transactionId, balanceRaw });\n\n return updatedToken;\n } catch (error) {\n log('Failed to refresh payment token balance', { transactionId, error });\n return paymentToken;\n }\n}\n\n/**\n * Retrieve quotes for a transaction.\n *\n * @param transaction - Transaction metadata.\n * @param from - Resolved wallet address (`accountOverride ?? txParams.from`).\n * @param requests - Quote requests.\n * @param paymentToken - Selected payment token, if any.\n * @param isQuoteRequired - Whether a quote is always required for the transaction.\n * @param isAccountEIP7702Compatible - Whether the account supports EIP-7702.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n * @param messenger - Controller messenger.\n * @param fiatPaymentMethod - Selected fiat payment method ID, if applicable.\n * @param signal - Signal that aborts when the quote request is superseded.\n * @returns An object containing batch transactions and quotes.\n */\nasync function getQuotes(\n transaction: TransactionMeta,\n from: Hex,\n requests: QuoteRequest[],\n paymentToken: TransactionPaymentToken | undefined,\n isQuoteRequired: boolean,\n isAccountEIP7702Compatible: boolean,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n messenger: TransactionPayControllerMessenger,\n fiatPaymentMethod?: string,\n signal?: AbortSignal,\n): Promise<{\n batchTransactions: BatchTransaction[];\n error?: QuoteErrorInfo;\n quotes: TransactionPayQuote<Json>[];\n}> {\n const { id: transactionId } = transaction;\n const strategies = getStrategiesByName(\n getStrategies(transaction),\n (strategyName) => {\n log('Skipping unknown strategy', {\n strategy: strategyName,\n transactionId,\n });\n },\n );\n\n if (!requests?.length && !fiatPaymentMethod) {\n // A selected payment token with no conversion requests means the route is\n // direct. Return an explicit no-op quote so clients and the publish hook\n // can distinguish \"no conversion needed\" from \"quote needed but missing\".\n // Not applicable when a quote is always required, as an empty requests\n // list then means the source amounts could not be calculated.\n const noOpQuote =\n paymentToken && !isQuoteRequired\n ? buildNoOpQuote(from, paymentToken)\n : undefined;\n\n if (noOpQuote) {\n log('Built no-op quote for direct route', { transactionId });\n }\n\n return {\n batchTransactions: [],\n quotes: noOpQuote ? [noOpQuote] : [],\n };\n }\n\n const request = {\n accountSupports7702: isAccountEIP7702Compatible,\n fiatPaymentMethod,\n from,\n messenger,\n requests,\n signal,\n transaction,\n };\n\n let error: QuoteErrorInfo | undefined;\n\n for (const { name, strategy } of strategies) {\n try {\n const support = await checkStrategySupport(strategy, request);\n\n if (!support) {\n log('Strategy does not support request', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n const quotes = (await strategy.getQuotes(\n request,\n )) as TransactionPayQuote<Json>[];\n\n if (!quotes.length) {\n log('Strategy returned no quotes', { strategy: name, transactionId });\n continue;\n }\n\n const isQuoteSupported = await checkStrategyQuoteSupport(strategy, {\n messenger,\n quotes,\n signal,\n transaction,\n });\n\n if (!isQuoteSupported) {\n log('Strategy does not support quotes', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n log('Updated', { transactionId, quotes });\n\n const batchTransactions = strategy.getBatchTransactions\n ? await strategy.getBatchTransactions({\n messenger,\n quotes,\n signal,\n })\n : [];\n\n log('Batch transactions', { transactionId, batchTransactions });\n\n return {\n batchTransactions,\n quotes,\n };\n } catch (caughtError) {\n if (signal?.aborted) {\n throw caughtError;\n }\n\n error ??= isQuoteError(caughtError)\n ? caughtError.info\n : { message: (caughtError as Error).message, reason: 'no-quotes' };\n\n if (\n isQuoteError(caughtError) &&\n caughtError.info.reason === 'insufficient-source-balance' &&\n caughtError.quotes?.length\n ) {\n log('Keeping quotes despite insufficient source balance', {\n strategy: name,\n transactionId,\n });\n return {\n batchTransactions: [],\n error: caughtError.info,\n quotes: caughtError.quotes as TransactionPayQuote<Json>[],\n };\n }\n\n log('Strategy failed, trying next', {\n error: caughtError,\n strategy: name,\n transactionId,\n });\n continue;\n }\n }\n\n log('No quotes available', { transactionId });\n\n return {\n batchTransactions: [],\n error,\n quotes: [],\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"quotes.js","sourceRoot":"","sources":["../../src/utils/quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAIrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAmB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAc7C,OAAO,EAA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C,CAAC,CAAC,WAAW,CAAC,IAAI;gBAClB,CAAC,CAAC,EAAE,OAAO,EAAG,WAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;YAErE,IACE,YAAY,CAAC,WAAW,CAAC;gBACzB,WAAW,CAAC,IAAI,CAAC,MAAM,KAAK,6BAA6B;gBACzD,WAAW,CAAC,MAAM,EAAE,MAAM,EAC1B,CAAC;gBACD,GAAG,CAAC,oDAAoD,EAAE;oBACxD,QAAQ,EAAE,IAAI;oBACd,aAAa;iBACd,CAAC,CAAC;gBACH,OAAO;oBACL,iBAAiB,EAAE,EAAE;oBACrB,KAAK,EAAE,WAAW,CAAC,IAAI;oBACvB,MAAM,EAAE,WAAW,CAAC,MAAqC;iBAC1D,CAAC;YACJ,CAAC;YAED,GAAG,CAAC,8BAA8B,EAAE;gBAClC,KAAK,EAAE,WAAW;gBAClB,QAAQ,EAAE,IAAI;gBACd,aAAa;aACd,CAAC,CAAC;YACH,SAAS;QACX,CAAC;IACH,CAAC;IAED,GAAG,CAAC,qBAAqB,EAAE,EAAE,aAAa,EAAE,CAAC,CAAC;IAE9C,OAAO;QACL,iBAAiB,EAAE,EAAE;QACrB,KAAK;QACL,MAAM,EAAE,EAAE;KACX,CAAC;AACJ,CAAC","sourcesContent":["import { TransactionStatus } from '@metamask/transaction-controller';\nimport type { BatchTransaction } from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { PaymentOverride, TransactionPayStrategy } from '../constants.js';\nimport { projectLogger } from '../logger.js';\nimport type {\n QuoteRequest,\n QuoteErrorInfo,\n TransactionData,\n GetBalanceCallback,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPaySourceAmount,\n TransactionPayTotals,\n TransactionPaymentToken,\n UpdateTransactionDataCallback,\n} from '../types.js';\nimport { accountSupports7702 } from './7702.js';\nimport { buildNoOpQuote } from './no-op-quote.js';\nimport { updateSourceAmounts } from './source-amounts.js';\nimport {\n checkStrategyQuoteSupport,\n checkStrategySupport,\n getStrategiesByName,\n getStrategyByName,\n} from './strategy.js';\nimport {\n computeTokenAmounts,\n getLiveTokenBalance,\n getTokenFiatRate,\n} from './token.js';\nimport { calculateTotals } from './totals.js';\nimport { getTransaction, updateTransaction } from './transaction.js';\nimport { isQuoteError } from './validation.js';\n\nconst DEFAULT_REFRESH_INTERVAL = 30 * 1000; // 30 Seconds\n\nconst log = createModuleLogger(projectLogger, 'quotes');\n\nconst inFlightQuoteRequests = new Map<string, AbortController>();\n\nexport type UpdateQuotesRequest = {\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[];\n messenger: TransactionPayControllerMessenger;\n transactionData: TransactionData | undefined;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n};\n\n/**\n * Update the quotes for a specific transaction.\n *\n * Calls for the same `transactionId` are serialised: a fresh call aborts any\n * previous in-flight call so a slower stale response cannot overwrite a newer\n * one in state.\n *\n * @param request - Request parameters.\n * @returns Boolean indicating if the quotes were updated. Returns `false` when\n * the call was aborted by a subsequent call for the same transaction.\n */\nexport async function updateQuotes(\n request: UpdateQuotesRequest,\n): Promise<boolean> {\n const {\n getStrategies,\n messenger,\n transactionData,\n transactionId,\n updateTransactionData,\n } = request;\n\n const transaction = getTransaction(transactionId, messenger);\n\n if (!transaction || !transactionData) {\n throw new Error('Transaction not found');\n }\n\n if (transaction?.status !== TransactionStatus.unapproved) {\n return false;\n }\n\n log('Updating quotes', { transactionId });\n\n const {\n accountOverride,\n atomic,\n fiatPayment,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n isQuoteRequired,\n paymentOverride,\n paymentToken: originalPaymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n } = transactionData;\n\n const from = getFrom(transaction, transactionData);\n\n const controller = abortPreviousAndCreateController(transactionId);\n const { signal } = controller;\n\n updateTransactionData(transactionId, (data) => {\n data.isLoading = true;\n data.quoteError = undefined;\n });\n\n try {\n const paymentToken = await refreshPaymentTokenBalance({\n // Post-quote payment tokens are received by `accountOverride`.\n from: accountOverride ?? (transaction.txParams.from as Hex),\n messenger,\n paymentToken: originalPaymentToken,\n signal,\n transactionId,\n updateTransactionData,\n });\n\n if (signal.aborted) {\n log('Quote request aborted before building requests', { transactionId });\n return false;\n }\n\n // Refreshing the balance above re-derives max source amounts, so read the\n // latest values instead of the snapshot taken before the refresh. Using\n // the snapshot quotes a max amount against a stale balance, which requests\n // a zero source amount when the token was selected before its balance\n // loaded.\n const latestSourceAmounts =\n getSourceAmounts(messenger, transactionId) ?? sourceAmounts;\n\n const requests = buildQuoteRequests({\n accountOverride,\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount: isMaxAmount ?? false,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts: latestSourceAmounts,\n tokens,\n transactionId,\n });\n\n const supports7702 = accountSupports7702(messenger, from);\n\n const { batchTransactions, error, quotes } = await getQuotes(\n transaction,\n from,\n requests,\n paymentToken,\n isQuoteRequired ?? false,\n supports7702,\n getStrategies,\n messenger,\n fiatPayment?.selectedPaymentMethodId,\n signal,\n );\n\n if (signal.aborted) {\n log('Quote request aborted before persisting results', { transactionId });\n return false;\n }\n\n // No-op quotes mark direct routes. They have no fees or amounts and the\n // transaction is signed and submitted locally, so totals and transaction\n // sync must treat them as \"no quotes\".\n const executableQuotes = quotes.filter(\n (quote) => quote.strategy !== TransactionPayStrategy.None,\n );\n\n const totals = calculateTotals({\n fiatPaymentAmount: fiatPayment?.amountFiat,\n messenger,\n quotes: executableQuotes,\n tokens,\n transaction,\n });\n\n log('Calculated totals', { transactionId, totals });\n\n syncTransaction({\n batchTransactions,\n selectedFiatPayment: fiatPayment?.selectedPaymentMethodId,\n hasQuotes: executableQuotes.length > 0,\n isPostQuote,\n messenger,\n paymentToken,\n strategy: executableQuotes[0]?.strategy,\n totals,\n transactionId,\n });\n\n updateTransactionData(transactionId, (data) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n data.quotes = quotes as never;\n data.quoteError = error;\n data.quotesLastUpdated = Date.now();\n data.totals = totals;\n });\n } catch (error) {\n if (signal.aborted) {\n log('Quote request aborted', { transactionId, reason: signal.reason });\n return false;\n }\n throw error;\n } finally {\n if (!signal.aborted) {\n updateTransactionData(transactionId, (data) => {\n data.isLoading = false;\n });\n }\n clearControllerIfCurrent(transactionId, controller);\n }\n\n return true;\n}\n\n/**\n * Get the account that sends quotes for a transaction.\n *\n * @param transaction - Transaction metadata.\n * @param transactionData - Transaction pay data.\n * @returns The quote sender address.\n */\nfunction getFrom(\n transaction: TransactionMeta,\n transactionData: TransactionData,\n): Hex {\n const transactionFrom = transaction.txParams.from as Hex;\n\n // Post-quote output goes to `accountOverride`, so the funds holder sends.\n if (transactionData.isPostQuote) {\n return transactionFrom;\n }\n\n return transactionData.accountOverride ?? transactionFrom;\n}\n\n/**\n * Sync batch transactions to the transaction meta.\n *\n * @param request - Request object.\n * @param request.batchTransactions - Batch transactions to sync.\n * @param request.hasQuotes - Whether MM Pay produced any quotes for this transaction.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.messenger - Messenger instance.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.selectedFiatPayment - Selected fiat payment method ID.\n * @param request.strategy - Strategy of the executable quotes.\n * @param request.totals - Calculated totals.\n * @param request.transactionId - ID of the transaction to sync.\n */\nfunction syncTransaction({\n batchTransactions,\n hasQuotes,\n isPostQuote,\n messenger,\n paymentToken,\n selectedFiatPayment,\n strategy,\n totals,\n transactionId,\n}: {\n batchTransactions: BatchTransaction[];\n selectedFiatPayment?: string;\n hasQuotes: boolean;\n isPostQuote?: boolean;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n strategy?: TransactionPayStrategy;\n totals: TransactionPayTotals;\n transactionId: string;\n}): void {\n if (!paymentToken && !selectedFiatPayment) {\n return;\n }\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Update transaction pay data',\n },\n (tx: TransactionMeta) => {\n tx.batchTransactions = batchTransactions;\n tx.batchTransactionsOptions = {};\n\n // When MM Pay has produced quotes, it owns submission of this transaction\n // via its strategy publish hook, so the parent must be marked externally\n // signed to skip the local `KeyringController:signTransaction` call.\n // When there are no quotes (e.g. user selected the target token as the\n // payment token in a Predict flow), the transaction falls back to normal\n // local signing, so the flag is cleared to allow that.\n // If gas is sponsored, TC owns this field — it is set based on the\n // Sentinel simulation result and must not be cleared here. Same-token\n // flows (e.g. Monad mUSD withdrawal via a Money Account) produce no\n // quotes but still need external sign because the account cannot sign\n // locally.\n if (!tx.isGasFeeSponsored) {\n tx.isExternalSign = hasQuotes;\n }\n\n tx.metamaskPay = {\n bridgeFeeFiat: totals.fees.provider.usd,\n chainId: paymentToken?.chainId,\n isPostQuote,\n networkFeeFiat: totals.fees.sourceNetwork.estimate.usd,\n strategy,\n targetFiat: totals.targetAmount.usd,\n tokenAddress: paymentToken?.address,\n totalFiat: totals.total.usd,\n };\n },\n );\n}\n\n/**\n * Refresh source amounts and quotes for all transactions if expired.\n *\n * @param messenger - Messenger instance.\n * @param updateTransactionData - Callback to update transaction data.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n * @param getBalance - Optional callback to override the source balance used for max-amount calculation.\n */\nexport async function refreshQuotes(\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n getBalance?: GetBalanceCallback,\n): Promise<void> {\n const state = messenger.call('TransactionPayController:getState');\n const transactionIds = Object.keys(state.transactionData);\n\n for (const transactionId of transactionIds) {\n const transactionData = state.transactionData[transactionId];\n const { isLoading, quotes, quotesLastUpdated } = transactionData;\n\n if (isLoading || !quotes?.length) {\n continue;\n }\n\n // No-op quotes mark direct routes and have nothing to refresh. They are\n // regenerated whenever the transaction data changes.\n if (\n quotes.every((quote) => quote.strategy === TransactionPayStrategy.None)\n ) {\n continue;\n }\n\n const strategyName = quotes[0].strategy;\n const strategy = getStrategyByName(strategyName);\n\n const refreshInterval =\n (await strategy.getRefreshInterval?.({\n chainId: quotes[0].request.sourceChainId,\n messenger,\n transactionId,\n })) ?? DEFAULT_REFRESH_INTERVAL;\n\n const isExpired = Date.now() - (quotesLastUpdated ?? 0) > refreshInterval;\n\n if (!isExpired) {\n continue;\n }\n\n updateTransactionData(transactionId, (data) =>\n updateSourceAmounts(\n transactionId,\n /* oxlint-disable typescript/no-unnecessary-type-assertion */\n data as never,\n /* oxlint-enable typescript/no-unnecessary-type-assertion */\n messenger,\n getBalance,\n ),\n );\n\n const latestTransactionData = messenger.call(\n 'TransactionPayController:getState',\n ).transactionData[transactionId];\n\n const isUpdated = await updateQuotes({\n getStrategies,\n messenger,\n transactionData: latestTransactionData,\n transactionId,\n updateTransactionData,\n });\n\n if (isUpdated) {\n log('Refreshed quotes', { transactionId, strategy: strategyName });\n }\n }\n}\n\nfunction abortPreviousAndCreateController(\n transactionId: string,\n): AbortController {\n const previous = inFlightQuoteRequests.get(transactionId);\n\n if (previous && !previous.signal.aborted) {\n log('Aborting previous quote request', { transactionId });\n previous.abort(new Error('Superseded by newer quote request'));\n }\n\n const controller = new AbortController();\n inFlightQuoteRequests.set(transactionId, controller);\n return controller;\n}\n\nfunction clearControllerIfCurrent(\n transactionId: string,\n controller: AbortController,\n): void {\n if (inFlightQuoteRequests.get(transactionId) === controller) {\n inFlightQuoteRequests.delete(transactionId);\n }\n}\n\n/**\n * Read the current source amounts for a transaction from controller state.\n *\n * @param messenger - Messenger instance.\n * @param transactionId - ID of the transaction.\n * @returns The source amounts, or `undefined` if the transaction has none.\n */\nfunction getSourceAmounts(\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n): TransactionPaySourceAmount[] | undefined {\n return messenger.call('TransactionPayController:getState').transactionData[\n transactionId\n ]?.sourceAmounts;\n}\n\n/**\n * Build quote requests required to retrieve quotes.\n *\n * @param request - Request parameters.\n * @param request.accountOverride - Optional account receiving post-quote output.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction.\n * @param request.tokens - Required tokens for the transaction.\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests.\n */\nfunction buildQuoteRequests({\n accountOverride,\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n transactionId,\n}: {\n accountOverride?: Hex;\n atomic?: boolean;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n isPostQuote?: boolean;\n paymentOverride?: PaymentOverride;\n paymentToken: TransactionPaymentToken | undefined;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n tokens: TransactionPayRequiredToken[];\n transactionId: string;\n}): QuoteRequest[] {\n if (!paymentToken) {\n return [];\n }\n\n if (isPostQuote) {\n return buildPostQuoteRequests({\n accountOverride,\n atomic,\n destinationToken: paymentToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n });\n }\n\n // Standard flow: source = paymentToken, target = required tokens\n const requests = (sourceAmounts ?? []).map((sourceAmount) => {\n const token = tokens.find(\n (singleToken) => singleToken.address === sourceAmount.targetTokenAddress,\n ) as TransactionPayRequiredToken;\n\n return {\n atomic,\n from,\n isMaxAmount,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: paymentToken.balanceRaw,\n sourceChainId: paymentToken.chainId,\n sourceTokenAddress: paymentToken.address,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: token.allowUnderMinimum ? '0' : token.amountRaw,\n targetChainId: token.chainId,\n targetTokenAddress: token.address,\n };\n });\n\n if (!requests.length) {\n log('No quote requests', { transactionId });\n }\n\n return requests;\n}\n\n/**\n * Build quote requests for post-quote flows.\n * In this flow, the source is the transaction's required token,\n * and the target is the user's selected destination token (paymentToken).\n *\n * @param request - Request parameters.\n * @param request.accountOverride - Optional account receiving the output.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.destinationToken - Destination token (paymentToken in post-quote mode).\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction (includes source token info).\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests for post-quote flow.\n */\nfunction buildPostQuoteRequests({\n accountOverride,\n atomic,\n destinationToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n}: {\n accountOverride?: Hex;\n atomic?: boolean;\n destinationToken: TransactionPaymentToken;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n paymentOverride?: PaymentOverride;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n transactionId: string;\n}): QuoteRequest[] {\n // Find the source amount where targetTokenAddress matches the destination token\n const sourceAmount = sourceAmounts?.find(\n (amount) =>\n amount.targetTokenAddress.toLowerCase() ===\n destinationToken.address.toLowerCase(),\n );\n\n // Same-token-same-chain cases are already filtered in source-amounts.ts\n if (\n !sourceAmount?.sourceBalanceRaw ||\n !sourceAmount.sourceChainId ||\n !sourceAmount.sourceTokenAddress\n ) {\n log('No valid source amount found for post-quote request', {\n transactionId,\n });\n return [];\n }\n\n const request: QuoteRequest = {\n accountOverride,\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote: true,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: sourceAmount.sourceBalanceRaw,\n sourceChainId: sourceAmount.sourceChainId,\n sourceTokenAddress: sourceAmount.sourceTokenAddress,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: '0',\n targetChainId: destinationToken.chainId,\n targetTokenAddress: destinationToken.address,\n };\n\n log('Post-quote request built', { transactionId, request });\n\n // Currently only single token post-quote flows are supported.\n // Multiple token support would require multiple quotes for each required token.\n return [request];\n}\n\nasync function refreshPaymentTokenBalance({\n from,\n messenger,\n paymentToken,\n signal,\n transactionId,\n updateTransactionData,\n}: {\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n signal: AbortSignal;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n}): Promise<TransactionPaymentToken | undefined> {\n if (!paymentToken) {\n return undefined;\n }\n\n try {\n const fiatRates = getTokenFiatRate(\n messenger,\n paymentToken.address,\n paymentToken.chainId,\n );\n\n if (!fiatRates) {\n return paymentToken;\n }\n\n const liveBalance = await getLiveTokenBalance(\n messenger,\n from,\n paymentToken.chainId,\n paymentToken.address,\n );\n\n if (signal.aborted) {\n log('Payment token balance refresh aborted', { transactionId });\n return paymentToken;\n }\n\n const {\n raw: balanceRaw,\n human: balanceHuman,\n usd: balanceUsd,\n fiat: balanceFiat,\n } = computeTokenAmounts(liveBalance, paymentToken.decimals, fiatRates);\n\n const updatedToken = {\n ...paymentToken,\n balanceFiat,\n balanceHuman,\n balanceRaw,\n balanceUsd,\n };\n\n updateTransactionData(transactionId, (data) => {\n data.paymentToken = updatedToken;\n });\n\n log('Refreshed payment token balance', { transactionId, balanceRaw });\n\n return updatedToken;\n } catch (error) {\n log('Failed to refresh payment token balance', { transactionId, error });\n return paymentToken;\n }\n}\n\n/**\n * Retrieve quotes for a transaction.\n *\n * @param transaction - Transaction metadata.\n * @param from - Sending wallet address (`txParams.from` for post-quote, otherwise `accountOverride ?? txParams.from`).\n * @param requests - Quote requests.\n * @param paymentToken - Selected payment token, if any.\n * @param isQuoteRequired - Whether a quote is always required for the transaction.\n * @param isAccountEIP7702Compatible - Whether the account supports EIP-7702.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n * @param messenger - Controller messenger.\n * @param fiatPaymentMethod - Selected fiat payment method ID, if applicable.\n * @param signal - Signal that aborts when the quote request is superseded.\n * @returns An object containing batch transactions and quotes.\n */\nasync function getQuotes(\n transaction: TransactionMeta,\n from: Hex,\n requests: QuoteRequest[],\n paymentToken: TransactionPaymentToken | undefined,\n isQuoteRequired: boolean,\n isAccountEIP7702Compatible: boolean,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n messenger: TransactionPayControllerMessenger,\n fiatPaymentMethod?: string,\n signal?: AbortSignal,\n): Promise<{\n batchTransactions: BatchTransaction[];\n error?: QuoteErrorInfo;\n quotes: TransactionPayQuote<Json>[];\n}> {\n const { id: transactionId } = transaction;\n const strategies = getStrategiesByName(\n getStrategies(transaction),\n (strategyName) => {\n log('Skipping unknown strategy', {\n strategy: strategyName,\n transactionId,\n });\n },\n );\n\n if (!requests?.length && !fiatPaymentMethod) {\n // A selected payment token with no conversion requests means the route is\n // direct. Return an explicit no-op quote so clients and the publish hook\n // can distinguish \"no conversion needed\" from \"quote needed but missing\".\n // Not applicable when a quote is always required, as an empty requests\n // list then means the source amounts could not be calculated.\n const noOpQuote =\n paymentToken && !isQuoteRequired\n ? buildNoOpQuote(from, paymentToken)\n : undefined;\n\n if (noOpQuote) {\n log('Built no-op quote for direct route', { transactionId });\n }\n\n return {\n batchTransactions: [],\n quotes: noOpQuote ? [noOpQuote] : [],\n };\n }\n\n const request = {\n accountSupports7702: isAccountEIP7702Compatible,\n fiatPaymentMethod,\n from,\n messenger,\n requests,\n signal,\n transaction,\n };\n\n let error: QuoteErrorInfo | undefined;\n\n for (const { name, strategy } of strategies) {\n try {\n const support = await checkStrategySupport(strategy, request);\n\n if (!support) {\n log('Strategy does not support request', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n const quotes = (await strategy.getQuotes(\n request,\n )) as TransactionPayQuote<Json>[];\n\n if (!quotes.length) {\n log('Strategy returned no quotes', { strategy: name, transactionId });\n continue;\n }\n\n const isQuoteSupported = await checkStrategyQuoteSupport(strategy, {\n messenger,\n quotes,\n signal,\n transaction,\n });\n\n if (!isQuoteSupported) {\n log('Strategy does not support quotes', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n log('Updated', { transactionId, quotes });\n\n const batchTransactions = strategy.getBatchTransactions\n ? await strategy.getBatchTransactions({\n messenger,\n quotes,\n signal,\n })\n : [];\n\n log('Batch transactions', { transactionId, batchTransactions });\n\n return {\n batchTransactions,\n quotes,\n };\n } catch (caughtError) {\n if (signal?.aborted) {\n throw caughtError;\n }\n\n error ??= isQuoteError(caughtError)\n ? caughtError.info\n : { message: (caughtError as Error).message, reason: 'no-quotes' };\n\n if (\n isQuoteError(caughtError) &&\n caughtError.info.reason === 'insufficient-source-balance' &&\n caughtError.quotes?.length\n ) {\n log('Keeping quotes despite insufficient source balance', {\n strategy: name,\n transactionId,\n });\n return {\n batchTransactions: [],\n error: caughtError.info,\n quotes: caughtError.quotes as TransactionPayQuote<Json>[],\n };\n }\n\n log('Strategy failed, trying next', {\n error: caughtError,\n strategy: name,\n transactionId,\n });\n continue;\n }\n }\n\n log('No quotes available', { transactionId });\n\n return {\n batchTransactions: [],\n error,\n quotes: [],\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/transaction-pay-controller",
|
|
3
|
-
"version": "30.4.3-preview-
|
|
3
|
+
"version": "30.4.3-preview-6ebaf4e52",
|
|
4
4
|
"description": "Manages alternate payment strategies to provide required funds for transactions in MetaMask",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|