@metamask-previews/transaction-pay-controller 31.2.1-preview-e80304db4 → 31.2.1-preview-1d88b8ba5

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.
Files changed (105) hide show
  1. package/CHANGELOG.md +23 -1
  2. package/dist/TransactionPayController.d.ts.map +1 -1
  3. package/dist/TransactionPayController.js +4 -5
  4. package/dist/TransactionPayController.js.map +1 -1
  5. package/dist/actions/update-payment-token.d.ts.map +1 -1
  6. package/dist/actions/update-payment-token.js +51 -22
  7. package/dist/actions/update-payment-token.js.map +1 -1
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js.map +1 -1
  11. package/dist/strategy/across/AcrossStrategy.d.ts.map +1 -1
  12. package/dist/strategy/across/AcrossStrategy.js +6 -1
  13. package/dist/strategy/across/AcrossStrategy.js.map +1 -1
  14. package/dist/strategy/across/across-quotes.js +7 -4
  15. package/dist/strategy/across/across-quotes.js.map +1 -1
  16. package/dist/strategy/across/across-submit.d.ts.map +1 -1
  17. package/dist/strategy/across/across-submit.js +3 -1
  18. package/dist/strategy/across/across-submit.js.map +1 -1
  19. package/dist/strategy/fiat/FiatStrategy.d.ts +1 -0
  20. package/dist/strategy/fiat/FiatStrategy.d.ts.map +1 -1
  21. package/dist/strategy/fiat/FiatStrategy.js +4 -0
  22. package/dist/strategy/fiat/FiatStrategy.js.map +1 -1
  23. package/dist/strategy/fiat/fiat-direct-musd.d.ts.map +1 -1
  24. package/dist/strategy/fiat/fiat-direct-musd.js +4 -2
  25. package/dist/strategy/fiat/fiat-direct-musd.js.map +1 -1
  26. package/dist/strategy/fiat/fiat-quotes.d.ts.map +1 -1
  27. package/dist/strategy/fiat/fiat-quotes.js +4 -2
  28. package/dist/strategy/fiat/fiat-quotes.js.map +1 -1
  29. package/dist/strategy/fiat/fiat-submit.d.ts.map +1 -1
  30. package/dist/strategy/fiat/fiat-submit.js +5 -2
  31. package/dist/strategy/fiat/fiat-submit.js.map +1 -1
  32. package/dist/strategy/fiat/fiat-test-funding.d.ts.map +1 -1
  33. package/dist/strategy/fiat/fiat-test-funding.js +3 -5
  34. package/dist/strategy/fiat/fiat-test-funding.js.map +1 -1
  35. package/dist/strategy/relay/RelayStrategy.d.ts +4 -0
  36. package/dist/strategy/relay/RelayStrategy.d.ts.map +1 -1
  37. package/dist/strategy/relay/RelayStrategy.js +6 -1
  38. package/dist/strategy/relay/RelayStrategy.js.map +1 -1
  39. package/dist/strategy/relay/relay-quotes.d.ts.map +1 -1
  40. package/dist/strategy/relay/relay-quotes.js +10 -6
  41. package/dist/strategy/relay/relay-quotes.js.map +1 -1
  42. package/dist/strategy/relay/relay-submit-execute.d.ts.map +1 -1
  43. package/dist/strategy/relay/relay-submit-execute.js +3 -1
  44. package/dist/strategy/relay/relay-submit-execute.js.map +1 -1
  45. package/dist/strategy/relay/relay-submit.d.ts.map +1 -1
  46. package/dist/strategy/relay/relay-submit.js +8 -6
  47. package/dist/strategy/relay/relay-submit.js.map +1 -1
  48. package/dist/strategy/relay/relay-validation.d.ts.map +1 -1
  49. package/dist/strategy/relay/relay-validation.js +5 -2
  50. package/dist/strategy/relay/relay-validation.js.map +1 -1
  51. package/dist/strategy/server/ServerStrategy.d.ts.map +1 -1
  52. package/dist/strategy/server/ServerStrategy.js +4 -0
  53. package/dist/strategy/server/ServerStrategy.js.map +1 -1
  54. package/dist/strategy/server/server-quotes.d.ts.map +1 -1
  55. package/dist/strategy/server/server-quotes.js +54 -11
  56. package/dist/strategy/server/server-quotes.js.map +1 -1
  57. package/dist/strategy/server/server-submit.d.ts.map +1 -1
  58. package/dist/strategy/server/server-submit.js +9 -6
  59. package/dist/strategy/server/server-submit.js.map +1 -1
  60. package/dist/strategy/server/server-support.d.ts +1 -3
  61. package/dist/strategy/server/server-support.d.ts.map +1 -1
  62. package/dist/strategy/server/server-support.js +0 -5
  63. package/dist/strategy/server/server-support.js.map +1 -1
  64. package/dist/strategy/server/server-validation.d.ts.map +1 -1
  65. package/dist/strategy/server/server-validation.js +3 -1
  66. package/dist/strategy/server/server-validation.js.map +1 -1
  67. package/dist/types.d.ts +60 -25
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/types.js.map +1 -1
  70. package/dist/utils/account.d.ts +54 -0
  71. package/dist/utils/account.d.ts.map +1 -1
  72. package/dist/utils/account.js +124 -0
  73. package/dist/utils/account.js.map +1 -1
  74. package/dist/utils/gas-payment.d.ts +12 -3
  75. package/dist/utils/gas-payment.d.ts.map +1 -1
  76. package/dist/utils/gas-payment.js +2 -2
  77. package/dist/utils/gas-payment.js.map +1 -1
  78. package/dist/utils/max-gas-station.d.ts.map +1 -1
  79. package/dist/utils/max-gas-station.js +9 -5
  80. package/dist/utils/max-gas-station.js.map +1 -1
  81. package/dist/utils/max-quote.js +3 -2
  82. package/dist/utils/max-quote.js.map +1 -1
  83. package/dist/utils/no-op-quote.d.ts +3 -3
  84. package/dist/utils/no-op-quote.d.ts.map +1 -1
  85. package/dist/utils/no-op-quote.js +4 -3
  86. package/dist/utils/no-op-quote.js.map +1 -1
  87. package/dist/utils/perps.d.ts.map +1 -1
  88. package/dist/utils/perps.js +5 -2
  89. package/dist/utils/perps.js.map +1 -1
  90. package/dist/utils/post-quote.js +4 -3
  91. package/dist/utils/post-quote.js.map +1 -1
  92. package/dist/utils/quotes.d.ts.map +1 -1
  93. package/dist/utils/quotes.js +99 -25
  94. package/dist/utils/quotes.js.map +1 -1
  95. package/dist/utils/source-amounts.d.ts.map +1 -1
  96. package/dist/utils/source-amounts.js +25 -4
  97. package/dist/utils/source-amounts.js.map +1 -1
  98. package/dist/utils/token.d.ts +84 -1
  99. package/dist/utils/token.d.ts.map +1 -1
  100. package/dist/utils/token.js +144 -13
  101. package/dist/utils/token.js.map +1 -1
  102. package/dist/utils/validation.d.ts.map +1 -1
  103. package/dist/utils/validation.js +14 -11
  104. package/dist/utils/validation.js.map +1 -1
  105. package/package.json +2 -1
@@ -1 +1 @@
1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EH,OAAO;QACL,GAAG,SAAS;QACZ,aAAa,EAAE;YACb,QAAQ,EAAE,UAAU,CAAC;gBACnB,SAAS,CAAC,aAAa,CAAC,QAAQ;gBAChC,qBAAqB,CAAC,QAAQ;aAC/B,CAAC;YACF,GAAG,EAAE,UAAU,CAAC,CAAC,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,qBAAqB,CAAC,GAAG,CAAC,CAAC;SAC1E;QACD,SAAS;QACT,gBAAgB;QAChB,aAAa;KACd,CAAC;AACJ,CAAC;AAED,SAAS,kCAAkC,CAAC,EAC1C,GAAG,EACH,SAAS,EACT,MAAM,EACN,WAAW,GAMZ;IACC,MAAM,0BAA0B,GAAG,WAAW,CAAC,kBAAkB,EAAE,IAAI,CACrE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,GAAG,CACf,CAAC;IACF,MAAM,YAAY,GAChB,0BAA0B,EAAE,YAAY;QACxC,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC;IACpC,MAAM,oBAAoB,GACxB,0BAA0B,EAAE,oBAAoB;QAChD,WAAW,CAAC,QAAQ,CAAC,oBAAoB,CAAC;IAE5C,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"]}
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,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE3E,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,0CAA0C,EAAE,MAAM,yBAAy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Y,CAAC;IACpC,MAAM,oBAAoB,GACxB,0BAA0B,EAAE,oBAAoB;QAChD,WAAW,CAAC,QAAQ,CAAC,oBAAoB,CAAC;IAE5C,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 { getEvmQuoteSource, 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 sourceTokenAmount,\n targetAmountMinimum,\n targetChainId,\n targetTokenAddress,\n } = normalizedRequest;\n const { chainId: sourceChainId, tokenAddress: sourceTokenAddress } =\n getEvmQuoteSource(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 } = request;\n const { chainId: sourceChainId, tokenAddress: sourceTokenAddress } =\n getEvmQuoteSource(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 { chainId: sourceChainId, tokenAddress: sourceTokenAddress } =\n getEvmQuoteSource(request);\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n sourceTokenAddress,\n 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 +1 @@
1
- {"version":3,"file":"across-submit.d.ts","sourceRoot":"","sources":["../../../src/strategy/across/across-submit.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAK3C,OAAO,KAAK,EACV,yBAAyB,EAG1B,MAAM,gBAAgB,CAAC;AAoBxB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAU9C;;;;;GAKG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,yBAAyB,CAAC,WAAW,CAAC,GAC9C,OAAO,CAAC;IAAE,eAAe,CAAC,EAAE,GAAG,CAAA;CAAE,CAAC,CAepC"}
1
+ {"version":3,"file":"across-submit.d.ts","sourceRoot":"","sources":["../../../src/strategy/across/across-submit.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAK3C,OAAO,KAAK,EACV,yBAAyB,EAG1B,MAAM,gBAAgB,CAAC;AAqBxB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAU9C;;;;;GAKG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,yBAAyB,CAAC,WAAW,CAAC,GAC9C,OAAO,CAAC;IAAE,eAAe,CAAC,EAAE,GAAG,CAAA;CAAE,CAAC,CAepC"}
@@ -8,6 +8,7 @@ import { getPayStrategiesConfig } from '../../utils/feature-flags.js';
8
8
  import { getGasBuffer } from '../../utils/feature-flags.js';
9
9
  import { GasPaymentMode, logGasPaymentOutcome, resolveGasPayment, } from '../../utils/gas-payment.js';
10
10
  import { getNetworkClientId } from '../../utils/provider.js';
11
+ import { getEvmQuoteSource } from '../../utils/token.js';
11
12
  import { collectTransactionIds, getTransaction, updateTransaction, waitForTransactionConfirmed, } from '../../utils/transaction.js';
12
13
  import { getAcrossOrderedTransactions, getOriginalTransactionGas, } from './transactions.js';
13
14
  const log = createModuleLogger(projectLogger, 'across-strategy');
@@ -59,7 +60,8 @@ async function executeSingleQuote(quote, messenger, transaction) {
59
60
  async function submitTransactions(quote, parentTransaction, acrossDepositType, messenger) {
60
61
  const { swapTx } = quote.original.quote;
61
62
  const { gasLimits: quoteGasLimits, is7702 } = quote.original.metamask;
62
- const { from, sourceTokenAddress } = quote.request;
63
+ const { from } = quote.request;
64
+ const { tokenAddress: sourceTokenAddress } = getEvmQuoteSource(quote.request);
63
65
  const chainId = toHex(swapTx.chainId);
64
66
  // Across has no relayer-paid delegation flow and is never sponsored, so the
65
67
  // only lift available is the gas station collecting gas in the source token.
@@ -1 +1 @@
1
- {"version":3,"file":"across-submit.js","sourceRoot":"","sources":["../../../src/strategy/across/across-submit.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,eAAe,EACf,KAAK,GACN,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,kCAAkC,CAAC;AAO1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAMhD,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,iBAAiB,EACjB,2BAA2B,GAC5B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAG3B,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,iBAAiB,CAAC,CAAC;AACjE,MAAM,2BAA2B,GAAG,IAAI,CAAC;AAOzC;;;;;GAKG;AACH,MAAM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W,CAAC,IAAI,CAAC;IAC5B,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,SAAS,sBAAsB,CAC7B,IAAS,EACT,MAQC;IAED,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,IAAI,KAAK,CAAC,CAAC;IAE3C,OAAO;QACL,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,IAAI;QACJ,GAAG,EAAE,MAAM,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC;QACvE,YAAY,EAAE,oBAAoB,CAAC,MAAM,CAAC,YAAY,CAAC;QACvD,oBAAoB,EAAE,oBAAoB,CAAC,MAAM,CAAC,oBAAoB,CAAC;QACvE,EAAE,EAAE,MAAM,CAAC,EAAE;QACb,KAAK;KACN,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,oBAAoB,CAAC,KAAc;IAC1C,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC;AACtB,CAAC;AAED;;;;;GAKG;AACH,SAAS,wBAAwB,CAC/B,MAAyB;IAEzB,OAAO;QACL,IAAI,EAAE,MAAM,CAAC,IAAuB;QACpC,GAAG,EAAE,MAAM,CAAC,GAAsB;QAClC,YAAY,EAAE,MAAM,CAAC,YAA+B;QACpD,oBAAoB,EAAE,MAAM,CAAC,oBAAuC;QACpE,EAAE,EAAE,MAAM,CAAC,EAAqB;QAChC,KAAK,EAAE,MAAM,CAAC,KAAwB;KACvC,CAAC;AACJ,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n successfulFetch,\n toHex,\n} from '@metamask/controller-utils';\nimport {\n TransactionType,\n hasTransactionType,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransactionParams,\n TransactionMeta,\n TransactionParams,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { PERPS_DEPOSIT_TYPES } from '../../constants.js';\nimport { projectLogger } from '../../logger.js';\nimport type {\n PayStrategyExecuteRequest,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types.js';\nimport { accountSupports7702 } from '../../utils/account.js';\nimport { getPayStrategiesConfig } from '../../utils/feature-flags.js';\nimport { getGasBuffer } from '../../utils/feature-flags.js';\nimport {\n GasPaymentMode,\n logGasPaymentOutcome,\n resolveGasPayment,\n} from '../../utils/gas-payment.js';\nimport { getNetworkClientId } from '../../utils/provider.js';\nimport {\n collectTransactionIds,\n getTransaction,\n updateTransaction,\n waitForTransactionConfirmed,\n} from '../../utils/transaction.js';\nimport {\n getAcrossOrderedTransactions,\n getOriginalTransactionGas,\n} from './transactions.js';\nimport type { AcrossQuote } from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'across-strategy');\nconst ACROSS_STATUS_POLL_INTERVAL = 1000;\n\ntype PreparedAcrossTransaction = {\n params: TransactionParams;\n type: TransactionMeta['type'];\n};\n\n/**\n * Submit Across quotes.\n *\n * @param request - Request object.\n * @returns An object containing the transaction hash if available.\n */\nexport async function submitAcrossQuotes(\n request: PayStrategyExecuteRequest<AcrossQuote>,\n): Promise<{ transactionHash?: Hex }> {\n log('Executing quotes', request);\n\n const { quotes, messenger, transaction } = request;\n let transactionHash: Hex | undefined;\n\n for (const quote of quotes) {\n ({ transactionHash } = await executeSingleQuote(\n quote,\n messenger,\n transaction,\n ));\n }\n\n return { transactionHash };\n}\n\nasync function executeSingleQuote(\n quote: TransactionPayQuote<AcrossQuote>,\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n): Promise<{ transactionHash?: Hex }> {\n log('Executing single quote', quote);\n\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Remove nonce from skipped transaction',\n },\n (tx) => {\n tx.txParams.nonce = undefined;\n },\n );\n\n const acrossDepositType = getAcrossDepositType(transaction);\n const transactionHash = await submitTransactions(\n quote,\n transaction,\n acrossDepositType,\n messenger,\n );\n\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Intent complete after Across submission',\n },\n (tx) => {\n tx.isIntentComplete = true;\n },\n );\n\n return { transactionHash };\n}\n\n/**\n * Submit transactions for an Across quote.\n *\n * @param quote - Across quote.\n * @param parentTransaction - Parent transaction.\n * @param acrossDepositType - Transaction type used for the swap/deposit step.\n * @param messenger - Controller messenger.\n * @returns Hash of the last submitted transaction, if available.\n */\nasync function submitTransactions(\n quote: TransactionPayQuote<AcrossQuote>,\n parentTransaction: TransactionMeta,\n acrossDepositType: TransactionType,\n messenger: TransactionPayControllerMessenger,\n): Promise<Hex | undefined> {\n const { swapTx } = quote.original.quote;\n const { gasLimits: quoteGasLimits, is7702 } = quote.original.metamask;\n const { from, sourceTokenAddress } = quote.request;\n const chainId = toHex(swapTx.chainId);\n\n // Across has no relayer-paid delegation flow and is never sponsored, so the\n // only lift available is the gas station collecting gas in the source token.\n const gasPayment = resolveGasPayment({\n isSourceGasFeeToken: quote.fees.isSourceGasFeeToken,\n sourceTokenAddress,\n });\n const isGasFeeTokenPayment = gasPayment.mode === GasPaymentMode.GasFeeToken;\n\n const orderedTransactions = getAcrossOrderedTransactions({\n quote: quote.original.quote,\n swapType: acrossDepositType,\n });\n const shouldPrependOriginalTransaction =\n quote.request.isPostQuote === true &&\n parentTransaction.txParams.to !== undefined;\n const hasPrependedOriginalGasLimit =\n shouldPrependOriginalTransaction &&\n !is7702 &&\n quoteGasLimits.length > orderedTransactions.length;\n const gasLimitOffset = hasPrependedOriginalGasLimit ? 1 : 0;\n const transactionCount =\n orderedTransactions.length + (shouldPrependOriginalTransaction ? 1 : 0);\n\n const networkClientId = getNetworkClientId(messenger, chainId);\n\n const is7702Batch = is7702 && transactionCount > 1;\n const canUseQuotedBatchGasLimit =\n is7702Batch &&\n (!shouldPrependOriginalTransaction ||\n hasOriginalTransactionGas(parentTransaction));\n const batchGasLimit = canUseQuotedBatchGasLimit\n ? quoteGasLimits[0]?.max\n : undefined;\n\n if (canUseQuotedBatchGasLimit && batchGasLimit === undefined) {\n throw new Error('Missing quote gas limit for Across 7702 batch');\n }\n\n const quotedGasLimit7702 =\n batchGasLimit === undefined ? undefined : toHex(batchGasLimit);\n const parentHasAuthorizationList = Boolean(\n parentTransaction.txParams.authorizationList?.length,\n );\n\n const shouldUseGasFeeToken7702Submit = shouldEstimate7702SubmitBatch({\n isGasFeeTokenPayment,\n parentTransaction,\n quote,\n })\n ? accountSupports7702(messenger, from)\n : false;\n const shouldUse7702Submit = [\n Boolean(quotedGasLimit7702),\n is7702Batch,\n parentHasAuthorizationList,\n shouldUseGasFeeToken7702Submit,\n ].some(Boolean);\n\n const shouldEstimateGasLimit7702 = !quotedGasLimit7702 && shouldUse7702Submit;\n\n const estimatedGasLimit7702 = shouldEstimateGasLimit7702\n ? await estimateSubmitBatchGasLimit7702({\n chainId,\n from,\n messenger,\n orderedTransactions,\n parentTransaction,\n shouldPrependOriginalTransaction,\n })\n : undefined;\n\n const gasLimit7702 = quotedGasLimit7702 ?? estimatedGasLimit7702;\n const submitAs7702 = shouldUse7702Submit || Boolean(gasLimit7702);\n\n const acrossTransactions: PreparedAcrossTransaction[] =\n orderedTransactions.map((transaction, index) => {\n const gasLimit = submitAs7702\n ? undefined\n : quoteGasLimits[index + gasLimitOffset]?.max;\n\n if (gasLimit === undefined && !submitAs7702) {\n const quoteGasIndex = index + gasLimitOffset;\n const errorMessage =\n transaction.kind === 'approval'\n ? `Missing quote gas limit for Across approval transaction at index ${quoteGasIndex}`\n : 'Missing quote gas limit for Across swap transaction';\n\n throw new Error(errorMessage);\n }\n\n return {\n params: buildTransactionParams(from, {\n chainId: transaction.chainId,\n data: transaction.data,\n gasLimit,\n maxFeePerGas: transaction.maxFeePerGas,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas,\n to: transaction.to,\n value: transaction.value,\n }),\n type: transaction.type ?? acrossDepositType,\n };\n });\n const originalTransaction = shouldPrependOriginalTransaction\n ? [\n buildOriginalTransaction(\n parentTransaction,\n submitAs7702 || !hasPrependedOriginalGasLimit\n ? undefined\n : quoteGasLimits[0]?.max,\n ),\n ]\n : [];\n const transactions = [...originalTransaction, ...acrossTransactions];\n\n const transactionIds: string[] = [];\n\n const { end } = collectTransactionIds(\n chainId,\n from,\n messenger,\n (transactionId) => {\n transactionIds.push(transactionId);\n\n updateTransaction(\n {\n transactionId: parentTransaction.id,\n messenger,\n note: 'Add required transaction ID from Across submission',\n },\n (tx) => {\n tx.requiredTransactionIds ??= [];\n tx.requiredTransactionIds.push(transactionId);\n },\n );\n },\n );\n\n let result: { result: Promise<string> } | undefined;\n const { excludeNativeTokenForFee, gasFeeToken } = gasPayment;\n\n try {\n if (transactions.length === 1) {\n result = await messenger.call(\n 'TransactionController:addTransaction',\n transactions[0].params,\n {\n excludeNativeTokenForFee,\n gasFeeToken,\n networkClientId,\n origin: ORIGIN_METAMASK,\n isInternal: true,\n requireApproval: false,\n type: transactions[0].type,\n },\n );\n } else {\n const batchTransactions = transactions.map(({ params, type }) => ({\n params: toBatchTransactionParams(params),\n type,\n }));\n\n await messenger.call('TransactionController:addTransactionBatch', {\n disable7702: !submitAs7702,\n disableHook: submitAs7702,\n disableSequential: submitAs7702,\n excludeNativeTokenForFee,\n from,\n gasFeeToken,\n gasLimit7702,\n networkClientId,\n origin: ORIGIN_METAMASK,\n isInternal: true,\n requireApproval: false,\n transactions: batchTransactions,\n });\n }\n } finally {\n end();\n }\n\n if (result) {\n const txHash = await result.result;\n log('Submitted transaction', txHash);\n }\n\n await Promise.all(\n transactionIds.map((txId) => waitForTransactionConfirmed(txId, messenger)),\n );\n\n logGasPaymentOutcome(\n gasPayment,\n transactionIds.map((txId) => getTransaction(txId, messenger)),\n );\n\n const hash = transactionIds.length\n ? getTransaction(transactionIds.slice(-1)[0], messenger)?.hash\n : undefined;\n\n return await waitForAcrossCompletion(hash as Hex | undefined, messenger);\n}\n\ntype AcrossStatusResponse = {\n depositId?: number | string;\n depositTxnRef?: Hex;\n status?: string;\n destinationTxHash?: Hex;\n fillTxnRef?: Hex;\n fillTxHash?: Hex;\n txHash?: Hex;\n};\n\n/**\n * Poll Across until a submitted deposit reaches a terminal status.\n *\n * @param transactionHash - Source-chain deposit transaction hash.\n * @param messenger - Controller messenger.\n * @returns Destination/fill transaction hash when available, otherwise the source hash.\n */\nasync function waitForAcrossCompletion(\n transactionHash: Hex | undefined,\n messenger: TransactionPayControllerMessenger,\n): Promise<Hex | undefined> {\n if (!transactionHash) {\n return transactionHash;\n }\n\n const config = getPayStrategiesConfig(messenger);\n const params = new URLSearchParams({\n depositTxnRef: transactionHash,\n });\n const url = `${config.across.apiBase}/deposit/status?${params.toString()}`;\n\n let attempt = 0;\n\n while (true) {\n attempt += 1;\n let status: AcrossStatusResponse;\n\n try {\n const response = await successfulFetch(url, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n });\n status = (await response.json()) as AcrossStatusResponse;\n } catch (error) {\n log('Across status polling request failed', {\n attempt,\n error: String(error),\n transactionHash,\n });\n\n await new Promise((resolve) =>\n setTimeout(resolve, ACROSS_STATUS_POLL_INTERVAL),\n );\n continue;\n }\n\n const normalizedStatus = status.status?.toLowerCase();\n\n log('Polled Across status', {\n attempt,\n status: normalizedStatus,\n transactionHash,\n });\n\n if (\n normalizedStatus &&\n ['completed', 'filled', 'success'].includes(normalizedStatus)\n ) {\n return (\n status.destinationTxHash ??\n status.fillTxnRef ??\n status.fillTxHash ??\n status.txHash ??\n transactionHash\n );\n }\n\n if (\n normalizedStatus &&\n ['error', 'failed', 'refund', 'refunded'].includes(normalizedStatus)\n ) {\n throw new Error(`Across request failed with status: ${normalizedStatus}`);\n }\n\n await new Promise((resolve) =>\n setTimeout(resolve, ACROSS_STATUS_POLL_INTERVAL),\n );\n }\n}\n\n/**\n * Check whether submit should estimate a 7702 batch gas limit.\n *\n * This is needed for Predict withdraw post-quote flows that pay source-chain\n * gas with the source token, because the final submit batch can differ from the\n * batch shape that Across quoted.\n *\n * @param args - Check arguments.\n * @param args.isGasFeeTokenPayment - Whether source-chain gas is paid with a gas fee token.\n * @param args.parentTransaction - Original transaction metadata.\n * @param args.quote - Across quote selected for execution.\n * @returns Whether submit should try to estimate the final 7702 batch gas.\n */\nfunction shouldEstimate7702SubmitBatch({\n isGasFeeTokenPayment,\n parentTransaction,\n quote,\n}: {\n isGasFeeTokenPayment: boolean;\n parentTransaction: TransactionMeta;\n quote: TransactionPayQuote<AcrossQuote>;\n}): boolean {\n return (\n hasTransactionType(parentTransaction, [TransactionType.predictWithdraw]) &&\n quote.request.isPostQuote === true &&\n isGasFeeTokenPayment\n );\n}\n\n/**\n * Estimate the 7702 batch gas limit for the actual submit payload.\n *\n * Quotes can contain a combined 7702 gas limit that only covered the Across\n * approval/swap legs. When submit prepends the original transaction, estimate\n * the final batch shape so the gas limit covers every submitted leg.\n *\n * @param args - Estimation arguments.\n * @param args.chainId - Source chain ID.\n * @param args.from - Sender address.\n * @param args.messenger - Controller messenger.\n * @param args.orderedTransactions - Across approval/swap legs in submission order.\n * @param args.parentTransaction - Original transaction that may be prepended.\n * @param args.shouldPrependOriginalTransaction - Whether to include the original transaction in the estimate.\n * @returns Hex gas limit, or `undefined` when estimation is unavailable.\n */\nasync function estimateSubmitBatchGasLimit7702({\n chainId,\n from,\n messenger,\n orderedTransactions,\n parentTransaction,\n shouldPrependOriginalTransaction,\n}: {\n chainId: Hex;\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n orderedTransactions: ReturnType<typeof getAcrossOrderedTransactions>;\n parentTransaction: TransactionMeta;\n shouldPrependOriginalTransaction: boolean;\n}): Promise<Hex | undefined> {\n if (!accountSupports7702(messenger, from)) {\n return undefined;\n }\n\n const originalTransaction = shouldPrependOriginalTransaction\n ? [buildOriginalTransaction(parentTransaction)]\n : [];\n\n const acrossTransactions = orderedTransactions.map((transaction) => ({\n params: buildTransactionParams(from, {\n chainId: transaction.chainId,\n data: transaction.data,\n maxFeePerGas: transaction.maxFeePerGas,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas,\n to: transaction.to,\n value: transaction.value,\n }),\n type: transaction.type,\n }));\n\n const transactions = [...originalTransaction, ...acrossTransactions];\n\n try {\n const result = await messenger.call(\n 'TransactionController:estimateGasBatch',\n {\n chainId,\n from,\n transactions: transactions.map(({ params }) =>\n toBatchTransactionParams(params),\n ),\n },\n );\n\n // Older TransactionController versions return no `mode`, so detect a\n // combined EIP-7702 gas limit from the number of gas limits instead.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const is7702Result =\n result.mode === undefined\n ? result.gasLimits.length === 1\n : result.mode === 'eip7702';\n\n if (!is7702Result) {\n return undefined;\n }\n\n const gasLimit = Math.ceil(\n result.gasLimits[0] * getGasBuffer(messenger, chainId),\n );\n\n return toHex(gasLimit);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Build the original parent transaction as a prepared batch leg.\n *\n * @param transaction - Original transaction metadata.\n * @param gasLimit - Optional gas limit to pin on the original leg.\n * @returns Prepared transaction params and transaction type for the original leg.\n */\nfunction buildOriginalTransaction(\n transaction: TransactionMeta,\n gasLimit?: number,\n): PreparedAcrossTransaction {\n return {\n params: {\n data: transaction.txParams.data,\n from: transaction.txParams.from,\n gas: gasLimit === undefined ? undefined : toHex(gasLimit),\n to: transaction.txParams.to,\n value: transaction.txParams.value,\n },\n type: getOriginalTransactionType(transaction),\n };\n}\n\n/**\n * Get the transaction type to use for the original batch leg.\n *\n * @param transaction - Original transaction metadata.\n * @returns `predictWithdraw` for Predict withdrawals; otherwise the original type.\n */\nfunction getOriginalTransactionType(\n transaction: TransactionMeta,\n): TransactionMeta['type'] {\n if (hasTransactionType(transaction, [TransactionType.predictWithdraw])) {\n return TransactionType.predictWithdraw;\n }\n\n return transaction.type;\n}\n\n/**\n * Check whether the original transaction already has a usable gas limit.\n *\n * @param transaction - Original transaction metadata.\n * @returns Whether the original or nested transaction gas is a positive integer.\n */\nfunction hasOriginalTransactionGas(transaction: TransactionMeta): boolean {\n return getOriginalTransactionGas(transaction) !== undefined;\n}\n\n/**\n * Get the transaction type for the Across bridge/deposit leg.\n *\n * @param transaction - Original parent transaction.\n * @returns Across-specific transaction type for known flows, or the original type.\n */\nfunction getAcrossDepositType(transaction: TransactionMeta): TransactionType {\n if (hasTransactionType(transaction, [TransactionType.predictWithdraw])) {\n return TransactionType.predictAcrossWithdraw;\n }\n\n if (transaction.type && PERPS_DEPOSIT_TYPES.includes(transaction.type)) {\n return TransactionType.perpsAcrossDeposit;\n }\n\n switch (transaction.type) {\n case TransactionType.predictDeposit:\n return TransactionType.predictAcrossDeposit;\n case undefined:\n return TransactionType.perpsAcrossDeposit;\n default:\n return transaction.type;\n }\n}\n\n/**\n * Build TransactionController params for an Across approval or swap leg.\n *\n * @param from - Sender address.\n * @param params - Across transaction fields.\n * @param params.chainId - Source chain ID.\n * @param params.data - Transaction calldata.\n * @param params.gasLimit - Optional gas limit.\n * @param params.to - Recipient contract address.\n * @param params.value - Optional native value.\n * @param params.maxFeePerGas - Optional EIP-1559 max fee.\n * @param params.maxPriorityFeePerGas - Optional EIP-1559 priority fee.\n * @returns TransactionController params.\n */\nfunction buildTransactionParams(\n from: Hex,\n params: {\n chainId: number;\n data: Hex;\n gasLimit?: number;\n to: Hex;\n value?: Hex;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n },\n): TransactionParams {\n const value = toHex(params.value ?? '0x0');\n\n return {\n data: params.data,\n from,\n gas: params.gasLimit === undefined ? undefined : toHex(params.gasLimit),\n maxFeePerGas: normalizeOptionalHex(params.maxFeePerGas),\n maxPriorityFeePerGas: normalizeOptionalHex(params.maxPriorityFeePerGas),\n to: params.to,\n value,\n };\n}\n\n/**\n * Normalize an optional numeric string or hex string into a hex value.\n *\n * @param value - Optional value to normalize.\n * @returns Hex value, or `undefined` when no value is provided.\n */\nfunction normalizeOptionalHex(value?: string): Hex | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n return toHex(value);\n}\n\n/**\n * Convert full TransactionController params into batch transaction params.\n *\n * @param params - Transaction params.\n * @returns Batch-compatible transaction params.\n */\nfunction toBatchTransactionParams(\n params: TransactionParams,\n): BatchTransactionParams {\n return {\n data: params.data as Hex | undefined,\n gas: params.gas as Hex | undefined,\n maxFeePerGas: params.maxFeePerGas as Hex | undefined,\n maxPriorityFeePerGas: params.maxPriorityFeePerGas as Hex | undefined,\n to: params.to as Hex | undefined,\n value: params.value as Hex | undefined,\n };\n}\n"]}
1
+ {"version":3,"file":"across-submit.js","sourceRoot":"","sources":["../../../src/strategy/across/across-submit.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,eAAe,EACf,KAAK,GACN,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,kCAAkC,CAAC;AAO1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAMhD,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,iBAAiB,EACjB,2BAA2B,GAC5B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAG3B,MAAM,G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C,KAAwB;KACvC,CAAC;AACJ,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n successfulFetch,\n toHex,\n} from '@metamask/controller-utils';\nimport {\n TransactionType,\n hasTransactionType,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransactionParams,\n TransactionMeta,\n TransactionParams,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { PERPS_DEPOSIT_TYPES } from '../../constants.js';\nimport { projectLogger } from '../../logger.js';\nimport type {\n PayStrategyExecuteRequest,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types.js';\nimport { accountSupports7702 } from '../../utils/account.js';\nimport { getPayStrategiesConfig } from '../../utils/feature-flags.js';\nimport { getGasBuffer } from '../../utils/feature-flags.js';\nimport {\n GasPaymentMode,\n logGasPaymentOutcome,\n resolveGasPayment,\n} from '../../utils/gas-payment.js';\nimport { getNetworkClientId } from '../../utils/provider.js';\nimport { getEvmQuoteSource } from '../../utils/token.js';\nimport {\n collectTransactionIds,\n getTransaction,\n updateTransaction,\n waitForTransactionConfirmed,\n} from '../../utils/transaction.js';\nimport {\n getAcrossOrderedTransactions,\n getOriginalTransactionGas,\n} from './transactions.js';\nimport type { AcrossQuote } from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'across-strategy');\nconst ACROSS_STATUS_POLL_INTERVAL = 1000;\n\ntype PreparedAcrossTransaction = {\n params: TransactionParams;\n type: TransactionMeta['type'];\n};\n\n/**\n * Submit Across quotes.\n *\n * @param request - Request object.\n * @returns An object containing the transaction hash if available.\n */\nexport async function submitAcrossQuotes(\n request: PayStrategyExecuteRequest<AcrossQuote>,\n): Promise<{ transactionHash?: Hex }> {\n log('Executing quotes', request);\n\n const { quotes, messenger, transaction } = request;\n let transactionHash: Hex | undefined;\n\n for (const quote of quotes) {\n ({ transactionHash } = await executeSingleQuote(\n quote,\n messenger,\n transaction,\n ));\n }\n\n return { transactionHash };\n}\n\nasync function executeSingleQuote(\n quote: TransactionPayQuote<AcrossQuote>,\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n): Promise<{ transactionHash?: Hex }> {\n log('Executing single quote', quote);\n\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Remove nonce from skipped transaction',\n },\n (tx) => {\n tx.txParams.nonce = undefined;\n },\n );\n\n const acrossDepositType = getAcrossDepositType(transaction);\n const transactionHash = await submitTransactions(\n quote,\n transaction,\n acrossDepositType,\n messenger,\n );\n\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Intent complete after Across submission',\n },\n (tx) => {\n tx.isIntentComplete = true;\n },\n );\n\n return { transactionHash };\n}\n\n/**\n * Submit transactions for an Across quote.\n *\n * @param quote - Across quote.\n * @param parentTransaction - Parent transaction.\n * @param acrossDepositType - Transaction type used for the swap/deposit step.\n * @param messenger - Controller messenger.\n * @returns Hash of the last submitted transaction, if available.\n */\nasync function submitTransactions(\n quote: TransactionPayQuote<AcrossQuote>,\n parentTransaction: TransactionMeta,\n acrossDepositType: TransactionType,\n messenger: TransactionPayControllerMessenger,\n): Promise<Hex | undefined> {\n const { swapTx } = quote.original.quote;\n const { gasLimits: quoteGasLimits, is7702 } = quote.original.metamask;\n const { from } = quote.request;\n const { tokenAddress: sourceTokenAddress } = getEvmQuoteSource(quote.request);\n const chainId = toHex(swapTx.chainId);\n\n // Across has no relayer-paid delegation flow and is never sponsored, so the\n // only lift available is the gas station collecting gas in the source token.\n const gasPayment = resolveGasPayment({\n isSourceGasFeeToken: quote.fees.isSourceGasFeeToken,\n sourceTokenAddress,\n });\n const isGasFeeTokenPayment = gasPayment.mode === GasPaymentMode.GasFeeToken;\n\n const orderedTransactions = getAcrossOrderedTransactions({\n quote: quote.original.quote,\n swapType: acrossDepositType,\n });\n const shouldPrependOriginalTransaction =\n quote.request.isPostQuote === true &&\n parentTransaction.txParams.to !== undefined;\n const hasPrependedOriginalGasLimit =\n shouldPrependOriginalTransaction &&\n !is7702 &&\n quoteGasLimits.length > orderedTransactions.length;\n const gasLimitOffset = hasPrependedOriginalGasLimit ? 1 : 0;\n const transactionCount =\n orderedTransactions.length + (shouldPrependOriginalTransaction ? 1 : 0);\n\n const networkClientId = getNetworkClientId(messenger, chainId);\n\n const is7702Batch = is7702 && transactionCount > 1;\n const canUseQuotedBatchGasLimit =\n is7702Batch &&\n (!shouldPrependOriginalTransaction ||\n hasOriginalTransactionGas(parentTransaction));\n const batchGasLimit = canUseQuotedBatchGasLimit\n ? quoteGasLimits[0]?.max\n : undefined;\n\n if (canUseQuotedBatchGasLimit && batchGasLimit === undefined) {\n throw new Error('Missing quote gas limit for Across 7702 batch');\n }\n\n const quotedGasLimit7702 =\n batchGasLimit === undefined ? undefined : toHex(batchGasLimit);\n const parentHasAuthorizationList = Boolean(\n parentTransaction.txParams.authorizationList?.length,\n );\n\n const shouldUseGasFeeToken7702Submit = shouldEstimate7702SubmitBatch({\n isGasFeeTokenPayment,\n parentTransaction,\n quote,\n })\n ? accountSupports7702(messenger, from)\n : false;\n const shouldUse7702Submit = [\n Boolean(quotedGasLimit7702),\n is7702Batch,\n parentHasAuthorizationList,\n shouldUseGasFeeToken7702Submit,\n ].some(Boolean);\n\n const shouldEstimateGasLimit7702 = !quotedGasLimit7702 && shouldUse7702Submit;\n\n const estimatedGasLimit7702 = shouldEstimateGasLimit7702\n ? await estimateSubmitBatchGasLimit7702({\n chainId,\n from,\n messenger,\n orderedTransactions,\n parentTransaction,\n shouldPrependOriginalTransaction,\n })\n : undefined;\n\n const gasLimit7702 = quotedGasLimit7702 ?? estimatedGasLimit7702;\n const submitAs7702 = shouldUse7702Submit || Boolean(gasLimit7702);\n\n const acrossTransactions: PreparedAcrossTransaction[] =\n orderedTransactions.map((transaction, index) => {\n const gasLimit = submitAs7702\n ? undefined\n : quoteGasLimits[index + gasLimitOffset]?.max;\n\n if (gasLimit === undefined && !submitAs7702) {\n const quoteGasIndex = index + gasLimitOffset;\n const errorMessage =\n transaction.kind === 'approval'\n ? `Missing quote gas limit for Across approval transaction at index ${quoteGasIndex}`\n : 'Missing quote gas limit for Across swap transaction';\n\n throw new Error(errorMessage);\n }\n\n return {\n params: buildTransactionParams(from, {\n chainId: transaction.chainId,\n data: transaction.data,\n gasLimit,\n maxFeePerGas: transaction.maxFeePerGas,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas,\n to: transaction.to,\n value: transaction.value,\n }),\n type: transaction.type ?? acrossDepositType,\n };\n });\n const originalTransaction = shouldPrependOriginalTransaction\n ? [\n buildOriginalTransaction(\n parentTransaction,\n submitAs7702 || !hasPrependedOriginalGasLimit\n ? undefined\n : quoteGasLimits[0]?.max,\n ),\n ]\n : [];\n const transactions = [...originalTransaction, ...acrossTransactions];\n\n const transactionIds: string[] = [];\n\n const { end } = collectTransactionIds(\n chainId,\n from,\n messenger,\n (transactionId) => {\n transactionIds.push(transactionId);\n\n updateTransaction(\n {\n transactionId: parentTransaction.id,\n messenger,\n note: 'Add required transaction ID from Across submission',\n },\n (tx) => {\n tx.requiredTransactionIds ??= [];\n tx.requiredTransactionIds.push(transactionId);\n },\n );\n },\n );\n\n let result: { result: Promise<string> } | undefined;\n const { excludeNativeTokenForFee, gasFeeToken } = gasPayment;\n\n try {\n if (transactions.length === 1) {\n result = await messenger.call(\n 'TransactionController:addTransaction',\n transactions[0].params,\n {\n excludeNativeTokenForFee,\n gasFeeToken,\n networkClientId,\n origin: ORIGIN_METAMASK,\n isInternal: true,\n requireApproval: false,\n type: transactions[0].type,\n },\n );\n } else {\n const batchTransactions = transactions.map(({ params, type }) => ({\n params: toBatchTransactionParams(params),\n type,\n }));\n\n await messenger.call('TransactionController:addTransactionBatch', {\n disable7702: !submitAs7702,\n disableHook: submitAs7702,\n disableSequential: submitAs7702,\n excludeNativeTokenForFee,\n from,\n gasFeeToken,\n gasLimit7702,\n networkClientId,\n origin: ORIGIN_METAMASK,\n isInternal: true,\n requireApproval: false,\n transactions: batchTransactions,\n });\n }\n } finally {\n end();\n }\n\n if (result) {\n const txHash = await result.result;\n log('Submitted transaction', txHash);\n }\n\n await Promise.all(\n transactionIds.map((txId) => waitForTransactionConfirmed(txId, messenger)),\n );\n\n logGasPaymentOutcome(\n gasPayment,\n transactionIds.map((txId) => getTransaction(txId, messenger)),\n );\n\n const hash = transactionIds.length\n ? getTransaction(transactionIds.slice(-1)[0], messenger)?.hash\n : undefined;\n\n return await waitForAcrossCompletion(hash as Hex | undefined, messenger);\n}\n\ntype AcrossStatusResponse = {\n depositId?: number | string;\n depositTxnRef?: Hex;\n status?: string;\n destinationTxHash?: Hex;\n fillTxnRef?: Hex;\n fillTxHash?: Hex;\n txHash?: Hex;\n};\n\n/**\n * Poll Across until a submitted deposit reaches a terminal status.\n *\n * @param transactionHash - Source-chain deposit transaction hash.\n * @param messenger - Controller messenger.\n * @returns Destination/fill transaction hash when available, otherwise the source hash.\n */\nasync function waitForAcrossCompletion(\n transactionHash: Hex | undefined,\n messenger: TransactionPayControllerMessenger,\n): Promise<Hex | undefined> {\n if (!transactionHash) {\n return transactionHash;\n }\n\n const config = getPayStrategiesConfig(messenger);\n const params = new URLSearchParams({\n depositTxnRef: transactionHash,\n });\n const url = `${config.across.apiBase}/deposit/status?${params.toString()}`;\n\n let attempt = 0;\n\n while (true) {\n attempt += 1;\n let status: AcrossStatusResponse;\n\n try {\n const response = await successfulFetch(url, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n },\n });\n status = (await response.json()) as AcrossStatusResponse;\n } catch (error) {\n log('Across status polling request failed', {\n attempt,\n error: String(error),\n transactionHash,\n });\n\n await new Promise((resolve) =>\n setTimeout(resolve, ACROSS_STATUS_POLL_INTERVAL),\n );\n continue;\n }\n\n const normalizedStatus = status.status?.toLowerCase();\n\n log('Polled Across status', {\n attempt,\n status: normalizedStatus,\n transactionHash,\n });\n\n if (\n normalizedStatus &&\n ['completed', 'filled', 'success'].includes(normalizedStatus)\n ) {\n return (\n status.destinationTxHash ??\n status.fillTxnRef ??\n status.fillTxHash ??\n status.txHash ??\n transactionHash\n );\n }\n\n if (\n normalizedStatus &&\n ['error', 'failed', 'refund', 'refunded'].includes(normalizedStatus)\n ) {\n throw new Error(`Across request failed with status: ${normalizedStatus}`);\n }\n\n await new Promise((resolve) =>\n setTimeout(resolve, ACROSS_STATUS_POLL_INTERVAL),\n );\n }\n}\n\n/**\n * Check whether submit should estimate a 7702 batch gas limit.\n *\n * This is needed for Predict withdraw post-quote flows that pay source-chain\n * gas with the source token, because the final submit batch can differ from the\n * batch shape that Across quoted.\n *\n * @param args - Check arguments.\n * @param args.isGasFeeTokenPayment - Whether source-chain gas is paid with a gas fee token.\n * @param args.parentTransaction - Original transaction metadata.\n * @param args.quote - Across quote selected for execution.\n * @returns Whether submit should try to estimate the final 7702 batch gas.\n */\nfunction shouldEstimate7702SubmitBatch({\n isGasFeeTokenPayment,\n parentTransaction,\n quote,\n}: {\n isGasFeeTokenPayment: boolean;\n parentTransaction: TransactionMeta;\n quote: TransactionPayQuote<AcrossQuote>;\n}): boolean {\n return (\n hasTransactionType(parentTransaction, [TransactionType.predictWithdraw]) &&\n quote.request.isPostQuote === true &&\n isGasFeeTokenPayment\n );\n}\n\n/**\n * Estimate the 7702 batch gas limit for the actual submit payload.\n *\n * Quotes can contain a combined 7702 gas limit that only covered the Across\n * approval/swap legs. When submit prepends the original transaction, estimate\n * the final batch shape so the gas limit covers every submitted leg.\n *\n * @param args - Estimation arguments.\n * @param args.chainId - Source chain ID.\n * @param args.from - Sender address.\n * @param args.messenger - Controller messenger.\n * @param args.orderedTransactions - Across approval/swap legs in submission order.\n * @param args.parentTransaction - Original transaction that may be prepended.\n * @param args.shouldPrependOriginalTransaction - Whether to include the original transaction in the estimate.\n * @returns Hex gas limit, or `undefined` when estimation is unavailable.\n */\nasync function estimateSubmitBatchGasLimit7702({\n chainId,\n from,\n messenger,\n orderedTransactions,\n parentTransaction,\n shouldPrependOriginalTransaction,\n}: {\n chainId: Hex;\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n orderedTransactions: ReturnType<typeof getAcrossOrderedTransactions>;\n parentTransaction: TransactionMeta;\n shouldPrependOriginalTransaction: boolean;\n}): Promise<Hex | undefined> {\n if (!accountSupports7702(messenger, from)) {\n return undefined;\n }\n\n const originalTransaction = shouldPrependOriginalTransaction\n ? [buildOriginalTransaction(parentTransaction)]\n : [];\n\n const acrossTransactions = orderedTransactions.map((transaction) => ({\n params: buildTransactionParams(from, {\n chainId: transaction.chainId,\n data: transaction.data,\n maxFeePerGas: transaction.maxFeePerGas,\n maxPriorityFeePerGas: transaction.maxPriorityFeePerGas,\n to: transaction.to,\n value: transaction.value,\n }),\n type: transaction.type,\n }));\n\n const transactions = [...originalTransaction, ...acrossTransactions];\n\n try {\n const result = await messenger.call(\n 'TransactionController:estimateGasBatch',\n {\n chainId,\n from,\n transactions: transactions.map(({ params }) =>\n toBatchTransactionParams(params),\n ),\n },\n );\n\n // Older TransactionController versions return no `mode`, so detect a\n // combined EIP-7702 gas limit from the number of gas limits instead.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const is7702Result =\n result.mode === undefined\n ? result.gasLimits.length === 1\n : result.mode === 'eip7702';\n\n if (!is7702Result) {\n return undefined;\n }\n\n const gasLimit = Math.ceil(\n result.gasLimits[0] * getGasBuffer(messenger, chainId),\n );\n\n return toHex(gasLimit);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Build the original parent transaction as a prepared batch leg.\n *\n * @param transaction - Original transaction metadata.\n * @param gasLimit - Optional gas limit to pin on the original leg.\n * @returns Prepared transaction params and transaction type for the original leg.\n */\nfunction buildOriginalTransaction(\n transaction: TransactionMeta,\n gasLimit?: number,\n): PreparedAcrossTransaction {\n return {\n params: {\n data: transaction.txParams.data,\n from: transaction.txParams.from,\n gas: gasLimit === undefined ? undefined : toHex(gasLimit),\n to: transaction.txParams.to,\n value: transaction.txParams.value,\n },\n type: getOriginalTransactionType(transaction),\n };\n}\n\n/**\n * Get the transaction type to use for the original batch leg.\n *\n * @param transaction - Original transaction metadata.\n * @returns `predictWithdraw` for Predict withdrawals; otherwise the original type.\n */\nfunction getOriginalTransactionType(\n transaction: TransactionMeta,\n): TransactionMeta['type'] {\n if (hasTransactionType(transaction, [TransactionType.predictWithdraw])) {\n return TransactionType.predictWithdraw;\n }\n\n return transaction.type;\n}\n\n/**\n * Check whether the original transaction already has a usable gas limit.\n *\n * @param transaction - Original transaction metadata.\n * @returns Whether the original or nested transaction gas is a positive integer.\n */\nfunction hasOriginalTransactionGas(transaction: TransactionMeta): boolean {\n return getOriginalTransactionGas(transaction) !== undefined;\n}\n\n/**\n * Get the transaction type for the Across bridge/deposit leg.\n *\n * @param transaction - Original parent transaction.\n * @returns Across-specific transaction type for known flows, or the original type.\n */\nfunction getAcrossDepositType(transaction: TransactionMeta): TransactionType {\n if (hasTransactionType(transaction, [TransactionType.predictWithdraw])) {\n return TransactionType.predictAcrossWithdraw;\n }\n\n if (transaction.type && PERPS_DEPOSIT_TYPES.includes(transaction.type)) {\n return TransactionType.perpsAcrossDeposit;\n }\n\n switch (transaction.type) {\n case TransactionType.predictDeposit:\n return TransactionType.predictAcrossDeposit;\n case undefined:\n return TransactionType.perpsAcrossDeposit;\n default:\n return transaction.type;\n }\n}\n\n/**\n * Build TransactionController params for an Across approval or swap leg.\n *\n * @param from - Sender address.\n * @param params - Across transaction fields.\n * @param params.chainId - Source chain ID.\n * @param params.data - Transaction calldata.\n * @param params.gasLimit - Optional gas limit.\n * @param params.to - Recipient contract address.\n * @param params.value - Optional native value.\n * @param params.maxFeePerGas - Optional EIP-1559 max fee.\n * @param params.maxPriorityFeePerGas - Optional EIP-1559 priority fee.\n * @returns TransactionController params.\n */\nfunction buildTransactionParams(\n from: Hex,\n params: {\n chainId: number;\n data: Hex;\n gasLimit?: number;\n to: Hex;\n value?: Hex;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n },\n): TransactionParams {\n const value = toHex(params.value ?? '0x0');\n\n return {\n data: params.data,\n from,\n gas: params.gasLimit === undefined ? undefined : toHex(params.gasLimit),\n maxFeePerGas: normalizeOptionalHex(params.maxFeePerGas),\n maxPriorityFeePerGas: normalizeOptionalHex(params.maxPriorityFeePerGas),\n to: params.to,\n value,\n };\n}\n\n/**\n * Normalize an optional numeric string or hex string into a hex value.\n *\n * @param value - Optional value to normalize.\n * @returns Hex value, or `undefined` when no value is provided.\n */\nfunction normalizeOptionalHex(value?: string): Hex | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n return toHex(value);\n}\n\n/**\n * Convert full TransactionController params into batch transaction params.\n *\n * @param params - Transaction params.\n * @returns Batch-compatible transaction params.\n */\nfunction toBatchTransactionParams(\n params: TransactionParams,\n): BatchTransactionParams {\n return {\n data: params.data as Hex | undefined,\n gas: params.gas as Hex | undefined,\n maxFeePerGas: params.maxFeePerGas as Hex | undefined,\n maxPriorityFeePerGas: params.maxPriorityFeePerGas as Hex | undefined,\n to: params.to as Hex | undefined,\n value: params.value as Hex | undefined,\n };\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import type { PayStrategy, PayStrategyExecuteRequest, PayStrategyGetQuotesRequest, TransactionPayQuote } from '../../types.js';
2
2
  import type { FiatQuote } from './types.js';
3
3
  export declare class FiatStrategy implements PayStrategy<FiatQuote> {
4
+ supports(request: PayStrategyGetQuotesRequest): boolean;
4
5
  getQuotes(request: PayStrategyGetQuotesRequest): Promise<TransactionPayQuote<FiatQuote>[]>;
5
6
  execute(request: PayStrategyExecuteRequest<FiatQuote>): ReturnType<PayStrategy<FiatQuote>['execute']>;
6
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"FiatStrategy.d.ts","sourceRoot":"","sources":["../../../src/strategy/fiat/FiatStrategy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,yBAAyB,EACzB,2BAA2B,EAC3B,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAIxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAI5C,qBAAa,YAAa,YAAW,WAAW,CAAC,SAAS,CAAC;IACnD,SAAS,CACb,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,mBAAmB,CAAC,SAAS,CAAC,EAAE,CAAC,CAE3C;IAEK,OAAO,CACX,OAAO,EAAE,yBAAyB,CAAC,SAAS,CAAC,GAC5C,UAAU,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,CAY/C;CACF"}
1
+ {"version":3,"file":"FiatStrategy.d.ts","sourceRoot":"","sources":["../../../src/strategy/fiat/FiatStrategy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,yBAAyB,EACzB,2BAA2B,EAC3B,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAKxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAI5C,qBAAa,YAAa,YAAW,WAAW,CAAC,SAAS,CAAC;IACzD,QAAQ,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAEtD;IAEK,SAAS,CACb,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,mBAAmB,CAAC,SAAS,CAAC,EAAE,CAAC,CAE3C;IAEK,OAAO,CACX,OAAO,EAAE,yBAAyB,CAAC,SAAS,CAAC,GAC5C,UAAU,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,CAY/C;CACF"}
@@ -1,8 +1,12 @@
1
1
  import { prefixError } from '../../utils/error-prefix.js';
2
+ import { isEvmQuoteRequest } from '../../utils/token.js';
2
3
  import { getFiatQuotes } from './fiat-quotes.js';
3
4
  import { submitFiatQuotes } from './fiat-submit.js';
4
5
  const ERROR_PREFIX = 'Fiat: ';
5
6
  export class FiatStrategy {
7
+ supports(request) {
8
+ return request.requests.every(isEvmQuoteRequest);
9
+ }
6
10
  async getQuotes(request) {
7
11
  return getFiatQuotes(request);
8
12
  }
@@ -1 +1 @@
1
- {"version":3,"file":"FiatStrategy.js","sourceRoot":"","sources":["../../../src/strategy/fiat/FiatStrategy.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAGpD,MAAM,YAAY,GAAG,QAAQ,CAAC;AAE9B,MAAM,OAAO,YAAY;IACvB,KAAK,CAAC,SAAS,CACb,OAAoC;QAEpC,OAAO,aAAa,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;IAED,KAAK,CAAC,OAAO,CACX,OAA6C;QAE7C,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,gBAAgB,CAAC,OAAO,CAAC,CAAC;YAE/C,IAAI,MAAM,CAAC,eAAe,KAAK,SAAS,EAAE,CAAC;gBACzC,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;YAC9C,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,WAAW,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;QACzC,CAAC;IACH,CAAC;CACF","sourcesContent":["import type {\n PayStrategy,\n PayStrategyExecuteRequest,\n PayStrategyGetQuotesRequest,\n TransactionPayQuote,\n} from '../../types.js';\nimport { prefixError } from '../../utils/error-prefix.js';\nimport { getFiatQuotes } from './fiat-quotes.js';\nimport { submitFiatQuotes } from './fiat-submit.js';\nimport type { FiatQuote } from './types.js';\n\nconst ERROR_PREFIX = 'Fiat: ';\n\nexport class FiatStrategy implements PayStrategy<FiatQuote> {\n async getQuotes(\n request: PayStrategyGetQuotesRequest,\n ): Promise<TransactionPayQuote<FiatQuote>[]> {\n return getFiatQuotes(request);\n }\n\n async execute(\n request: PayStrategyExecuteRequest<FiatQuote>,\n ): ReturnType<PayStrategy<FiatQuote>['execute']> {\n try {\n const result = await submitFiatQuotes(request);\n\n if (result.transactionHash === undefined) {\n throw new Error('Missing transaction hash');\n }\n\n return result;\n } catch (error) {\n throw prefixError(error, ERROR_PREFIX);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"FiatStrategy.js","sourceRoot":"","sources":["../../../src/strategy/fiat/FiatStrategy.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAGpD,MAAM,YAAY,GAAG,QAAQ,CAAC;AAE9B,MAAM,OAAO,YAAY;IACvB,QAAQ,CAAC,OAAoC;QAC3C,OAAO,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;IACnD,CAAC;IAED,KAAK,CAAC,SAAS,CACb,OAAoC;QAEpC,OAAO,aAAa,CAAC,OAAO,CAAC,CAAC;IAChC,CAAC;IAED,KAAK,CAAC,OAAO,CACX,OAA6C;QAE7C,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,gBAAgB,CAAC,OAAO,CAAC,CAAC;YAE/C,IAAI,MAAM,CAAC,eAAe,KAAK,SAAS,EAAE,CAAC;gBACzC,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;YAC9C,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,WAAW,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;QACzC,CAAC;IACH,CAAC;CACF","sourcesContent":["import type {\n PayStrategy,\n PayStrategyExecuteRequest,\n PayStrategyGetQuotesRequest,\n TransactionPayQuote,\n} from '../../types.js';\nimport { prefixError } from '../../utils/error-prefix.js';\nimport { isEvmQuoteRequest } from '../../utils/token.js';\nimport { getFiatQuotes } from './fiat-quotes.js';\nimport { submitFiatQuotes } from './fiat-submit.js';\nimport type { FiatQuote } from './types.js';\n\nconst ERROR_PREFIX = 'Fiat: ';\n\nexport class FiatStrategy implements PayStrategy<FiatQuote> {\n supports(request: PayStrategyGetQuotesRequest): boolean {\n return request.requests.every(isEvmQuoteRequest);\n }\n\n async getQuotes(\n request: PayStrategyGetQuotesRequest,\n ): Promise<TransactionPayQuote<FiatQuote>[]> {\n return getFiatQuotes(request);\n }\n\n async execute(\n request: PayStrategyExecuteRequest<FiatQuote>,\n ): ReturnType<PayStrategy<FiatQuote>['execute']> {\n try {\n const result = await submitFiatQuotes(request);\n\n if (result.transactionHash === undefined) {\n throw new Error('Missing transaction hash');\n }\n\n return result;\n } catch (error) {\n throw prefixError(error, ERROR_PREFIX);\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"fiat-direct-musd.d.ts","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-direct-musd.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,UAAU,EACX,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAM3C,OAAO,KAAK,EACV,yBAAyB,EACzB,2BAA2B,EAE3B,2BAA2B,EAC3B,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAMxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAU5C;;;;;;;;;;;GAWG;AACH,wBAAsB,sBAAsB,CAAC,EAC3C,UAAU,EACV,iBAAiB,EACjB,SAAS,EACT,mBAAmB,EACnB,aAAa,EACb,aAAa,GACd,EAAE;IACD,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,SAAS,EAAE,2BAA2B,CAAC,WAAW,CAAC,CAAC;IACpD,mBAAmB,EAAE,GAAG,CAAC;IACzB,aAAa,EAAE,2BAA2B,CAAC;IAC3C,aAAa,EAAE,MAAM,CAAC;CACvB,GAAG,OAAO,CAAC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;AAED;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,IAAI,CAAC,mBAAmB,CAAC,OAAO,CAAC,EAAE,SAAS,CAAC,GAAG,SAAS,GAC/D,OAAO,CAET;AAED;;;;;;;GAOG;AACH,wBAAsB,mCAAmC,CAAC,EACxD,KAAK,EACL,OAAO,GACR,EAAE;IACD,KAAK,EAAE,UAAU,CAAC;IAClB,OAAO,EAAE,yBAAyB,CAAC,SAAS,CAAC,CAAC;CAC/C,GAAG,OAAO,CAAC;IAAE,eAAe,CAAC,EAAE,GAAG,CAAA;CAAE,CAAC,CAiCrC"}
@@ -2,6 +2,7 @@ import { createModuleLogger } from '@metamask/utils';
2
2
  import { BigNumber } from 'bignumber.js';
3
3
  import { TransactionPayStrategy } from '../../constants.js';
4
4
  import { projectLogger } from '../../logger.js';
5
+ import { getCaipAccountId } from '../../utils/account.js';
5
6
  import { prefixError } from '../../utils/error-prefix.js';
6
7
  import { getFiatVaultDisabled } from '../../utils/feature-flags.js';
7
8
  import { submitSecondLeg } from '../../utils/second-leg.js';
@@ -134,6 +135,7 @@ function combineDirectMusdFiatQuote({ amountFiat, fiatQuote, messenger, moneyAcc
134
135
  const sourceAmountHuman = new BigNumber(sourceAmountRaw)
135
136
  .shiftedBy(-tokenInfo.decimals)
136
137
  .toString(10);
138
+ const sourceAssetId = buildCaipAssetType(MUSD_MONAD_FIAT_ASSET.chainId, MUSD_MONAD_FIAT_ASSET.address);
137
139
  return {
138
140
  // Direct mUSD is fee-on-top: the fee is added to the entered amount, so the
139
141
  // fees are NOT already inside the source amount and the total becomes
@@ -169,9 +171,9 @@ function combineDirectMusdFiatQuote({ amountFiat, fiatQuote, messenger, moneyAcc
169
171
  from: moneyAccountAddress,
170
172
  isDirectMusdMoneyAccount: true,
171
173
  recipient: moneyAccountAddress,
174
+ sourceAccountId: getCaipAccountId(sourceAssetId, moneyAccountAddress),
175
+ sourceAssetId,
172
176
  sourceBalanceRaw: sourceAmountRaw,
173
- sourceChainId: MUSD_MONAD_FIAT_ASSET.chainId,
174
- sourceTokenAddress: MUSD_MONAD_FIAT_ASSET.address,
175
177
  sourceTokenAmount: sourceAmountRaw,
176
178
  targetAmountMinimum: sourceAmountRaw,
177
179
  targetChainId: requiredToken.chainId,
@@ -1 +1 @@
1
- {"version":3,"file":"fiat-direct-musd.js","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-direct-musd.ts"],"names":[],"mappings":"AAKA,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;AAQhD,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,EACL,aAAa,EACb,uCAAuC,EACvC,kBAAkB,GACnB,MAAM,YAAY,CAAC;AAEpB,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,kBAAkB,CAAC,CAAC;AAClE,MAAM,wBAAwB,GAAG,eAAe,CAAC;AAEjD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,EAC3C,UAAU,EACV,iBAAiB,EACjB,SAAS,EACT,mBAAmB,EACnB,aAAa,EACb,aAAa,GAQd;IACC,IAAI,CAAC;QACH,MAAM,cAAc,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;QAE1C,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,cAA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MAAM,GAAG,GAAG,IAAI,SAAS,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC;IACtC,OAAO,GAAG,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,sBAAsB,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import type {\n Quote as RampsQuote,\n RampsOrder,\n} from '@metamask/ramps-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 PayStrategyExecuteRequest,\n PayStrategyGetQuotesRequest,\n TransactionFiatPayment,\n TransactionPayRequiredToken,\n TransactionPayQuote,\n} from '../../types.js';\nimport { prefixError } from '../../utils/error-prefix.js';\nimport { getFiatVaultDisabled } from '../../utils/feature-flags.js';\nimport { submitSecondLeg } from '../../utils/second-leg.js';\nimport { buildCaipAssetType, getTokenInfo } from '../../utils/token.js';\nimport { MUSD_MONAD_FIAT_ASSET } from './constants.js';\nimport type { FiatQuote } from './types.js';\nimport {\n getRampsQuote,\n getRawSourceAmountFromOrderCryptoAmount,\n validateOrderAsset,\n} from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'fiat-direct-musd');\nconst DIRECT_MUSD_ERROR_PREFIX = 'Direct mUSD: ';\n\n/**\n * Returns a direct mUSD fiat quote to the Money Account.\n *\n * @param options - Direct quote options.\n * @param options.amountFiat - Fiat amount entered by the user.\n * @param options.fiatPaymentMethod - Selected fiat payment method.\n * @param options.messenger - Controller messenger.\n * @param options.moneyAccountAddress - Money Account receiving the on-ramped mUSD.\n * @param options.requiredToken - Required token from the original Money Account transaction.\n * @param options.transactionId - Transaction ID for state updates and logs.\n * @returns Direct mUSD Fiat quote, or undefined when unavailable.\n */\nexport async function getDirectMusdFiatQuote({\n amountFiat,\n fiatPaymentMethod,\n messenger,\n moneyAccountAddress,\n requiredToken,\n transactionId,\n}: {\n amountFiat: string;\n fiatPaymentMethod: string;\n messenger: PayStrategyGetQuotesRequest['messenger'];\n moneyAccountAddress: Hex;\n requiredToken: TransactionPayRequiredToken;\n transactionId: string;\n}): Promise<TransactionPayQuote<FiatQuote> | undefined> {\n try {\n const adjustedAmount = Number(amountFiat);\n\n if (!Number.isFinite(adjustedAmount) || adjustedAmount <= 0) {\n throw new Error('Invalid fiat amount for direct mUSD quote');\n }\n\n // `getRampsQuote` requests `getQuoteWithFees`, so a Transak Native quote\n // already carries the native fee (fee-on-top for direct mUSD) in its\n // provider/network fee fields.\n const fiatQuote = await getRampsQuote({\n adjustedAmount,\n errorMessage: 'No matching ramps quote found for direct mUSD provider',\n fiatAsset: MUSD_MONAD_FIAT_ASSET,\n fiatPaymentMethod,\n messenger,\n walletAddress: moneyAccountAddress,\n });\n\n messenger.call('TransactionPayController:updateFiatPayment', {\n callback: (fiatPayment: TransactionFiatPayment) => {\n fiatPayment.rampsQuote = fiatQuote;\n fiatPayment.caipAssetId = buildCaipAssetType(\n MUSD_MONAD_FIAT_ASSET.chainId,\n MUSD_MONAD_FIAT_ASSET.address,\n );\n },\n transactionId,\n });\n\n log('Direct mUSD fiat quote flow', {\n amountFiat,\n moneyAccountAddress,\n transactionId,\n });\n\n return combineDirectMusdFiatQuote({\n amountFiat,\n fiatQuote,\n messenger,\n moneyAccountAddress,\n requiredToken,\n });\n } catch (error) {\n log('Direct mUSD fiat quote failed', { error, transactionId });\n return undefined;\n }\n}\n\n/**\n * Detects a direct mUSD Money Account quote from its stored request marker.\n *\n * @param quote - Quote to inspect.\n * @returns True when the quote originated from the direct mUSD fiat path.\n */\nexport function isDirectMusdMoneyAccountQuote(\n quote: Pick<TransactionPayQuote<unknown>, 'request'> | undefined,\n): boolean {\n return quote?.request.isDirectMusdMoneyAccount === true;\n}\n\n/**\n * Submits the direct mUSD post-Ramp path after fiat settlement.\n *\n * @param options - Submit options.\n * @param options.order - Completed fiat order.\n * @param options.request - Strategy execute request.\n * @returns Hash of the submitted direct mUSD transaction, if available.\n */\nexport async function submitDirectMusdAfterFiatCompletion({\n order,\n request,\n}: {\n order: RampsOrder;\n request: PayStrategyExecuteRequest<FiatQuote>;\n}): Promise<{ transactionHash?: Hex }> {\n const { messenger, transaction } = request;\n const moneyAccountAddress = transaction.txParams.from as Hex;\n\n try {\n validateOrderAsset({\n expectedAsset: MUSD_MONAD_FIAT_ASSET,\n orderCrypto: order.cryptoCurrency,\n transactionId: transaction.id,\n });\n\n // Kill switch: leave the on-ramped mUSD in the Money Account rather than\n // depositing it into the vault.\n if (getFiatVaultDisabled(messenger)) {\n log('Skipping vault deposit because the fiat vault is disabled', {\n moneyAccountAddress,\n transactionId: transaction.id,\n });\n\n return { transactionHash: '0x' };\n }\n\n return await submitSecondLeg({\n chainId: MUSD_MONAD_FIAT_ASSET.chainId,\n from: moneyAccountAddress,\n messenger,\n settlementHash: order.txHash as Hex | undefined,\n tokenAddress: MUSD_MONAD_FIAT_ASSET.address,\n transaction,\n });\n } catch (error) {\n throw prefixError(error, DIRECT_MUSD_ERROR_PREFIX);\n }\n}\n\nfunction combineDirectMusdFiatQuote({\n amountFiat,\n fiatQuote,\n messenger,\n moneyAccountAddress,\n requiredToken,\n}: {\n amountFiat: string;\n fiatQuote: RampsQuote;\n messenger: PayStrategyGetQuotesRequest['messenger'];\n moneyAccountAddress: Hex;\n requiredToken: TransactionPayRequiredToken;\n}): TransactionPayQuote<FiatQuote> {\n const tokenInfo = getTokenInfo(\n messenger,\n MUSD_MONAD_FIAT_ASSET.address,\n MUSD_MONAD_FIAT_ASSET.chainId,\n );\n\n if (!tokenInfo) {\n throw new Error('Unable to resolve mUSD token info for direct fiat quote');\n }\n\n const sourceAmountRaw = getRawSourceAmountFromOrderCryptoAmount({\n cryptoAmount: fiatQuote.quote.amountOut,\n decimals: tokenInfo.decimals,\n });\n // `getQuoteWithFees` already reconciled the fee split to the resolved\n // provider (for Transak Native, the native total split across provider and\n // network), so the provider/network fields can be mapped straight into the\n // fee buckets.\n const rampsProviderFee = getSafeFee(fiatQuote.quote.providerFee).toString(10);\n const rampsNetworkFee = getSafeFee(fiatQuote.quote.networkFee).toString(10);\n const rampsTotalFee = new BigNumber(rampsProviderFee)\n .plus(rampsNetworkFee)\n .toString(10);\n const targetAmountFiat = getDirectMusdTargetAmountFiat(fiatQuote, amountFiat);\n const sourceAmountHuman = new BigNumber(sourceAmountRaw)\n .shiftedBy(-tokenInfo.decimals)\n .toString(10);\n\n return {\n // Direct mUSD is fee-on-top: the fee is added to the entered amount, so the\n // fees are NOT already inside the source amount and the total becomes\n // amount + fees (see calculateTotals).\n areFeesIncludedInSourceAmount: false,\n dust: { fiat: '0', usd: '0' },\n estimatedDuration: 0,\n fees: {\n metaMask: { fiat: '0', usd: '0' },\n provider: { fiat: rampsProviderFee, usd: rampsProviderFee },\n providerFiat: { fiat: rampsTotalFee, usd: rampsTotalFee },\n sourceNetwork: {\n estimate: {\n fiat: rampsNetworkFee,\n human: '0',\n raw: '0',\n usd: rampsNetworkFee,\n },\n max: {\n fiat: rampsNetworkFee,\n human: '0',\n raw: '0',\n usd: rampsNetworkFee,\n },\n },\n targetNetwork: { fiat: '0', usd: '0' },\n },\n original: {\n rampsQuote: fiatQuote,\n relayQuote: undefined,\n },\n request: {\n from: moneyAccountAddress,\n isDirectMusdMoneyAccount: true,\n recipient: moneyAccountAddress,\n sourceBalanceRaw: sourceAmountRaw,\n sourceChainId: MUSD_MONAD_FIAT_ASSET.chainId,\n sourceTokenAddress: MUSD_MONAD_FIAT_ASSET.address,\n sourceTokenAmount: sourceAmountRaw,\n targetAmountMinimum: sourceAmountRaw,\n targetChainId: requiredToken.chainId,\n targetTokenAddress: requiredToken.address,\n },\n sourceAmount: {\n fiat: amountFiat,\n human: sourceAmountHuman,\n raw: sourceAmountRaw,\n usd: amountFiat,\n },\n strategy: TransactionPayStrategy.Fiat,\n targetAmount: { fiat: targetAmountFiat, usd: targetAmountFiat },\n };\n}\n\n/**\n * Resolves the fiat value of the received mUSD for a direct deposit quote.\n *\n * Prefers the quote's `amountOutInFiat`. When that is missing, it falls back to\n * the entered fiat amount rather than `amountOut`, which is a crypto amount and\n * would otherwise put crypto units into a fiat field.\n *\n * @param fiatQuote - The resolved ramps quote.\n * @param amountFiat - The entered fiat amount, used as the fallback.\n * @returns The target amount in fiat.\n */\nfunction getDirectMusdTargetAmountFiat(\n fiatQuote: RampsQuote,\n amountFiat: string,\n): string {\n const amountOutInFiat = new BigNumber(fiatQuote.quote.amountOutInFiat ?? NaN);\n if (amountOutInFiat.isFinite() && amountOutInFiat.isGreaterThanOrEqualTo(0)) {\n return amountOutInFiat.toString(10);\n }\n\n return amountFiat;\n}\n\nfunction getSafeFee(value: BigNumber.Value | undefined): BigNumber {\n const fee = new BigNumber(value ?? 0);\n return fee.isFinite() && fee.isGreaterThanOrEqualTo(0)\n ? fee\n : new BigNumber(0);\n}\n"]}
1
+ {"version":3,"file":"fiat-direct-musd.js","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-direct-musd.ts"],"names":[],"mappings":"AAKA,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;AAQhD,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB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ACpB,GAAG,EAAE,UAAU;SAChB;QACD,QAAQ,EAAE,sBAAsB,CAAC,IAAI;QACrC,YAAY,EAAE,EAAE,IAAI,EAAE,gBAAgB,EAAE,GAAG,EAAE,gBAAgB,EAAE;KAChE,CAAC;AACJ,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAS,6BAA6B,CACpC,SAAqB,EACrB,UAAkB;IAElB,MAAM,eAAe,GAAG,IAAI,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,eAAe,IAAI,GAAG,CAAC,CAAC;IAC9E,IAAI,eAAe,CAAC,QAAQ,EAAE,IAAI,eAAe,CAAC,sBAAsB,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5E,OAAO,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IACtC,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,SAAS,UAAU,CAAC,KAAkC;IACpD,MAAM,GAAG,GAAG,IAAI,SAAS,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC;IACtC,OAAO,GAAG,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,sBAAsB,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import type {\n Quote as RampsQuote,\n RampsOrder,\n} from '@metamask/ramps-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 PayStrategyExecuteRequest,\n PayStrategyGetQuotesRequest,\n TransactionFiatPayment,\n TransactionPayRequiredToken,\n TransactionPayQuote,\n} from '../../types.js';\nimport { getCaipAccountId } from '../../utils/account.js';\nimport { prefixError } from '../../utils/error-prefix.js';\nimport { getFiatVaultDisabled } from '../../utils/feature-flags.js';\nimport { submitSecondLeg } from '../../utils/second-leg.js';\nimport { buildCaipAssetType, getTokenInfo } from '../../utils/token.js';\nimport { MUSD_MONAD_FIAT_ASSET } from './constants.js';\nimport type { FiatQuote } from './types.js';\nimport {\n getRampsQuote,\n getRawSourceAmountFromOrderCryptoAmount,\n validateOrderAsset,\n} from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'fiat-direct-musd');\nconst DIRECT_MUSD_ERROR_PREFIX = 'Direct mUSD: ';\n\n/**\n * Returns a direct mUSD fiat quote to the Money Account.\n *\n * @param options - Direct quote options.\n * @param options.amountFiat - Fiat amount entered by the user.\n * @param options.fiatPaymentMethod - Selected fiat payment method.\n * @param options.messenger - Controller messenger.\n * @param options.moneyAccountAddress - Money Account receiving the on-ramped mUSD.\n * @param options.requiredToken - Required token from the original Money Account transaction.\n * @param options.transactionId - Transaction ID for state updates and logs.\n * @returns Direct mUSD Fiat quote, or undefined when unavailable.\n */\nexport async function getDirectMusdFiatQuote({\n amountFiat,\n fiatPaymentMethod,\n messenger,\n moneyAccountAddress,\n requiredToken,\n transactionId,\n}: {\n amountFiat: string;\n fiatPaymentMethod: string;\n messenger: PayStrategyGetQuotesRequest['messenger'];\n moneyAccountAddress: Hex;\n requiredToken: TransactionPayRequiredToken;\n transactionId: string;\n}): Promise<TransactionPayQuote<FiatQuote> | undefined> {\n try {\n const adjustedAmount = Number(amountFiat);\n\n if (!Number.isFinite(adjustedAmount) || adjustedAmount <= 0) {\n throw new Error('Invalid fiat amount for direct mUSD quote');\n }\n\n // `getRampsQuote` requests `getQuoteWithFees`, so a Transak Native quote\n // already carries the native fee (fee-on-top for direct mUSD) in its\n // provider/network fee fields.\n const fiatQuote = await getRampsQuote({\n adjustedAmount,\n errorMessage: 'No matching ramps quote found for direct mUSD provider',\n fiatAsset: MUSD_MONAD_FIAT_ASSET,\n fiatPaymentMethod,\n messenger,\n walletAddress: moneyAccountAddress,\n });\n\n messenger.call('TransactionPayController:updateFiatPayment', {\n callback: (fiatPayment: TransactionFiatPayment) => {\n fiatPayment.rampsQuote = fiatQuote;\n fiatPayment.caipAssetId = buildCaipAssetType(\n MUSD_MONAD_FIAT_ASSET.chainId,\n MUSD_MONAD_FIAT_ASSET.address,\n );\n },\n transactionId,\n });\n\n log('Direct mUSD fiat quote flow', {\n amountFiat,\n moneyAccountAddress,\n transactionId,\n });\n\n return combineDirectMusdFiatQuote({\n amountFiat,\n fiatQuote,\n messenger,\n moneyAccountAddress,\n requiredToken,\n });\n } catch (error) {\n log('Direct mUSD fiat quote failed', { error, transactionId });\n return undefined;\n }\n}\n\n/**\n * Detects a direct mUSD Money Account quote from its stored request marker.\n *\n * @param quote - Quote to inspect.\n * @returns True when the quote originated from the direct mUSD fiat path.\n */\nexport function isDirectMusdMoneyAccountQuote(\n quote: Pick<TransactionPayQuote<unknown>, 'request'> | undefined,\n): boolean {\n return quote?.request.isDirectMusdMoneyAccount === true;\n}\n\n/**\n * Submits the direct mUSD post-Ramp path after fiat settlement.\n *\n * @param options - Submit options.\n * @param options.order - Completed fiat order.\n * @param options.request - Strategy execute request.\n * @returns Hash of the submitted direct mUSD transaction, if available.\n */\nexport async function submitDirectMusdAfterFiatCompletion({\n order,\n request,\n}: {\n order: RampsOrder;\n request: PayStrategyExecuteRequest<FiatQuote>;\n}): Promise<{ transactionHash?: Hex }> {\n const { messenger, transaction } = request;\n const moneyAccountAddress = transaction.txParams.from as Hex;\n\n try {\n validateOrderAsset({\n expectedAsset: MUSD_MONAD_FIAT_ASSET,\n orderCrypto: order.cryptoCurrency,\n transactionId: transaction.id,\n });\n\n // Kill switch: leave the on-ramped mUSD in the Money Account rather than\n // depositing it into the vault.\n if (getFiatVaultDisabled(messenger)) {\n log('Skipping vault deposit because the fiat vault is disabled', {\n moneyAccountAddress,\n transactionId: transaction.id,\n });\n\n return { transactionHash: '0x' };\n }\n\n return await submitSecondLeg({\n chainId: MUSD_MONAD_FIAT_ASSET.chainId,\n from: moneyAccountAddress,\n messenger,\n settlementHash: order.txHash as Hex | undefined,\n tokenAddress: MUSD_MONAD_FIAT_ASSET.address,\n transaction,\n });\n } catch (error) {\n throw prefixError(error, DIRECT_MUSD_ERROR_PREFIX);\n }\n}\n\nfunction combineDirectMusdFiatQuote({\n amountFiat,\n fiatQuote,\n messenger,\n moneyAccountAddress,\n requiredToken,\n}: {\n amountFiat: string;\n fiatQuote: RampsQuote;\n messenger: PayStrategyGetQuotesRequest['messenger'];\n moneyAccountAddress: Hex;\n requiredToken: TransactionPayRequiredToken;\n}): TransactionPayQuote<FiatQuote> {\n const tokenInfo = getTokenInfo(\n messenger,\n MUSD_MONAD_FIAT_ASSET.address,\n MUSD_MONAD_FIAT_ASSET.chainId,\n );\n\n if (!tokenInfo) {\n throw new Error('Unable to resolve mUSD token info for direct fiat quote');\n }\n\n const sourceAmountRaw = getRawSourceAmountFromOrderCryptoAmount({\n cryptoAmount: fiatQuote.quote.amountOut,\n decimals: tokenInfo.decimals,\n });\n // `getQuoteWithFees` already reconciled the fee split to the resolved\n // provider (for Transak Native, the native total split across provider and\n // network), so the provider/network fields can be mapped straight into the\n // fee buckets.\n const rampsProviderFee = getSafeFee(fiatQuote.quote.providerFee).toString(10);\n const rampsNetworkFee = getSafeFee(fiatQuote.quote.networkFee).toString(10);\n const rampsTotalFee = new BigNumber(rampsProviderFee)\n .plus(rampsNetworkFee)\n .toString(10);\n const targetAmountFiat = getDirectMusdTargetAmountFiat(fiatQuote, amountFiat);\n const sourceAmountHuman = new BigNumber(sourceAmountRaw)\n .shiftedBy(-tokenInfo.decimals)\n .toString(10);\n const sourceAssetId = buildCaipAssetType(\n MUSD_MONAD_FIAT_ASSET.chainId,\n MUSD_MONAD_FIAT_ASSET.address,\n );\n\n return {\n // Direct mUSD is fee-on-top: the fee is added to the entered amount, so the\n // fees are NOT already inside the source amount and the total becomes\n // amount + fees (see calculateTotals).\n areFeesIncludedInSourceAmount: false,\n dust: { fiat: '0', usd: '0' },\n estimatedDuration: 0,\n fees: {\n metaMask: { fiat: '0', usd: '0' },\n provider: { fiat: rampsProviderFee, usd: rampsProviderFee },\n providerFiat: { fiat: rampsTotalFee, usd: rampsTotalFee },\n sourceNetwork: {\n estimate: {\n fiat: rampsNetworkFee,\n human: '0',\n raw: '0',\n usd: rampsNetworkFee,\n },\n max: {\n fiat: rampsNetworkFee,\n human: '0',\n raw: '0',\n usd: rampsNetworkFee,\n },\n },\n targetNetwork: { fiat: '0', usd: '0' },\n },\n original: {\n rampsQuote: fiatQuote,\n relayQuote: undefined,\n },\n request: {\n from: moneyAccountAddress,\n isDirectMusdMoneyAccount: true,\n recipient: moneyAccountAddress,\n sourceAccountId: getCaipAccountId(sourceAssetId, moneyAccountAddress),\n sourceAssetId,\n sourceBalanceRaw: sourceAmountRaw,\n sourceTokenAmount: sourceAmountRaw,\n targetAmountMinimum: sourceAmountRaw,\n targetChainId: requiredToken.chainId,\n targetTokenAddress: requiredToken.address,\n },\n sourceAmount: {\n fiat: amountFiat,\n human: sourceAmountHuman,\n raw: sourceAmountRaw,\n usd: amountFiat,\n },\n strategy: TransactionPayStrategy.Fiat,\n targetAmount: { fiat: targetAmountFiat, usd: targetAmountFiat },\n };\n}\n\n/**\n * Resolves the fiat value of the received mUSD for a direct deposit quote.\n *\n * Prefers the quote's `amountOutInFiat`. When that is missing, it falls back to\n * the entered fiat amount rather than `amountOut`, which is a crypto amount and\n * would otherwise put crypto units into a fiat field.\n *\n * @param fiatQuote - The resolved ramps quote.\n * @param amountFiat - The entered fiat amount, used as the fallback.\n * @returns The target amount in fiat.\n */\nfunction getDirectMusdTargetAmountFiat(\n fiatQuote: RampsQuote,\n amountFiat: string,\n): string {\n const amountOutInFiat = new BigNumber(fiatQuote.quote.amountOutInFiat ?? NaN);\n if (amountOutInFiat.isFinite() && amountOutInFiat.isGreaterThanOrEqualTo(0)) {\n return amountOutInFiat.toString(10);\n }\n\n return amountFiat;\n}\n\nfunction getSafeFee(value: BigNumber.Value | undefined): BigNumber {\n const fee = new BigNumber(value ?? 0);\n return fee.isFinite() && fee.isGreaterThanOrEqualTo(0)\n ? fee\n : new BigNumber(0);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"fiat-quotes.d.ts","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-quotes.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EACV,2BAA2B,EAI3B,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAYxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAiB5C;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CACjC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,mBAAmB,CAAC,SAAS,CAAC,EAAE,CAAC,CA0C3C"}
1
+ {"version":3,"file":"fiat-quotes.d.ts","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-quotes.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EACV,2BAA2B,EAI3B,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAaxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAiB5C;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CACjC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,mBAAmB,CAAC,SAAS,CAAC,EAAE,CAAC,CA0C3C"}