@metamask-previews/transaction-pay-controller 30.0.3-preview-44b7ded21 → 30.1.0-preview-2750df1dc

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 (49) hide show
  1. package/CHANGELOG.md +18 -1
  2. package/dist/strategy/fiat/fiat-direct-musd.d.ts.map +1 -1
  3. package/dist/strategy/fiat/fiat-direct-musd.js +17 -12
  4. package/dist/strategy/fiat/fiat-direct-musd.js.map +1 -1
  5. package/dist/strategy/fiat/fiat-submit.js +1 -1
  6. package/dist/strategy/fiat/fiat-submit.js.map +1 -1
  7. package/dist/strategy/fiat/utils.d.ts +6 -24
  8. package/dist/strategy/fiat/utils.d.ts.map +1 -1
  9. package/dist/strategy/fiat/utils.js +21 -37
  10. package/dist/strategy/fiat/utils.js.map +1 -1
  11. package/dist/strategy/relay/relay-quotes.d.ts.map +1 -1
  12. package/dist/strategy/relay/relay-quotes.js +10 -40
  13. package/dist/strategy/relay/relay-quotes.js.map +1 -1
  14. package/dist/strategy/relay/relay-submit.d.ts.map +1 -1
  15. package/dist/strategy/relay/relay-submit.js +59 -110
  16. package/dist/strategy/relay/relay-submit.js.map +1 -1
  17. package/dist/strategy/server/server-api.d.ts +2 -2
  18. package/dist/strategy/server/server-api.d.ts.map +1 -1
  19. package/dist/strategy/server/server-api.js.map +1 -1
  20. package/dist/strategy/server/server-quotes.d.ts.map +1 -1
  21. package/dist/strategy/server/server-quotes.js +122 -21
  22. package/dist/strategy/server/server-quotes.js.map +1 -1
  23. package/dist/strategy/server/server-submit.d.ts.map +1 -1
  24. package/dist/strategy/server/server-submit.js +38 -2
  25. package/dist/strategy/server/server-submit.js.map +1 -1
  26. package/dist/strategy/server/server-support.d.ts +0 -2
  27. package/dist/strategy/server/server-support.d.ts.map +1 -1
  28. package/dist/strategy/server/server-support.js +0 -5
  29. package/dist/strategy/server/server-support.js.map +1 -1
  30. package/dist/strategy/server/types.d.ts +6 -9
  31. package/dist/strategy/server/types.d.ts.map +1 -1
  32. package/dist/strategy/server/types.js +0 -6
  33. package/dist/strategy/server/types.js.map +1 -1
  34. package/dist/types.d.ts +10 -0
  35. package/dist/types.d.ts.map +1 -1
  36. package/dist/types.js.map +1 -1
  37. package/dist/utils/chomp.d.ts +32 -0
  38. package/dist/utils/chomp.d.ts.map +1 -1
  39. package/dist/utils/chomp.js +73 -0
  40. package/dist/utils/chomp.js.map +1 -1
  41. package/dist/utils/second-leg.d.ts +71 -0
  42. package/dist/utils/second-leg.d.ts.map +1 -0
  43. package/dist/utils/second-leg.js +281 -0
  44. package/dist/utils/second-leg.js.map +1 -0
  45. package/package.json +2 -2
  46. package/dist/utils/ma-vault-deposit.d.ts +0 -40
  47. package/dist/utils/ma-vault-deposit.d.ts.map +0 -1
  48. package/dist/utils/ma-vault-deposit.js +0 -230
  49. package/dist/utils/ma-vault-deposit.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"relay-quotes.js","sourceRoot":"","sources":["../../../src/strategy/relay/relay-quotes.ts"],"names":[],"mappings":"AAAA,2CAA2C;AAE3C,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,KAAK,EAAE,MAAM,4BAA4B,CAAC;AAMnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EACL,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,gBAAgB,EAChB,sBAAsB,EACtB,uBAAuB,EACvB,oBAAoB,EACpB,mBAAmB,EACnB,aAAa,EACb,eAAe,GAChB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAShD,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EACL,eAAe,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QACnB,+CAA+C;KAChD,CAAC,CAAC,kBAAkB,CAAC,UAAU,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,CAAQ,CAAC;AACnE,CAAC;AAED;;;;;GAKG;AACH,SAAS,oBAAoB,CAAC,IAAS;IACrC,OAAO,IAAI,SAAS,CAAC,CAAC,+CAA+C,CAAC,CAAC;SACpE,kBAAkB,CAAC,UAAU,EAAE,IAAI,CAAC;SACpC,EAAE,CAAC,WAAW,EAAE,CAAC;AACtB,CAAC;AACD,SAAS,yBAAyB,CAChC,SAA4C,EAC5C,KAAiB;IAEjB,MAAM,aAAa,GAAG,KAAK,CAAC,IAAI,EAAE,UAAU,CAAC;IAC7C,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,aAAa,EAAE,SAAS,IAAI,GAAG,CAAC,CAAC;IACjE,MAAM,eAAe,GAAG,IAAI,SAAS,CAAC,aAAa,EAAE,eAAe,IAAI,GAAG,CAAC,CAAC;IAE7E,IAAI,CAAC,aAAa,IAAI,SAAS,CAAC,MAAM,EAAE,EAAE,CAAC;QACzC,OAAO,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;IAC1B,CAAC;IAED,MAAM,sBAAsB,GAAG,YAAY,CACzC,SAAS,EACT,KAAK,CAAC,aAAa,CAAC,QAAQ,CAAC,OAAO,CAAC,EACrC,aAAa,CAAC,QAAQ,CAAC,OAAO,CAC/B,CAAC;IAEF,OAAO,sBAAsB,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9D,CAAC;AAED,SAAS,YAAY,CACnB,SAA4C,EAC5C,OAAe,EACf,YAAoB;IAEpB,OAAO,OAAO,CACZ,cAAc,CAAC,SAAS,CAAC,CAAC,OAAc,CAAC,EAAE,QAAQ,CACjD,YAAY,CAAC,WAAW,EAAS,CAClC,CACF,CAAC;AACJ,CAAC","sourcesContent":["/* eslint-disable require-atomic-updates */\n\nimport { Interface } from '@ethersproject/abi';\nimport { toHex } from '@metamask/controller-utils';\nimport type {\n AuthorizationList,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n ARBITRUM_USDC_ADDRESS,\n CHAIN_ID_ARBITRUM,\n CHAIN_ID_HYPERCORE,\n CHAIN_ID_POLYGON,\n HYPERCORE_USDC_ADDRESS,\n HYPERCORE_USDC_DECIMALS,\n NATIVE_TOKEN_ADDRESS,\n PERPS_DEPOSIT_TYPES,\n USDC_DECIMALS,\n PaymentOverride,\n} from '../../constants.js';\nimport { TransactionPayStrategy } from '../../index.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 } from '../../utils/amounts.js';\nimport {\n getFeatureFlags,\n getRelayOriginGasOverhead,\n getSlippage,\n getStablecoins,\n isAtomicMaxEnabled,\n isEIP7702Chain,\n isRelayExecuteEnabled,\n} from '../../utils/feature-flags.js';\nimport {\n GasPaymentMode,\n resolveGasPayment,\n resolveGasStationCost,\n} 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 {\n getNativeToken,\n getTokenFiatRate,\n normalizeTokenAddress,\n TokenAddressTarget,\n} from '../../utils/token.js';\nimport { getQuotePricing } from '../../utils/trade-type.js';\nimport { TOKEN_TRANSFER_FOUR_BYTE } from './constants.js';\nimport { applyHyperliquidActivationFee } from './hyperliquid-activation.js';\nimport {\n applyPolymarketDepositWalletOverrides,\n getPredictWithdrawSafeAddress,\n isPredictWithdraw,\n} from './polymarket/withdraw.js';\nimport { fetchRelayQuote } from './relay-api.js';\nimport {\n getRelayMaxQuote,\n isSubsidizedAtomicMaxQuote,\n throwAtomicPromotionFailed,\n} from './relay-max.js';\nimport { validateRelayQuotes } from './relay-validation.js';\nimport type {\n RelayQuote,\n RelayQuoteMetamask,\n RelayQuoteRequest,\n RelayTransactionStep,\n} from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'relay-strategy');\n\n// Buffer applied to the gas cost when reserving native tokens for gas in\n// post-quote flows, accounting for gas limit re-estimation variance.\nconst POST_QUOTE_GAS_BUFFER = 1.1;\n\n// Hardcoded gas allowance for the prepended payment override transaction(s).\nconst PAYMENT_OVERRIDE_GAS = 75_000;\nconst ZERO_AMOUNT = { fiat: '0', human: '0', raw: '0', usd: '0' };\n\ntype RelayQuoteRequestDraft = Omit<RelayQuoteRequest, 'amount' | 'tradeType'> &\n Partial<Pick<RelayQuoteRequest, 'amount'>>;\ntype RelayStepData = RelayTransactionStep['items'][0]['data'];\n\ntype RelayGasResult = {\n totalGasEstimate: number;\n totalGasLimit: number;\n gasLimits: number[];\n is7702: boolean;\n};\n\n/**\n * Fetches Relay quotes.\n *\n * @param request - Request object.\n * @returns Array of quotes.\n */\nexport async function getRelayQuotes(\n request: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<RelayQuote>[]> {\n const { requests } = request;\n\n log('Fetching quotes', requests);\n\n try {\n const normalizedRequests = await Promise.all(\n requests\n .filter((singleRequest) => {\n const hasTargetMinimum = singleRequest.targetAmountMinimum !== '0';\n const isPostQuote = Boolean(singleRequest.isPostQuote);\n const isExactInputRequest =\n Boolean(singleRequest.isMaxAmount) &&\n new BigNumber(singleRequest.sourceTokenAmount).gt(0);\n\n return hasTargetMinimum || isPostQuote || isExactInputRequest;\n })\n .map((singleRequest) =>\n normalizeRequest(singleRequest, request.transaction),\n )\n .map((normalizedRequest) =>\n applyHyperliquidActivationFee(\n normalizedRequest,\n request.messenger,\n request.transaction,\n request.signal,\n ),\n ),\n );\n\n log('Normalized requests', normalizedRequests);\n\n const quotes = await Promise.all(\n normalizedRequests.map((singleRequest) =>\n getQuoteWithMaxAmountHandling(singleRequest, request),\n ),\n );\n\n const atomicMaxQuotes = quotes.filter(isSubsidizedAtomicMaxQuote);\n const otherQuotes = quotes.filter(\n (quote) => !isSubsidizedAtomicMaxQuote(quote),\n );\n\n if (otherQuotes.length > 0) {\n await validateRelayQuotes({\n messenger: request.messenger,\n quotes: otherQuotes,\n signal: request.signal,\n transaction: request.transaction,\n });\n }\n\n if (atomicMaxQuotes.length > 0) {\n try {\n await validateRelayQuotes({\n messenger: request.messenger,\n quotes: atomicMaxQuotes,\n signal: request.signal,\n transaction: request.transaction,\n });\n } catch (error) {\n throwAtomicPromotionFailed(error);\n }\n }\n\n return quotes;\n } catch (error) {\n log('Error fetching quotes', { error });\n throw error;\n }\n}\n\nasync function getQuoteWithMaxAmountHandling(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<RelayQuote>> {\n const { isMaxAmount } = request;\n\n if (!isMaxAmount) {\n return getQuoteWithPostQuoteGasHandling(request, fullRequest);\n }\n\n return getRelayMaxQuote(request, fullRequest, getSingleQuote);\n}\n\n/**\n * For post-quote flows, fetch an initial quote to compute gas cost in source\n * token, then re-quote with the source amount reduced by the gas cost.\n * This ensures Relay reserves enough for the gas fee token payment.\n *\n * For non-post-quote flows, just returns a single quote.\n *\n * @param request - Quote request.\n * @param fullRequest - Full request context.\n * @returns The final quote (phase 2 for post-quote, or phase 1 for normal).\n */\nasync function getQuoteWithPostQuoteGasHandling(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<RelayQuote>> {\n const phase1Quote = await getSingleQuote(request, fullRequest);\n\n if (!request.isPostQuote) {\n return phase1Quote;\n }\n\n if (phase1Quote.original.metamask?.isExecute) {\n return phase1Quote;\n }\n\n // Gas must be subtracted from the source amount when the user's balance\n // is fully committed to the swap. This applies when gas is paid via an\n // ERC-20 fee token (isSourceGasFeeToken) OR when the source itself is\n // the native gas token (gas comes from the same pool as the swap value).\n const isSourceNative =\n request.sourceTokenAddress.toLowerCase() ===\n getNativeToken(request.sourceChainId).toLowerCase() ||\n request.sourceTokenAddress.toLowerCase() ===\n NATIVE_TOKEN_ADDRESS.toLowerCase();\n\n if (!phase1Quote.fees.isSourceGasFeeToken && !isSourceNative) {\n return phase1Quote;\n }\n\n const gasCostRaw = new BigNumber(phase1Quote.fees.sourceNetwork.max.raw)\n .multipliedBy(POST_QUOTE_GAS_BUFFER)\n .integerValue(BigNumber.ROUND_UP);\n\n const existingHeadroom = new BigNumber(request.sourceBalanceRaw).minus(\n request.sourceTokenAmount,\n );\n\n if (existingHeadroom.isGreaterThanOrEqualTo(gasCostRaw)) {\n log('Sufficient existing balance for gas, skipping subtraction', {\n existingHeadroom: existingHeadroom.toString(10),\n gasCostRaw: gasCostRaw.toString(10),\n });\n return phase1Quote;\n }\n\n const adjustedSourceAmount = new BigNumber(request.sourceTokenAmount)\n .minus(gasCostRaw)\n .integerValue(BigNumber.ROUND_DOWN);\n\n log('Subtracting gas from source for post-quote two-call', {\n originalSourceAmount: request.sourceTokenAmount,\n gasCostRaw,\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n });\n\n if (!adjustedSourceAmount.isGreaterThan(0)) {\n log(\n 'Insufficient balance after gas subtraction for post-quote, using phase 1',\n );\n return phase1Quote;\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 (\n phase1Quote.fees.isSourceGasFeeToken &&\n !phase2Quote.fees.isSourceGasFeeToken\n ) {\n log('Phase 2 lost gas fee token eligibility, falling back to phase 1');\n return phase1Quote;\n }\n\n return phase2Quote;\n } catch (error) {\n log('Phase 2 quote failed, falling back to phase 1', { error });\n return phase1Quote;\n }\n}\n\n/**\n * Fetches a single Relay quote.\n *\n * @param request - Quote request.\n * @param fullRequest - Full quotes request.\n * @returns Single quote.\n */\nasync function getSingleQuote(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<RelayQuote>> {\n const {\n accountSupports7702: supports7702,\n messenger,\n signal,\n transaction,\n } = fullRequest;\n\n const {\n from,\n sourceChainId,\n sourceTokenAddress,\n sourceTokenAmount,\n targetAmountMinimum,\n targetChainId,\n targetTokenAddress,\n } = request;\n\n const slippageDecimal = getSlippage(\n messenger,\n sourceChainId,\n sourceTokenAddress,\n );\n\n const slippageTolerance = new BigNumber(slippageDecimal * 100 * 100).toFixed(\n 0,\n );\n\n try {\n const useExecute =\n supports7702 &&\n isRelayExecuteEnabled(messenger) &&\n isEIP7702Chain(messenger, sourceChainId);\n\n const nonAtomicRecipient = await resolveNonAtomicRecipient(\n transaction,\n request,\n messenger,\n );\n\n const effectiveRequest = nonAtomicRecipient\n ? { ...request, recipient: nonAtomicRecipient }\n : request;\n\n const body: RelayQuoteRequestDraft = {\n destinationChainId: Number(targetChainId),\n destinationCurrency: targetTokenAddress,\n originChainId: Number(sourceChainId),\n originCurrency: sourceTokenAddress,\n ...(useExecute\n ? {\n originGasOverhead: getRelayOriginGasOverhead(messenger),\n metamask: { executeVersion: 2 },\n }\n : {}),\n recipient: effectiveRequest.recipient ?? from,\n slippageTolerance,\n user: from,\n };\n\n if (effectiveRequest.isPolymarketDepositWallet) {\n await applyPolymarketDepositWalletOverrides(\n body,\n effectiveRequest,\n messenger,\n );\n }\n\n const isAtomic = effectiveRequest.atomic !== false;\n\n const processedTransactions = await processTransactions(\n transaction,\n effectiveRequest,\n body,\n messenger,\n );\n\n if (\n !processedTransactions &&\n isAtomic &&\n effectiveRequest.isPostQuote &&\n effectiveRequest.paymentOverride === PaymentOverride.MoneyAccount\n ) {\n await processMoneyAccountPostQuote(\n transaction,\n effectiveRequest,\n body,\n messenger,\n );\n } else if (!processedTransactions && effectiveRequest.refundTo) {\n // For post-quote flows, honour the caller-specified refund address so that\n // failed Relay transactions refund to the correct account (e.g. the Predict\n // Safe proxy) rather than defaulting to the EOA.\n body.refundTo = effectiveRequest.refundTo;\n }\n\n const pricing = getQuotePricing({\n hasCalls: Boolean(body.txs?.length),\n sourceTokenAmount,\n targetAmountMinimum,\n transaction,\n });\n\n const finalBody: RelayQuoteRequest = {\n ...body,\n // A step that bundled its own calls has already pinned the amount those\n // calls consume, so it wins over the derived amount.\n amount: body.amount ?? pricing.amount,\n tradeType: pricing.tradeType,\n };\n\n log('Request body', finalBody);\n\n const quote = await fetchRelayQuote(messenger, finalBody, signal);\n\n log('Fetched relay quote', quote);\n\n return await normalizeQuote(quote, effectiveRequest, fullRequest);\n } catch (error) {\n log('Error fetching relay quote', error);\n throw error;\n }\n}\n\nfunction normalizeAuthorizationList(\n authorizationList: AuthorizationList | undefined,\n): RelayQuoteRequest['authorizationList'] {\n return authorizationList?.map((a) => ({\n ...a,\n chainId: Number(a.chainId),\n nonce: Number(a.nonce),\n r: a.r as Hex,\n s: a.s as Hex,\n yParity: Number(a.yParity),\n }));\n}\n\n/**\n * Derives the Relay quote recipient for non-atomic flows, where the second leg\n * runs after settlement so funds must land directly on the account submitting\n * that leg.\n *\n * Post-quote flows (e.g. Perps/Predict withdraw to Money Account) ask the\n * client `getPaymentOverrideData` callback, which knows the Money Account\n * address that cannot be derived from the request. Non-post-quote flows (e.g.\n * max-amount Money Account deposit) use the parent transaction's own `from`,\n * which is the Money Account rather than the funding EOA in `request.from`.\n *\n * @param transaction - Transaction metadata.\n * @param request - Quote request.\n * @param messenger - Controller messenger.\n * @returns The recipient address, or `undefined` for atomic flows.\n */\nasync function resolveNonAtomicRecipient(\n transaction: TransactionMeta,\n request: QuoteRequest,\n messenger: TransactionPayControllerMessenger,\n): Promise<Hex | undefined> {\n if (request.atomic !== false) {\n return undefined;\n }\n\n if (!request.isPostQuote) {\n return (transaction.txParams?.from as Hex | undefined) ?? request.from;\n }\n\n const { transactionData: transactionDataList } = messenger.call(\n 'TransactionPayController:getState',\n );\n\n const transactionData = transactionDataList[transaction.id];\n const amountHuman = transactionData?.tokens?.[0]?.amountHuman ?? '0';\n\n const { recipient } = await messenger.call(\n 'TransactionPayController:getPaymentOverrideData',\n {\n amount: amountHuman,\n transaction,\n transactionData,\n },\n );\n\n return recipient;\n}\n\n/**\n * Add tranasction data to request body if needed.\n *\n * @param transaction - Transaction metadata.\n * @param request - Quote request.\n * @param requestBody - Request body to populate.\n * @param messenger - Controller messenger.\n * @returns `true` when the transaction was embedded in the quote; `false` when\n * skipped so the caller can route to an alternate handler.\n */\nasync function processTransactions(\n transaction: TransactionMeta,\n request: QuoteRequest,\n requestBody: RelayQuoteRequestDraft,\n messenger: TransactionPayControllerMessenger,\n): Promise<boolean> {\n // Skip when skipProcessTransactions (defaulting to isPostQuote) is set — the\n // original transaction is submitted separately, not embedded in the quote.\n // Skip Polymarket deposit wallet flows — the source is already a bridged\n // token transfer, not a contract call to embed. Skip non-atomic flows — the\n // second leg is submitted after Relay settlement.\n if (\n (request.skipProcessTransactions ?? request.isPostQuote) === true ||\n request.isPolymarketDepositWallet === true ||\n request.atomic === false\n ) {\n return false;\n }\n\n const { nestedTransactions, txParams } = transaction;\n const { isMaxAmount, targetChainId } = request;\n const data = txParams?.data as Hex | undefined;\n\n const singleData =\n nestedTransactions?.length === 1 ? nestedTransactions[0].data : data;\n\n const isHypercore = targetChainId === CHAIN_ID_HYPERCORE;\n\n const isTokenTransfer =\n !isHypercore && Boolean(singleData?.startsWith(TOKEN_TRANSFER_FOUR_BYTE));\n\n if (isTokenTransfer) {\n requestBody.recipient = getTransferRecipient(singleData as Hex);\n\n log('Updating recipient as token transfer', requestBody.recipient);\n }\n\n const hasNoData = singleData === undefined || singleData === '0x';\n const skipDelegation = hasNoData || isTokenTransfer || isHypercore;\n\n if (skipDelegation) {\n log('Skipping delegation as token transfer or Hypercore deposit');\n return true;\n }\n\n // Eligible atomic max requests carry a destination amount, so the calls\n // below use EXACT_OUTPUT rather than the usual max EXACT_INPUT quote.\n if (\n isMaxAmount &&\n (request.isPostQuote === true ||\n !isAtomicMaxEnabled(messenger, transaction))\n ) {\n throw new Error('Max amount quotes do not support included transactions');\n }\n\n const delegation = await messenger.call(\n 'TransactionPayController:getDelegationTransaction',\n { transaction },\n );\n\n requestBody.authorizationList = normalizeAuthorizationList(\n delegation.authorizationList,\n );\n\n const tokenTransferData = nestedTransactions?.find((nestedTx) =>\n nestedTx.data?.startsWith(TOKEN_TRANSFER_FOUR_BYTE),\n )?.data;\n\n // If the transactions include a token transfer, change the recipient\n // so any extra dust is also sent to the same address, rather than back to the user.\n if (tokenTransferData) {\n requestBody.recipient = getTransferRecipient(tokenTransferData);\n requestBody.refundTo = request.from;\n }\n\n const fundingRecipient = (transaction.txParams?.from as Hex) ?? request.from;\n\n requestBody.txs = [\n {\n to: request.targetTokenAddress,\n data: buildTokenTransferData(\n fundingRecipient,\n request.targetAmountMinimum,\n ),\n value: '0x0',\n },\n {\n to: delegation.to,\n data: delegation.data,\n value: delegation.value,\n },\n ];\n\n return true;\n}\n\nasync function processMoneyAccountPostQuote(\n transaction: TransactionMeta,\n request: QuoteRequest,\n requestBody: RelayQuoteRequestDraft,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n const { transactionData: transactionDataList } = messenger.call(\n 'TransactionPayController:getState',\n );\n\n const transactionData = transactionDataList[transaction.id];\n const amountHuman = transactionData?.tokens?.[0]?.amountHuman ?? '0';\n\n const {\n calls: overrideCalls,\n recipient,\n authorizationList,\n } = await messenger.call('TransactionPayController:getPaymentOverrideData', {\n amount: amountHuman,\n transaction,\n transactionData,\n });\n\n if (!overrideCalls.length) {\n log('No payment override calls for money account post-quote');\n return;\n }\n\n const fundingRecipient = recipient ?? request.from;\n const rawAmount = transactionData?.tokens?.[0]?.amountRaw ?? '0';\n\n requestBody.authorizationList = normalizeAuthorizationList(authorizationList);\n requestBody.amount = rawAmount;\n requestBody.txs = [\n {\n to: request.targetTokenAddress,\n data: buildTokenTransferData(fundingRecipient, rawAmount),\n value: '0x0',\n },\n ...overrideCalls.map((call) => ({\n to: call.to as Hex,\n data: call.data as Hex,\n value: (call.value as Hex) ?? '0x0',\n })),\n ];\n\n log('Added money account deposit calls to quote body', {\n callCount: overrideCalls.length,\n });\n}\n\n/**\n * Normalizes requests for Relay.\n *\n * @param request - Quote request to normalize.\n * @param transaction - Parent transaction metadata, used to gate\n * Hyperliquid-specific rewrites on transaction type.\n * @returns Normalized request.\n */\nfunction normalizeRequest(\n request: QuoteRequest,\n transaction: TransactionMeta,\n): QuoteRequest {\n const newRequest = {\n ...request,\n };\n\n const isPerpsDeposit =\n transaction.type !== undefined &&\n PERPS_DEPOSIT_TYPES.includes(transaction.type);\n\n const isHyperliquidDeposit =\n isPerpsDeposit &&\n !request.isPostQuote &&\n request.targetChainId === CHAIN_ID_ARBITRUM &&\n request.targetTokenAddress.toLowerCase() ===\n ARBITRUM_USDC_ADDRESS.toLowerCase();\n\n newRequest.sourceTokenAddress = normalizeTokenAddress(\n newRequest.sourceTokenAddress,\n newRequest.sourceChainId,\n TokenAddressTarget.Relay,\n );\n newRequest.targetTokenAddress = normalizeTokenAddress(\n newRequest.targetTokenAddress,\n newRequest.targetChainId,\n TokenAddressTarget.Relay,\n );\n\n if (isHyperliquidDeposit) {\n newRequest.targetChainId = CHAIN_ID_HYPERCORE;\n newRequest.targetTokenAddress = HYPERCORE_USDC_ADDRESS;\n newRequest.targetAmountMinimum = new BigNumber(request.targetAmountMinimum)\n .shiftedBy(HYPERCORE_USDC_DECIMALS - USDC_DECIMALS)\n .toString(10);\n\n log('Converting Arbitrum Hyperliquid deposit to direct deposit', {\n originalRequest: request,\n normalizedRequest: newRequest,\n });\n }\n\n // HyperLiquid withdrawal: source is HyperCore Perps USDC, not Arbitrum.\n if (request.isHyperliquidSource) {\n newRequest.sourceChainId = CHAIN_ID_HYPERCORE;\n newRequest.sourceTokenAddress = HYPERCORE_USDC_ADDRESS;\n\n if (newRequest.sourceTokenAmount) {\n newRequest.sourceTokenAmount = new BigNumber(newRequest.sourceTokenAmount)\n .shiftedBy(HYPERCORE_USDC_DECIMALS - USDC_DECIMALS)\n .toString(10);\n }\n }\n\n return newRequest;\n}\n\n/**\n * Normalizes a Relay quote into a TransactionPayQuote.\n *\n * @param quote - Relay quote.\n * @param request - Original quote request.\n * @param fullRequest - Full quotes request.\n * @returns Normalized quote.\n */\nasync function normalizeQuote(\n quote: RelayQuote,\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<RelayQuote>> {\n const { messenger } = fullRequest;\n const { details } = quote;\n const { currencyIn, currencyOut } = details;\n\n const { usdToFiatRate } = getFiatRates(messenger, request);\n\n const dust = getFiatValueFromUsd(\n calculateDustUsd(quote, request),\n usdToFiatRate,\n );\n\n const subsidizedFeeUsd = getSubsidizedFeeAmountUsd(messenger, quote);\n\n const appFeeUsd = new BigNumber(quote.fees?.app?.amountUsd ?? '0');\n const metaMaskFee = getFiatValueFromUsd(appFeeUsd, usdToFiatRate);\n\n // Subtract app fee from provider fee since totalImpact.usd already includes\n // it. The relay provider fee is forced to zero when the quote is subsidized,\n // but any reserved HyperLiquid activation fee is withheld from the source\n // send regardless, so it must always be surfaced in the provider fee.\n const activationFeeUsd = new BigNumber(\n request.hyperliquidActivationFeeUsd ?? '0',\n );\n const providerFeeUsd = subsidizedFeeUsd.gt(0)\n ? activationFeeUsd\n : calculateProviderFee(quote).minus(appFeeUsd).plus(activationFeeUsd);\n const provider = getFiatValueFromUsd(providerFeeUsd, usdToFiatRate);\n\n const {\n gasLimits,\n is7702,\n isGasFeeToken: isSourceGasFeeToken,\n ...sourceNetwork\n } = await calculateSourceNetworkCost(\n quote,\n messenger,\n request,\n fullRequest.transaction,\n fullRequest.accountSupports7702,\n );\n\n const targetNetwork = {\n usd: '0',\n fiat: '0',\n };\n\n const sourceAmount: Amount = {\n human: currencyIn.amountFormatted,\n raw: currencyIn.amount,\n ...getFiatValueFromUsd(new BigNumber(currencyIn.amountUsd), usdToFiatRate),\n };\n\n const isTargetStablecoin = isStablecoin(\n messenger,\n request.targetChainId,\n request.targetTokenAddress,\n );\n\n const targetAmountUsd = isTargetStablecoin\n ? new BigNumber(currencyOut.amountFormatted)\n : new BigNumber(currencyOut.amountUsd);\n\n const targetAmount = getFiatValueFromUsd(targetAmountUsd, usdToFiatRate);\n\n const metamask: RelayQuoteMetamask = {\n ...quote.metamask,\n gasLimits: is7702 ? [gasLimits[0]] : gasLimits,\n is7702,\n };\n\n return {\n dust,\n estimatedDuration: details.timeEstimate,\n fees: {\n isSourceGasFeeToken,\n metaMask: metaMaskFee,\n provider,\n sourceNetwork,\n targetNetwork,\n },\n isInputBased: quote.request.tradeType === 'EXACT_INPUT',\n original: {\n ...quote,\n metamask,\n },\n request,\n sourceAmount,\n targetAmount,\n strategy: TransactionPayStrategy.Relay,\n };\n}\n\n/**\n * Calculate dust USD value.\n *\n * @param quote - Relay quote.\n * @param request - Quote request.\n * @returns Dust value in USD and fiat.\n */\nfunction calculateDustUsd(quote: RelayQuote, request: QuoteRequest): BigNumber {\n const { currencyOut } = quote.details;\n const { amountUsd, amountFormatted, minimumAmount } = currencyOut;\n const { decimals: targetDecimals } = currencyOut.currency;\n\n const targetUsdRate = new BigNumber(amountUsd).dividedBy(amountFormatted);\n\n const dustRaw = BigNumber.maximum(\n new BigNumber(minimumAmount).minus(request.targetAmountMinimum),\n 0,\n );\n\n return dustRaw.shiftedBy(-targetDecimals).multipliedBy(targetUsdRate);\n}\n\n/**\n * Calculates USD to fiat rate.\n *\n * @param messenger - Controller messenger.\n * @param request - Quote request.\n * @returns USD to fiat rate.\n */\nfunction getFiatRates(\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n): {\n sourceFiatRate: FiatRates;\n usdToFiatRate: BigNumber;\n} {\n // For HyperLiquid source, the normalized chain/token (HyperCore + Perps USDC)\n // won't have a fiat rate entry. Use Arbitrum USDC instead since Perps USDC\n // is pegged 1:1.\n const sourceChainId = request.isHyperliquidSource\n ? CHAIN_ID_ARBITRUM\n : request.sourceChainId;\n const sourceTokenAddress = request.isHyperliquidSource\n ? ARBITRUM_USDC_ADDRESS\n : request.sourceTokenAddress;\n\n const finalSourceTokenAddress =\n sourceChainId === CHAIN_ID_POLYGON &&\n sourceTokenAddress === NATIVE_TOKEN_ADDRESS\n ? getNativeToken(sourceChainId)\n : sourceTokenAddress;\n\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n finalSourceTokenAddress,\n sourceChainId,\n );\n\n if (!sourceFiatRate) {\n throw new Error('Source token fiat rate not found');\n }\n\n const usdToFiatRate = new BigNumber(sourceFiatRate.fiatRate).dividedBy(\n sourceFiatRate.usdRate,\n );\n\n return { sourceFiatRate, usdToFiatRate };\n}\n\n/**\n * Calculates source network cost from a Relay quote.\n *\n * For post-quote flows (e.g. predictWithdraw), the cost also includes the\n * original transaction's gas (the user's Polygon USDC.e transfer) in addition\n * to the Relay deposit transaction gas, by appending the original\n * transaction's params so that gas estimation and gas-fee-token logic handle\n * both transactions together.\n *\n * Network fees are zeroed whenever the user does not pay origin gas, either\n * because a relayer covers it or because MetaMask sponsors it.\n *\n * @param quote - Relay quote.\n * @param messenger - Controller messenger.\n * @param request - Quote request.\n * @param transaction - Original transaction metadata.\n * @param accountSupports7702 - Whether the source account supports EIP-7702.\n * @returns Total source network cost in USD and fiat.\n */\nasync function calculateSourceNetworkCost(\n quote: RelayQuote,\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n transaction: TransactionMeta,\n accountSupports7702: boolean | undefined,\n): Promise<\n TransactionPayQuote<RelayQuote>['fees']['sourceNetwork'] & {\n gasLimits: number[];\n isGasFeeToken?: boolean;\n is7702: boolean;\n }\n> {\n const { from, sourceChainId, sourceTokenAddress } = request;\n\n // Neither flow bills origin gas to the user: the execute flow has a relayer\n // redeem a signed delegation, and a HyperLiquid withdrawal's \"deposit\" step\n // is an off-chain HL sendAsset signature rather than an on-chain\n // transaction.\n const isExecuteFlow = Boolean(quote.metamask?.isExecute);\n const isHyperliquidWithdrawal = Boolean(request.isHyperliquidSource);\n\n const gasPayment = resolveGasPayment({\n isDelegated: isExecuteFlow || isHyperliquidWithdrawal,\n sourceTokenAddress,\n sponsorship: {\n accountSupports7702,\n request,\n transaction,\n },\n });\n\n if (gasPayment.mode === GasPaymentMode.Delegation) {\n log('Zeroing network fees as the user does not pay origin gas', {\n isExecuteFlow,\n isHyperliquidWithdrawal,\n });\n\n return {\n estimate: ZERO_AMOUNT,\n max: ZERO_AMOUNT,\n gasLimits: [],\n is7702: false,\n };\n }\n\n if (gasPayment.mode === GasPaymentMode.Sponsored) {\n log('Zeroing source network fees for sponsored same-chain Relay route');\n\n // Gas limit is zero as sponsored transactions go through the EIP-7702\n // gas station hook and do not require user-paid gas.\n return {\n estimate: ZERO_AMOUNT,\n max: ZERO_AMOUNT,\n gasLimits: [0],\n is7702: true,\n };\n }\n\n const txSteps = quote.steps.filter(\n (step): step is RelayTransactionStep => step.kind === 'transaction',\n );\n const relayParams = txSteps\n .flatMap((step) => step.items)\n .map((item) => item.data);\n\n const { chainId, data, maxFeePerGas, maxPriorityFeePerGas, to, value } =\n relayParams[0];\n\n const isPredictWithdrawFlow = isPredictWithdraw(request, transaction);\n\n // `fromOverride = Safe proxy` is only valid for deposit-style Relay routes\n // where the deposit contract reads the user's source-token balance directly.\n // Same-chain destinations route through DEX swap aggregators that frequently\n // reject contract callers (anti-MEV `msg.sender == tx.origin` checks,\n // ERC777-style callback interfaces, native wrap/unwrap requiring caller\n // native balance). Simulating those from the Safe proxy reverts and breaks\n // gas estimation. For swap-only routes, fall back to the relay params'\n // EOA `from` so simulation succeeds.\n const fromOverride = getPredictWithdrawSafeAddress(\n request,\n quote.steps,\n transaction,\n );\n\n // For post-quote flows the original transaction will be prepended to the\n // batch at submission time. Include it in the gas estimation so\n // estimateGasBatch sees the full batch and can detect EIP-7702 support.\n // Without this, a single relay step is estimated alone, gets is7702=false,\n // and the batch falls back to separate type-0x2 transactions that each\n // need native gas — breaking zero-balance fiat-funded accounts.\n const originalTxGasParams = getOriginalTxGasParams(request, transaction);\n const allGasParams = originalTxGasParams\n ? [originalTxGasParams, ...relayParams]\n : relayParams;\n\n const gasResult = await calculateSourceNetworkGasLimit(\n allGasParams,\n messenger,\n fromOverride,\n );\n\n // When the original tx was NOT included in gas estimation (no gas params\n // available), fall back to the legacy prepend-after-the-fact approach.\n const { gasLimits, is7702, totalGasEstimate, totalGasLimit } =\n originalTxGasParams\n ? gasResult\n : combinePrependedGas(gasResult, request, transaction);\n\n log('Gas limit', {\n is7702,\n totalGasEstimate,\n totalGasLimit,\n gasLimits,\n });\n\n const estimate = calculateGasCost({\n chainId,\n gas: totalGasEstimate,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n });\n\n const max = calculateGasCost({\n chainId,\n gas: totalGasLimit,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n isMax: true,\n });\n\n const result = { estimate, max, gasLimits, is7702 };\n\n // Gas-fee-token lookup must use the Safe proxy for ALL Predict withdraws,\n // not only deposit-style routes. The user's source token (pUSD) lives in\n // the Safe; the EOA is empty until the Safe.execTransaction sub-call runs\n // mid-batch. Querying the EOA for gas-fee-token availability would always\n // return nothing and force users to hold POL.\n // (`useFromOverride` only governs the gas-estimation `from` address, where\n // swap-style routes need EOA because DEX routers reject contract callers.)\n const proxyFeeTokenAccount = isPredictWithdrawFlow\n ? request.refundTo\n : undefined;\n\n const gasStationCost = await resolveGasStationCost({\n accountSupports7702,\n feeTokenAccount: proxyFeeTokenAccount,\n firstStepData: {\n data,\n to,\n value,\n },\n messenger,\n nativeGasCostRaw: max.raw,\n request: {\n from,\n sourceChainId,\n sourceTokenAddress,\n },\n totalGasEstimate,\n totalItemCount: proxyFeeTokenAccount\n ? relayParams.length + 1\n : Math.max(relayParams.length, gasLimits.length),\n });\n\n if (!gasStationCost.amount) {\n return result;\n }\n\n log('Using gas fee token for source network', {\n gasFeeTokenCost: gasStationCost.amount,\n proxyFeeTokenAccount,\n });\n\n return {\n isGasFeeToken: true,\n estimate: gasStationCost.amount,\n max: gasStationCost.amount,\n gasLimits,\n is7702,\n };\n}\n\n/**\n * Calculate the total gas limit for the source network.\n *\n * @param params - Array of relay transaction parameters.\n * @param messenger - Controller messenger.\n * @param fromOverride - Optional address to use as `from` in gas estimation\n * instead of the address in the relay params. Used in predict withdraw flows\n * to estimate with the proxy/Safe address that holds the source token balance.\n * @returns Total gas estimates and per-transaction gas limits.\n */\nasync function calculateSourceNetworkGasLimit(\n params: RelayTransactionStep['items'][0]['data'][],\n messenger: TransactionPayControllerMessenger,\n fromOverride?: Hex,\n): Promise<{\n totalGasEstimate: number;\n totalGasLimit: number;\n gasLimits: number[];\n is7702: boolean;\n}> {\n const transactions = params.map((singleParams) =>\n toRelayQuoteGasTransaction(singleParams, fromOverride),\n );\n\n const relayGasResult = await estimateQuoteGasLimits({\n fallbackGas: getFeatureFlags(messenger).relayFallbackGas,\n fallbackOnSimulationFailure: true,\n messenger,\n transactions,\n });\n\n return {\n gasLimits: relayGasResult.gasLimits.map((gasLimit) => gasLimit.max),\n is7702: relayGasResult.is7702,\n totalGasEstimate: relayGasResult.totalGasEstimate,\n totalGasLimit: relayGasResult.totalGasLimit,\n };\n}\n\nfunction toRelayQuoteGasTransaction(\n singleParams: RelayTransactionStep['items'][0]['data'],\n fromOverride?: Hex,\n): QuoteGasTransaction {\n return {\n chainId: toHex(singleParams.chainId),\n data: singleParams.data,\n from: fromOverride ?? singleParams.from,\n gas: fromOverride ? undefined : singleParams.gas,\n to: singleParams.to,\n value: singleParams.value ?? '0',\n };\n}\n\nfunction getOriginalTxGasParams(\n request: QuoteRequest,\n transaction: TransactionMeta,\n): RelayStepData | undefined {\n if (!request.isPostQuote) {\n return undefined;\n }\n\n const { txParams } = transaction;\n const to = txParams.to as Hex | undefined;\n\n if (!to) {\n return undefined;\n }\n\n const hasAccountOverride =\n request.from.toLowerCase() !== (txParams.from as Hex).toLowerCase();\n\n if (hasAccountOverride) {\n return undefined;\n }\n\n const nestedGas = transaction.nestedTransactions?.find((tx) => tx.gas)?.gas;\n const gas = nestedGas ?? txParams.gas;\n\n return {\n chainId: Number(transaction.chainId),\n data: (txParams.data as Hex) ?? '0x',\n from: txParams.from as Hex,\n gas: gas ? String(gas) : undefined,\n maxFeePerGas: '0',\n maxPriorityFeePerGas: '0',\n to,\n value: txParams.value ?? '0',\n };\n}\n\nfunction combinePrependedGas(\n relayOnlyGas: RelayGasResult,\n request: QuoteRequest,\n transaction: TransactionMeta,\n): RelayGasResult {\n const gas = request.isPostQuote\n ? combinePostQuoteGas(relayOnlyGas, transaction)\n : relayOnlyGas;\n\n return request.paymentOverride ? addPaymentOverrideGas(gas) : gas;\n}\n\n/**\n * Combine the original transaction's gas with relay gas for post-quote flows.\n *\n * Prefers gas from `nestedTransactions` (preserves the caller-provided value)\n * since TransactionController may re-estimate `txParams.gas` during batch\n * creation.\n *\n * @param relayGas - Gas estimates from relay transactions.\n * @param relayGas.totalGasEstimate - Estimated gas total.\n * @param relayGas.totalGasLimit - Maximum gas total.\n * @param relayGas.gasLimits - Per-transaction gas limits.\n * @param relayGas.is7702 - Whether the relay gas came from a combined 7702 batch estimate.\n * @param transaction - Original transaction metadata.\n * @returns Combined gas estimates including the original transaction.\n */\nfunction combinePostQuoteGas(\n relayGas: RelayGasResult,\n transaction: TransactionMeta,\n): RelayGasResult {\n const nestedGas = transaction.nestedTransactions?.find((tx) => tx.gas)?.gas;\n const rawGas = nestedGas ?? transaction.txParams.gas;\n const originalTxGas = rawGas ? new BigNumber(rawGas).toNumber() : undefined;\n\n if (originalTxGas === undefined) {\n return relayGas;\n }\n\n let { gasLimits } = relayGas;\n\n if (relayGas.is7702) {\n // Combined 7702 gas limit — add the original tx gas so the batch\n // keeps using a single 7702 limit.\n gasLimits = [gasLimits[0] + originalTxGas];\n } else {\n // Multiple individual gas limits — prepend the original tx gas\n // so the list order matches relay-submit's transaction order.\n gasLimits = [originalTxGas, ...gasLimits];\n }\n\n const totalGasEstimate = relayGas.totalGasEstimate + originalTxGas;\n const totalGasLimit = relayGas.totalGasLimit + originalTxGas;\n\n log('Combined original tx gas with relay gas', {\n originalTxGas,\n is7702: relayGas.is7702,\n gasLimits,\n totalGasLimit,\n });\n\n return {\n totalGasEstimate,\n totalGasLimit,\n gasLimits,\n is7702: relayGas.is7702,\n };\n}\n\nfunction addPaymentOverrideGas(relayGas: RelayGasResult): RelayGasResult {\n const gasLimits = relayGas.is7702\n ? [relayGas.gasLimits[0] + PAYMENT_OVERRIDE_GAS]\n : [PAYMENT_OVERRIDE_GAS, ...relayGas.gasLimits];\n\n return {\n totalGasEstimate: relayGas.totalGasEstimate + PAYMENT_OVERRIDE_GAS,\n totalGasLimit: relayGas.totalGasLimit + PAYMENT_OVERRIDE_GAS,\n gasLimits,\n is7702: relayGas.is7702,\n };\n}\n\n/**\n * Calculate the provider fee for a Relay quote.\n *\n * @param quote - Relay quote.\n * @returns - Provider fee in USD.\n */\nfunction calculateProviderFee(quote: RelayQuote): BigNumber {\n return new BigNumber(quote.details.totalImpact.usd).abs();\n}\n\n/**\n * Build token transfer data.\n *\n * @param recipient - Recipient address.\n * @param amountRaw - Amount in raw format.\n * @returns Token transfer data.\n */\nfunction buildTokenTransferData(recipient: Hex, amountRaw: string): Hex {\n return new Interface([\n 'function transfer(address to, uint256 amount)',\n ]).encodeFunctionData('transfer', [recipient, amountRaw]) as Hex;\n}\n\n/**\n * Get transfer recipient from token transfer data.\n *\n * @param data - Token transfer data.\n * @returns Transfer recipient.\n */\nfunction getTransferRecipient(data: Hex): Hex {\n return new Interface(['function transfer(address to, uint256 amount)'])\n .decodeFunctionData('transfer', data)\n .to.toLowerCase();\n}\nfunction getSubsidizedFeeAmountUsd(\n messenger: TransactionPayControllerMessenger,\n quote: RelayQuote,\n): BigNumber {\n const subsidizedFee = quote.fees?.subsidized;\n const amountUsd = new BigNumber(subsidizedFee?.amountUsd ?? '0');\n const amountFormatted = new BigNumber(subsidizedFee?.amountFormatted ?? '0');\n\n if (!subsidizedFee || amountUsd.isZero()) {\n return new BigNumber(0);\n }\n\n const isSubsidizedStablecoin = isStablecoin(\n messenger,\n toHex(subsidizedFee.currency.chainId),\n subsidizedFee.currency.address,\n );\n\n return isSubsidizedStablecoin ? amountFormatted : amountUsd;\n}\n\nfunction isStablecoin(\n messenger: TransactionPayControllerMessenger,\n chainId: string,\n tokenAddress: string,\n): boolean {\n return Boolean(\n getStablecoins(messenger)[chainId as Hex]?.includes(\n tokenAddress.toLowerCase() as Hex,\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"relay-quotes.js","sourceRoot":"","sources":["../../../src/strategy/relay/relay-quotes.ts"],"names":[],"mappings":"AAAA,2CAA2C;AAE3C,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,KAAK,EAAE,MAAM,4BAA4B,CAAC;AAMnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EACL,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,gBAAgB,EAChB,sBAAsB,EACtB,uBAAuB,EACvB,oBAAoB,EACpB,mBAAmB,EACnB,aAAa,EACb,eAAe,GAChB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAShD,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EACL,eAAe,EACf,yBAAyB,EACzB,WAAW,EACX,cAAc,EACd,kBAAkB,EAClB,cAAc,EACd,qBAAqB,GACtB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA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AAS,CAAC;AAC9D,CAAC;AAED,SAAS,YAAY,CACnB,SAA4C,EAC5C,OAAe,EACf,YAAoB;IAEpB,OAAO,OAAO,CACZ,cAAc,CAAC,SAAS,CAAC,CAAC,OAAc,CAAC,EAAE,QAAQ,CACjD,YAAY,CAAC,WAAW,EAAS,CAClC,CACF,CAAC;AACJ,CAAC","sourcesContent":["/* eslint-disable require-atomic-updates */\n\nimport { Interface } from '@ethersproject/abi';\nimport { toHex } from '@metamask/controller-utils';\nimport type {\n AuthorizationList,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n ARBITRUM_USDC_ADDRESS,\n CHAIN_ID_ARBITRUM,\n CHAIN_ID_HYPERCORE,\n CHAIN_ID_POLYGON,\n HYPERCORE_USDC_ADDRESS,\n HYPERCORE_USDC_DECIMALS,\n NATIVE_TOKEN_ADDRESS,\n PERPS_DEPOSIT_TYPES,\n USDC_DECIMALS,\n PaymentOverride,\n} from '../../constants.js';\nimport { TransactionPayStrategy } from '../../index.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 } from '../../utils/amounts.js';\nimport {\n getFeatureFlags,\n getRelayOriginGasOverhead,\n getSlippage,\n getStablecoins,\n isAtomicMaxEnabled,\n isEIP7702Chain,\n isRelayExecuteEnabled,\n} from '../../utils/feature-flags.js';\nimport {\n GasPaymentMode,\n resolveGasPayment,\n resolveGasStationCost,\n} 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 { resolveNonAtomicRecipient } from '../../utils/second-leg.js';\nimport {\n getNativeToken,\n getTokenFiatRate,\n normalizeTokenAddress,\n TokenAddressTarget,\n} from '../../utils/token.js';\nimport { getQuotePricing } from '../../utils/trade-type.js';\nimport { TOKEN_TRANSFER_FOUR_BYTE } from './constants.js';\nimport { applyHyperliquidActivationFee } from './hyperliquid-activation.js';\nimport {\n applyPolymarketDepositWalletOverrides,\n getPredictWithdrawSafeAddress,\n isPredictWithdraw,\n} from './polymarket/withdraw.js';\nimport { fetchRelayQuote } from './relay-api.js';\nimport {\n getRelayMaxQuote,\n isSubsidizedAtomicMaxQuote,\n throwAtomicPromotionFailed,\n} from './relay-max.js';\nimport { validateRelayQuotes } from './relay-validation.js';\nimport type {\n RelayQuote,\n RelayQuoteMetamask,\n RelayQuoteRequest,\n RelayTransactionStep,\n} from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'relay-strategy');\n\n// Buffer applied to the gas cost when reserving native tokens for gas in\n// post-quote flows, accounting for gas limit re-estimation variance.\nconst POST_QUOTE_GAS_BUFFER = 1.1;\n\n// Hardcoded gas allowance for the prepended payment override transaction(s).\nconst PAYMENT_OVERRIDE_GAS = 75_000;\nconst ZERO_AMOUNT = { fiat: '0', human: '0', raw: '0', usd: '0' };\n\ntype RelayQuoteRequestDraft = Omit<RelayQuoteRequest, 'amount' | 'tradeType'> &\n Partial<Pick<RelayQuoteRequest, 'amount'>>;\ntype RelayStepData = RelayTransactionStep['items'][0]['data'];\n\ntype RelayGasResult = {\n totalGasEstimate: number;\n totalGasLimit: number;\n gasLimits: number[];\n is7702: boolean;\n};\n\n/**\n * Fetches Relay quotes.\n *\n * @param request - Request object.\n * @returns Array of quotes.\n */\nexport async function getRelayQuotes(\n request: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<RelayQuote>[]> {\n const { requests } = request;\n\n log('Fetching quotes', requests);\n\n try {\n const normalizedRequests = await Promise.all(\n requests\n .filter((singleRequest) => {\n const hasTargetMinimum = singleRequest.targetAmountMinimum !== '0';\n const isPostQuote = Boolean(singleRequest.isPostQuote);\n const isExactInputRequest =\n Boolean(singleRequest.isMaxAmount) &&\n new BigNumber(singleRequest.sourceTokenAmount).gt(0);\n\n return hasTargetMinimum || isPostQuote || isExactInputRequest;\n })\n .map((singleRequest) =>\n normalizeRequest(singleRequest, request.transaction),\n )\n .map((normalizedRequest) =>\n applyHyperliquidActivationFee(\n normalizedRequest,\n request.messenger,\n request.transaction,\n request.signal,\n ),\n ),\n );\n\n log('Normalized requests', normalizedRequests);\n\n const quotes = await Promise.all(\n normalizedRequests.map((singleRequest) =>\n getQuoteWithMaxAmountHandling(singleRequest, request),\n ),\n );\n\n const atomicMaxQuotes = quotes.filter(isSubsidizedAtomicMaxQuote);\n const otherQuotes = quotes.filter(\n (quote) => !isSubsidizedAtomicMaxQuote(quote),\n );\n\n if (otherQuotes.length > 0) {\n await validateRelayQuotes({\n messenger: request.messenger,\n quotes: otherQuotes,\n signal: request.signal,\n transaction: request.transaction,\n });\n }\n\n if (atomicMaxQuotes.length > 0) {\n try {\n await validateRelayQuotes({\n messenger: request.messenger,\n quotes: atomicMaxQuotes,\n signal: request.signal,\n transaction: request.transaction,\n });\n } catch (error) {\n throwAtomicPromotionFailed(error);\n }\n }\n\n return quotes;\n } catch (error) {\n log('Error fetching quotes', { error });\n throw error;\n }\n}\n\nasync function getQuoteWithMaxAmountHandling(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<RelayQuote>> {\n const { isMaxAmount } = request;\n\n if (!isMaxAmount) {\n return getQuoteWithPostQuoteGasHandling(request, fullRequest);\n }\n\n return getRelayMaxQuote(request, fullRequest, getSingleQuote);\n}\n\n/**\n * For post-quote flows, fetch an initial quote to compute gas cost in source\n * token, then re-quote with the source amount reduced by the gas cost.\n * This ensures Relay reserves enough for the gas fee token payment.\n *\n * For non-post-quote flows, just returns a single quote.\n *\n * @param request - Quote request.\n * @param fullRequest - Full request context.\n * @returns The final quote (phase 2 for post-quote, or phase 1 for normal).\n */\nasync function getQuoteWithPostQuoteGasHandling(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<RelayQuote>> {\n const phase1Quote = await getSingleQuote(request, fullRequest);\n\n if (!request.isPostQuote) {\n return phase1Quote;\n }\n\n if (phase1Quote.original.metamask?.isExecute) {\n return phase1Quote;\n }\n\n // Gas must be subtracted from the source amount when the user's balance\n // is fully committed to the swap. This applies when gas is paid via an\n // ERC-20 fee token (isSourceGasFeeToken) OR when the source itself is\n // the native gas token (gas comes from the same pool as the swap value).\n const isSourceNative =\n request.sourceTokenAddress.toLowerCase() ===\n getNativeToken(request.sourceChainId).toLowerCase() ||\n request.sourceTokenAddress.toLowerCase() ===\n NATIVE_TOKEN_ADDRESS.toLowerCase();\n\n if (!phase1Quote.fees.isSourceGasFeeToken && !isSourceNative) {\n return phase1Quote;\n }\n\n const gasCostRaw = new BigNumber(phase1Quote.fees.sourceNetwork.max.raw)\n .multipliedBy(POST_QUOTE_GAS_BUFFER)\n .integerValue(BigNumber.ROUND_UP);\n\n const existingHeadroom = new BigNumber(request.sourceBalanceRaw).minus(\n request.sourceTokenAmount,\n );\n\n if (existingHeadroom.isGreaterThanOrEqualTo(gasCostRaw)) {\n log('Sufficient existing balance for gas, skipping subtraction', {\n existingHeadroom: existingHeadroom.toString(10),\n gasCostRaw: gasCostRaw.toString(10),\n });\n return phase1Quote;\n }\n\n const adjustedSourceAmount = new BigNumber(request.sourceTokenAmount)\n .minus(gasCostRaw)\n .integerValue(BigNumber.ROUND_DOWN);\n\n log('Subtracting gas from source for post-quote two-call', {\n originalSourceAmount: request.sourceTokenAmount,\n gasCostRaw,\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n });\n\n if (!adjustedSourceAmount.isGreaterThan(0)) {\n log(\n 'Insufficient balance after gas subtraction for post-quote, using phase 1',\n );\n return phase1Quote;\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 (\n phase1Quote.fees.isSourceGasFeeToken &&\n !phase2Quote.fees.isSourceGasFeeToken\n ) {\n log('Phase 2 lost gas fee token eligibility, falling back to phase 1');\n return phase1Quote;\n }\n\n return phase2Quote;\n } catch (error) {\n log('Phase 2 quote failed, falling back to phase 1', { error });\n return phase1Quote;\n }\n}\n\n/**\n * Fetches a single Relay quote.\n *\n * @param request - Quote request.\n * @param fullRequest - Full quotes request.\n * @returns Single quote.\n */\nasync function getSingleQuote(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<RelayQuote>> {\n const {\n accountSupports7702: supports7702,\n messenger,\n signal,\n transaction,\n } = fullRequest;\n\n const {\n from,\n sourceChainId,\n sourceTokenAddress,\n sourceTokenAmount,\n targetAmountMinimum,\n targetChainId,\n targetTokenAddress,\n } = request;\n\n const slippageDecimal = getSlippage(\n messenger,\n sourceChainId,\n sourceTokenAddress,\n );\n\n const slippageTolerance = new BigNumber(slippageDecimal * 100 * 100).toFixed(\n 0,\n );\n\n try {\n const useExecute =\n supports7702 &&\n isRelayExecuteEnabled(messenger) &&\n isEIP7702Chain(messenger, sourceChainId);\n\n const nonAtomicRecipient = await resolveNonAtomicRecipient(\n transaction,\n request,\n messenger,\n );\n\n const effectiveRequest = nonAtomicRecipient\n ? { ...request, recipient: nonAtomicRecipient }\n : request;\n\n const body: RelayQuoteRequestDraft = {\n destinationChainId: Number(targetChainId),\n destinationCurrency: targetTokenAddress,\n originChainId: Number(sourceChainId),\n originCurrency: sourceTokenAddress,\n ...(useExecute\n ? {\n originGasOverhead: getRelayOriginGasOverhead(messenger),\n metamask: { executeVersion: 2 },\n }\n : {}),\n recipient: effectiveRequest.recipient ?? from,\n slippageTolerance,\n user: from,\n };\n\n if (effectiveRequest.isPolymarketDepositWallet) {\n await applyPolymarketDepositWalletOverrides(\n body,\n effectiveRequest,\n messenger,\n );\n }\n\n const isAtomic = effectiveRequest.atomic !== false;\n\n const processedTransactions = await processTransactions(\n transaction,\n effectiveRequest,\n body,\n messenger,\n );\n\n if (\n !processedTransactions &&\n isAtomic &&\n effectiveRequest.isPostQuote &&\n effectiveRequest.paymentOverride === PaymentOverride.MoneyAccount\n ) {\n await processMoneyAccountPostQuote(\n transaction,\n effectiveRequest,\n body,\n messenger,\n );\n } else if (!processedTransactions && effectiveRequest.refundTo) {\n // For post-quote flows, honour the caller-specified refund address so that\n // failed Relay transactions refund to the correct account (e.g. the Predict\n // Safe proxy) rather than defaulting to the EOA.\n body.refundTo = effectiveRequest.refundTo;\n }\n\n const pricing = getQuotePricing({\n hasCalls: Boolean(body.txs?.length),\n sourceTokenAmount,\n targetAmountMinimum,\n transaction,\n });\n\n const finalBody: RelayQuoteRequest = {\n ...body,\n // A step that bundled its own calls has already pinned the amount those\n // calls consume, so it wins over the derived amount.\n amount: body.amount ?? pricing.amount,\n tradeType: pricing.tradeType,\n };\n\n log('Request body', finalBody);\n\n const quote = await fetchRelayQuote(messenger, finalBody, signal);\n\n log('Fetched relay quote', quote);\n\n return await normalizeQuote(quote, effectiveRequest, fullRequest);\n } catch (error) {\n log('Error fetching relay quote', error);\n throw error;\n }\n}\n\nfunction normalizeAuthorizationList(\n authorizationList: AuthorizationList | undefined,\n): RelayQuoteRequest['authorizationList'] {\n return authorizationList?.map((a) => ({\n ...a,\n chainId: Number(a.chainId),\n nonce: Number(a.nonce),\n r: a.r as Hex,\n s: a.s as Hex,\n yParity: Number(a.yParity),\n }));\n}\n\n/**\n * Add tranasction data to request body if needed.\n *\n * @param transaction - Transaction metadata.\n * @param request - Quote request.\n * @param requestBody - Request body to populate.\n * @param messenger - Controller messenger.\n * @returns `true` when the transaction was embedded in the quote; `false` when\n * skipped so the caller can route to an alternate handler.\n */\nasync function processTransactions(\n transaction: TransactionMeta,\n request: QuoteRequest,\n requestBody: RelayQuoteRequestDraft,\n messenger: TransactionPayControllerMessenger,\n): Promise<boolean> {\n // Skip when skipProcessTransactions (defaulting to isPostQuote) is set — the\n // original transaction is submitted separately, not embedded in the quote.\n // Skip Polymarket deposit wallet flows — the source is already a bridged\n // token transfer, not a contract call to embed. Skip non-atomic flows — the\n // second leg is submitted after Relay settlement.\n if (\n (request.skipProcessTransactions ?? request.isPostQuote) === true ||\n request.isPolymarketDepositWallet === true ||\n request.atomic === false\n ) {\n return false;\n }\n\n const { nestedTransactions, txParams } = transaction;\n const { isMaxAmount, targetChainId } = request;\n const data = txParams?.data as Hex | undefined;\n\n const singleData =\n nestedTransactions?.length === 1 ? nestedTransactions[0].data : data;\n\n const isHypercore = targetChainId === CHAIN_ID_HYPERCORE;\n\n const isTokenTransfer =\n !isHypercore && Boolean(singleData?.startsWith(TOKEN_TRANSFER_FOUR_BYTE));\n\n if (isTokenTransfer) {\n requestBody.recipient = getTransferRecipient(singleData as Hex);\n\n log('Updating recipient as token transfer', requestBody.recipient);\n }\n\n const hasNoData = singleData === undefined || singleData === '0x';\n const skipDelegation = hasNoData || isTokenTransfer || isHypercore;\n\n if (skipDelegation) {\n log('Skipping delegation as token transfer or Hypercore deposit');\n return true;\n }\n\n // Eligible atomic max requests carry a destination amount, so the calls\n // below use EXACT_OUTPUT rather than the usual max EXACT_INPUT quote.\n if (\n isMaxAmount &&\n (request.isPostQuote === true ||\n !isAtomicMaxEnabled(messenger, transaction))\n ) {\n throw new Error('Max amount quotes do not support included transactions');\n }\n\n const delegation = await messenger.call(\n 'TransactionPayController:getDelegationTransaction',\n { transaction },\n );\n\n requestBody.authorizationList = normalizeAuthorizationList(\n delegation.authorizationList,\n );\n\n const tokenTransferData = nestedTransactions?.find((nestedTx) =>\n nestedTx.data?.startsWith(TOKEN_TRANSFER_FOUR_BYTE),\n )?.data;\n\n // If the transactions include a token transfer, change the recipient\n // so any extra dust is also sent to the same address, rather than back to the user.\n if (tokenTransferData) {\n requestBody.recipient = getTransferRecipient(tokenTransferData);\n requestBody.refundTo = request.from;\n }\n\n requestBody.txs = [\n {\n to: request.targetTokenAddress,\n data: buildTokenTransferData(\n transaction.txParams.from as Hex,\n request.targetAmountMinimum,\n ),\n value: '0x0',\n },\n {\n to: delegation.to,\n data: delegation.data,\n value: delegation.value,\n },\n ];\n\n return true;\n}\n\nasync function processMoneyAccountPostQuote(\n transaction: TransactionMeta,\n request: QuoteRequest,\n requestBody: RelayQuoteRequestDraft,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n const { transactionData: transactionDataList } = messenger.call(\n 'TransactionPayController:getState',\n );\n\n const transactionData = transactionDataList[transaction.id];\n const amountHuman = transactionData?.tokens?.[0]?.amountHuman ?? '0';\n\n const {\n calls: overrideCalls,\n recipient,\n authorizationList,\n } = await messenger.call('TransactionPayController:getPaymentOverrideData', {\n amount: amountHuman,\n transaction,\n transactionData,\n });\n\n if (!overrideCalls.length) {\n log('No payment override calls for money account post-quote');\n return;\n }\n\n const fundingRecipient = recipient ?? request.from;\n const rawAmount = transactionData?.tokens?.[0]?.amountRaw ?? '0';\n\n requestBody.authorizationList = normalizeAuthorizationList(authorizationList);\n requestBody.amount = rawAmount;\n requestBody.txs = [\n {\n to: request.targetTokenAddress,\n data: buildTokenTransferData(fundingRecipient, rawAmount),\n value: '0x0',\n },\n ...overrideCalls.map((call) => ({\n to: call.to as Hex,\n data: call.data as Hex,\n value: (call.value as Hex) ?? '0x0',\n })),\n ];\n\n log('Added money account deposit calls to quote body', {\n callCount: overrideCalls.length,\n });\n}\n\n/**\n * Normalizes requests for Relay.\n *\n * @param request - Quote request to normalize.\n * @param transaction - Parent transaction metadata, used to gate\n * Hyperliquid-specific rewrites on transaction type.\n * @returns Normalized request.\n */\nfunction normalizeRequest(\n request: QuoteRequest,\n transaction: TransactionMeta,\n): QuoteRequest {\n const newRequest = {\n ...request,\n };\n\n const isPerpsDeposit =\n transaction.type !== undefined &&\n PERPS_DEPOSIT_TYPES.includes(transaction.type);\n\n const isHyperliquidDeposit =\n isPerpsDeposit &&\n !request.isPostQuote &&\n request.targetChainId === CHAIN_ID_ARBITRUM &&\n request.targetTokenAddress.toLowerCase() ===\n ARBITRUM_USDC_ADDRESS.toLowerCase();\n\n newRequest.sourceTokenAddress = normalizeTokenAddress(\n newRequest.sourceTokenAddress,\n newRequest.sourceChainId,\n TokenAddressTarget.Relay,\n );\n newRequest.targetTokenAddress = normalizeTokenAddress(\n newRequest.targetTokenAddress,\n newRequest.targetChainId,\n TokenAddressTarget.Relay,\n );\n\n if (isHyperliquidDeposit) {\n newRequest.targetChainId = CHAIN_ID_HYPERCORE;\n newRequest.targetTokenAddress = HYPERCORE_USDC_ADDRESS;\n newRequest.targetAmountMinimum = new BigNumber(request.targetAmountMinimum)\n .shiftedBy(HYPERCORE_USDC_DECIMALS - USDC_DECIMALS)\n .toString(10);\n\n log('Converting Arbitrum Hyperliquid deposit to direct deposit', {\n originalRequest: request,\n normalizedRequest: newRequest,\n });\n }\n\n // HyperLiquid withdrawal: source is HyperCore Perps USDC, not Arbitrum.\n if (request.isHyperliquidSource) {\n newRequest.sourceChainId = CHAIN_ID_HYPERCORE;\n newRequest.sourceTokenAddress = HYPERCORE_USDC_ADDRESS;\n\n if (newRequest.sourceTokenAmount) {\n newRequest.sourceTokenAmount = new BigNumber(newRequest.sourceTokenAmount)\n .shiftedBy(HYPERCORE_USDC_DECIMALS - USDC_DECIMALS)\n .toString(10);\n }\n }\n\n return newRequest;\n}\n\n/**\n * Normalizes a Relay quote into a TransactionPayQuote.\n *\n * @param quote - Relay quote.\n * @param request - Original quote request.\n * @param fullRequest - Full quotes request.\n * @returns Normalized quote.\n */\nasync function normalizeQuote(\n quote: RelayQuote,\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<RelayQuote>> {\n const { messenger } = fullRequest;\n const { details } = quote;\n const { currencyIn, currencyOut } = details;\n\n const { usdToFiatRate } = getFiatRates(messenger, request);\n\n const dust = getFiatValueFromUsd(\n calculateDustUsd(quote, request),\n usdToFiatRate,\n );\n\n const subsidizedFeeUsd = getSubsidizedFeeAmountUsd(messenger, quote);\n\n const appFeeUsd = new BigNumber(quote.fees?.app?.amountUsd ?? '0');\n const metaMaskFee = getFiatValueFromUsd(appFeeUsd, usdToFiatRate);\n\n // Subtract app fee from provider fee since totalImpact.usd already includes\n // it. The relay provider fee is forced to zero when the quote is subsidized,\n // but any reserved HyperLiquid activation fee is withheld from the source\n // send regardless, so it must always be surfaced in the provider fee.\n const activationFeeUsd = new BigNumber(\n request.hyperliquidActivationFeeUsd ?? '0',\n );\n const providerFeeUsd = subsidizedFeeUsd.gt(0)\n ? activationFeeUsd\n : calculateProviderFee(quote).minus(appFeeUsd).plus(activationFeeUsd);\n const provider = getFiatValueFromUsd(providerFeeUsd, usdToFiatRate);\n\n const {\n gasLimits,\n is7702,\n isGasFeeToken: isSourceGasFeeToken,\n ...sourceNetwork\n } = await calculateSourceNetworkCost(\n quote,\n messenger,\n request,\n fullRequest.transaction,\n fullRequest.accountSupports7702,\n );\n\n const targetNetwork = {\n usd: '0',\n fiat: '0',\n };\n\n const sourceAmount: Amount = {\n human: currencyIn.amountFormatted,\n raw: currencyIn.amount,\n ...getFiatValueFromUsd(new BigNumber(currencyIn.amountUsd), usdToFiatRate),\n };\n\n const isTargetStablecoin = isStablecoin(\n messenger,\n request.targetChainId,\n request.targetTokenAddress,\n );\n\n const targetAmountUsd = isTargetStablecoin\n ? new BigNumber(currencyOut.amountFormatted)\n : new BigNumber(currencyOut.amountUsd);\n\n const targetAmount = getFiatValueFromUsd(targetAmountUsd, usdToFiatRate);\n\n const metamask: RelayQuoteMetamask = {\n ...quote.metamask,\n gasLimits: is7702 ? [gasLimits[0]] : gasLimits,\n is7702,\n };\n\n return {\n dust,\n estimatedDuration: details.timeEstimate,\n fees: {\n isSourceGasFeeToken,\n metaMask: metaMaskFee,\n provider,\n sourceNetwork,\n targetNetwork,\n },\n isInputBased: quote.request.tradeType === 'EXACT_INPUT',\n original: {\n ...quote,\n metamask,\n },\n request,\n sourceAmount,\n targetAmount,\n strategy: TransactionPayStrategy.Relay,\n };\n}\n\n/**\n * Calculate dust USD value.\n *\n * @param quote - Relay quote.\n * @param request - Quote request.\n * @returns Dust value in USD and fiat.\n */\nfunction calculateDustUsd(quote: RelayQuote, request: QuoteRequest): BigNumber {\n const { currencyOut } = quote.details;\n const { amountUsd, amountFormatted, minimumAmount } = currencyOut;\n const { decimals: targetDecimals } = currencyOut.currency;\n\n const targetUsdRate = new BigNumber(amountUsd).dividedBy(amountFormatted);\n\n const dustRaw = BigNumber.maximum(\n new BigNumber(minimumAmount).minus(request.targetAmountMinimum),\n 0,\n );\n\n return dustRaw.shiftedBy(-targetDecimals).multipliedBy(targetUsdRate);\n}\n\n/**\n * Calculates USD to fiat rate.\n *\n * @param messenger - Controller messenger.\n * @param request - Quote request.\n * @returns USD to fiat rate.\n */\nfunction getFiatRates(\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n): {\n sourceFiatRate: FiatRates;\n usdToFiatRate: BigNumber;\n} {\n // For HyperLiquid source, the normalized chain/token (HyperCore + Perps USDC)\n // won't have a fiat rate entry. Use Arbitrum USDC instead since Perps USDC\n // is pegged 1:1.\n const sourceChainId = request.isHyperliquidSource\n ? CHAIN_ID_ARBITRUM\n : request.sourceChainId;\n const sourceTokenAddress = request.isHyperliquidSource\n ? ARBITRUM_USDC_ADDRESS\n : request.sourceTokenAddress;\n\n const finalSourceTokenAddress =\n sourceChainId === CHAIN_ID_POLYGON &&\n sourceTokenAddress === NATIVE_TOKEN_ADDRESS\n ? getNativeToken(sourceChainId)\n : sourceTokenAddress;\n\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n finalSourceTokenAddress,\n sourceChainId,\n );\n\n if (!sourceFiatRate) {\n throw new Error('Source token fiat rate not found');\n }\n\n const usdToFiatRate = new BigNumber(sourceFiatRate.fiatRate).dividedBy(\n sourceFiatRate.usdRate,\n );\n\n return { sourceFiatRate, usdToFiatRate };\n}\n\n/**\n * Calculates source network cost from a Relay quote.\n *\n * For post-quote flows (e.g. predictWithdraw), the cost also includes the\n * original transaction's gas (the user's Polygon USDC.e transfer) in addition\n * to the Relay deposit transaction gas, by appending the original\n * transaction's params so that gas estimation and gas-fee-token logic handle\n * both transactions together.\n *\n * Network fees are zeroed whenever the user does not pay origin gas, either\n * because a relayer covers it or because MetaMask sponsors it.\n *\n * @param quote - Relay quote.\n * @param messenger - Controller messenger.\n * @param request - Quote request.\n * @param transaction - Original transaction metadata.\n * @param accountSupports7702 - Whether the source account supports EIP-7702.\n * @returns Total source network cost in USD and fiat.\n */\nasync function calculateSourceNetworkCost(\n quote: RelayQuote,\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n transaction: TransactionMeta,\n accountSupports7702: boolean | undefined,\n): Promise<\n TransactionPayQuote<RelayQuote>['fees']['sourceNetwork'] & {\n gasLimits: number[];\n isGasFeeToken?: boolean;\n is7702: boolean;\n }\n> {\n const { from, sourceChainId, sourceTokenAddress } = request;\n\n // None of these flows bill origin gas to the user: the execute flow has a\n // relayer redeem a signed delegation, a HyperLiquid withdrawal's \"deposit\"\n // step is an off-chain HL sendAsset signature rather than an on-chain\n // transaction, and a Polymarket deposit-wallet withdraw is submitted by the\n // Polymarket relayer.\n const isExecuteFlow = Boolean(quote.metamask?.isExecute);\n const isHyperliquidWithdrawal = Boolean(request.isHyperliquidSource);\n const isPolymarketDepositWallet = Boolean(request.isPolymarketDepositWallet);\n\n const gasPayment = resolveGasPayment({\n isDelegated:\n isExecuteFlow || isHyperliquidWithdrawal || isPolymarketDepositWallet,\n sourceTokenAddress,\n sponsorship: {\n accountSupports7702,\n request,\n transaction,\n },\n });\n\n if (gasPayment.mode === GasPaymentMode.Delegation) {\n log('Zeroing network fees as the user does not pay origin gas', {\n isExecuteFlow,\n isHyperliquidWithdrawal,\n isPolymarketDepositWallet,\n });\n\n return {\n estimate: ZERO_AMOUNT,\n max: ZERO_AMOUNT,\n gasLimits: [],\n is7702: false,\n };\n }\n\n if (gasPayment.mode === GasPaymentMode.Sponsored) {\n log('Zeroing source network fees for sponsored same-chain Relay route');\n\n // Gas limit is zero as sponsored transactions go through the EIP-7702\n // gas station hook and do not require user-paid gas.\n return {\n estimate: ZERO_AMOUNT,\n max: ZERO_AMOUNT,\n gasLimits: [0],\n is7702: true,\n };\n }\n\n const txSteps = quote.steps.filter(\n (step): step is RelayTransactionStep => step.kind === 'transaction',\n );\n const relayParams = txSteps\n .flatMap((step) => step.items)\n .map((item) => item.data);\n\n const { chainId, data, maxFeePerGas, maxPriorityFeePerGas, to, value } =\n relayParams[0];\n\n const isPredictWithdrawFlow = isPredictWithdraw(request, transaction);\n\n // `fromOverride = Safe proxy` is only valid for deposit-style Relay routes\n // where the deposit contract reads the user's source-token balance directly.\n // Same-chain destinations route through DEX swap aggregators that frequently\n // reject contract callers (anti-MEV `msg.sender == tx.origin` checks,\n // ERC777-style callback interfaces, native wrap/unwrap requiring caller\n // native balance). Simulating those from the Safe proxy reverts and breaks\n // gas estimation. For swap-only routes, fall back to the relay params'\n // EOA `from` so simulation succeeds.\n const fromOverride = getPredictWithdrawSafeAddress(\n request,\n quote.steps,\n transaction,\n );\n\n // For post-quote flows the original transaction will be prepended to the\n // batch at submission time. Include it in the gas estimation so\n // estimateGasBatch sees the full batch and can detect EIP-7702 support.\n // Without this, a single relay step is estimated alone, gets is7702=false,\n // and the batch falls back to separate type-0x2 transactions that each\n // need native gas — breaking zero-balance fiat-funded accounts.\n const originalTxGasParams = getOriginalTxGasParams(request, transaction);\n const allGasParams = originalTxGasParams\n ? [originalTxGasParams, ...relayParams]\n : relayParams;\n\n const gasResult = await calculateSourceNetworkGasLimit(\n allGasParams,\n messenger,\n fromOverride,\n );\n\n // When the original tx was NOT included in gas estimation (no gas params\n // available), fall back to the legacy prepend-after-the-fact approach.\n const { gasLimits, is7702, totalGasEstimate, totalGasLimit } =\n originalTxGasParams\n ? gasResult\n : combinePrependedGas(gasResult, request, transaction);\n\n log('Gas limit', {\n is7702,\n totalGasEstimate,\n totalGasLimit,\n gasLimits,\n });\n\n const estimate = calculateGasCost({\n chainId,\n gas: totalGasEstimate,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n });\n\n const max = calculateGasCost({\n chainId,\n gas: totalGasLimit,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n isMax: true,\n });\n\n const result = { estimate, max, gasLimits, is7702 };\n\n // Gas-fee-token lookup must use the Safe proxy for ALL Predict withdraws,\n // not only deposit-style routes. The user's source token (pUSD) lives in\n // the Safe; the EOA is empty until the Safe.execTransaction sub-call runs\n // mid-batch. Querying the EOA for gas-fee-token availability would always\n // return nothing and force users to hold POL.\n // (`useFromOverride` only governs the gas-estimation `from` address, where\n // swap-style routes need EOA because DEX routers reject contract callers.)\n const proxyFeeTokenAccount = isPredictWithdrawFlow\n ? request.refundTo\n : undefined;\n\n const gasStationCost = await resolveGasStationCost({\n accountSupports7702,\n feeTokenAccount: proxyFeeTokenAccount,\n firstStepData: {\n data,\n to,\n value,\n },\n messenger,\n nativeGasCostRaw: max.raw,\n request: {\n from,\n sourceChainId,\n sourceTokenAddress,\n },\n totalGasEstimate,\n totalItemCount: proxyFeeTokenAccount\n ? relayParams.length + 1\n : Math.max(relayParams.length, gasLimits.length),\n });\n\n if (!gasStationCost.amount) {\n return result;\n }\n\n log('Using gas fee token for source network', {\n gasFeeTokenCost: gasStationCost.amount,\n proxyFeeTokenAccount,\n });\n\n return {\n isGasFeeToken: true,\n estimate: gasStationCost.amount,\n max: gasStationCost.amount,\n gasLimits,\n is7702,\n };\n}\n\n/**\n * Calculate the total gas limit for the source network.\n *\n * @param params - Array of relay transaction parameters.\n * @param messenger - Controller messenger.\n * @param fromOverride - Optional address to use as `from` in gas estimation\n * instead of the address in the relay params. Used in predict withdraw flows\n * to estimate with the proxy/Safe address that holds the source token balance.\n * @returns Total gas estimates and per-transaction gas limits.\n */\nasync function calculateSourceNetworkGasLimit(\n params: RelayTransactionStep['items'][0]['data'][],\n messenger: TransactionPayControllerMessenger,\n fromOverride?: Hex,\n): Promise<{\n totalGasEstimate: number;\n totalGasLimit: number;\n gasLimits: number[];\n is7702: boolean;\n}> {\n const transactions = params.map((singleParams) =>\n toRelayQuoteGasTransaction(singleParams, fromOverride),\n );\n\n const relayGasResult = await estimateQuoteGasLimits({\n fallbackGas: getFeatureFlags(messenger).relayFallbackGas,\n fallbackOnSimulationFailure: true,\n messenger,\n transactions,\n });\n\n return {\n gasLimits: relayGasResult.gasLimits.map((gasLimit) => gasLimit.max),\n is7702: relayGasResult.is7702,\n totalGasEstimate: relayGasResult.totalGasEstimate,\n totalGasLimit: relayGasResult.totalGasLimit,\n };\n}\n\nfunction toRelayQuoteGasTransaction(\n singleParams: RelayTransactionStep['items'][0]['data'],\n fromOverride?: Hex,\n): QuoteGasTransaction {\n return {\n chainId: toHex(singleParams.chainId),\n data: singleParams.data,\n from: fromOverride ?? singleParams.from,\n gas: fromOverride ? undefined : singleParams.gas,\n to: singleParams.to,\n value: singleParams.value ?? '0',\n };\n}\n\nfunction getOriginalTxGasParams(\n request: QuoteRequest,\n transaction: TransactionMeta,\n): RelayStepData | undefined {\n if (!request.isPostQuote) {\n return undefined;\n }\n\n const { txParams } = transaction;\n const to = txParams.to as Hex | undefined;\n\n if (!to) {\n return undefined;\n }\n\n const hasAccountOverride =\n request.from.toLowerCase() !== (txParams.from as Hex).toLowerCase();\n\n if (hasAccountOverride) {\n return undefined;\n }\n\n const nestedGas = transaction.nestedTransactions?.find((tx) => tx.gas)?.gas;\n const gas = nestedGas ?? txParams.gas;\n\n return {\n chainId: Number(transaction.chainId),\n data: (txParams.data as Hex) ?? '0x',\n from: txParams.from as Hex,\n gas: gas ? String(gas) : undefined,\n maxFeePerGas: '0',\n maxPriorityFeePerGas: '0',\n to,\n value: txParams.value ?? '0',\n };\n}\n\nfunction combinePrependedGas(\n relayOnlyGas: RelayGasResult,\n request: QuoteRequest,\n transaction: TransactionMeta,\n): RelayGasResult {\n const gas = request.isPostQuote\n ? combinePostQuoteGas(relayOnlyGas, transaction)\n : relayOnlyGas;\n\n return request.paymentOverride ? addPaymentOverrideGas(gas) : gas;\n}\n\n/**\n * Combine the original transaction's gas with relay gas for post-quote flows.\n *\n * Prefers gas from `nestedTransactions` (preserves the caller-provided value)\n * since TransactionController may re-estimate `txParams.gas` during batch\n * creation.\n *\n * @param relayGas - Gas estimates from relay transactions.\n * @param relayGas.totalGasEstimate - Estimated gas total.\n * @param relayGas.totalGasLimit - Maximum gas total.\n * @param relayGas.gasLimits - Per-transaction gas limits.\n * @param relayGas.is7702 - Whether the relay gas came from a combined 7702 batch estimate.\n * @param transaction - Original transaction metadata.\n * @returns Combined gas estimates including the original transaction.\n */\nfunction combinePostQuoteGas(\n relayGas: RelayGasResult,\n transaction: TransactionMeta,\n): RelayGasResult {\n const nestedGas = transaction.nestedTransactions?.find((tx) => tx.gas)?.gas;\n const rawGas = nestedGas ?? transaction.txParams.gas;\n const originalTxGas = rawGas ? new BigNumber(rawGas).toNumber() : undefined;\n\n if (originalTxGas === undefined) {\n return relayGas;\n }\n\n let { gasLimits } = relayGas;\n\n if (relayGas.is7702) {\n // Combined 7702 gas limit — add the original tx gas so the batch\n // keeps using a single 7702 limit.\n gasLimits = [gasLimits[0] + originalTxGas];\n } else {\n // Multiple individual gas limits — prepend the original tx gas\n // so the list order matches relay-submit's transaction order.\n gasLimits = [originalTxGas, ...gasLimits];\n }\n\n const totalGasEstimate = relayGas.totalGasEstimate + originalTxGas;\n const totalGasLimit = relayGas.totalGasLimit + originalTxGas;\n\n log('Combined original tx gas with relay gas', {\n originalTxGas,\n is7702: relayGas.is7702,\n gasLimits,\n totalGasLimit,\n });\n\n return {\n totalGasEstimate,\n totalGasLimit,\n gasLimits,\n is7702: relayGas.is7702,\n };\n}\n\nfunction addPaymentOverrideGas(relayGas: RelayGasResult): RelayGasResult {\n const gasLimits = relayGas.is7702\n ? [relayGas.gasLimits[0] + PAYMENT_OVERRIDE_GAS]\n : [PAYMENT_OVERRIDE_GAS, ...relayGas.gasLimits];\n\n return {\n totalGasEstimate: relayGas.totalGasEstimate + PAYMENT_OVERRIDE_GAS,\n totalGasLimit: relayGas.totalGasLimit + PAYMENT_OVERRIDE_GAS,\n gasLimits,\n is7702: relayGas.is7702,\n };\n}\n\n/**\n * Calculate the provider fee for a Relay quote.\n *\n * @param quote - Relay quote.\n * @returns - Provider fee in USD.\n */\nfunction calculateProviderFee(quote: RelayQuote): BigNumber {\n return new BigNumber(quote.details.totalImpact.usd).abs();\n}\n\n/**\n * Build token transfer data.\n *\n * @param recipient - Recipient address.\n * @param amountRaw - Amount in raw format.\n * @returns Token transfer data.\n */\nfunction buildTokenTransferData(recipient: Hex, amountRaw: string): Hex {\n return new Interface([\n 'function transfer(address to, uint256 amount)',\n ]).encodeFunctionData('transfer', [recipient, amountRaw]) as Hex;\n}\n\n/**\n * Get transfer recipient from token transfer data.\n *\n * @param data - Token transfer data.\n * @returns Transfer recipient.\n */\nfunction getTransferRecipient(data: Hex): Hex {\n return new Interface(['function transfer(address to, uint256 amount)'])\n .decodeFunctionData('transfer', data)\n .to.toLowerCase();\n}\nfunction getSubsidizedFeeAmountUsd(\n messenger: TransactionPayControllerMessenger,\n quote: RelayQuote,\n): BigNumber {\n const subsidizedFee = quote.fees?.subsidized;\n const amountUsd = new BigNumber(subsidizedFee?.amountUsd ?? '0');\n const amountFormatted = new BigNumber(subsidizedFee?.amountFormatted ?? '0');\n\n if (!subsidizedFee || amountUsd.isZero()) {\n return new BigNumber(0);\n }\n\n const isSubsidizedStablecoin = isStablecoin(\n messenger,\n toHex(subsidizedFee.currency.chainId),\n subsidizedFee.currency.address,\n );\n\n return isSubsidizedStablecoin ? amountFormatted : amountUsd;\n}\n\nfunction isStablecoin(\n messenger: TransactionPayControllerMessenger,\n chainId: string,\n tokenAddress: string,\n): boolean {\n return Boolean(\n getStablecoins(messenger)[chainId as Hex]?.includes(\n tokenAddress.toLowerCase() as Hex,\n ),\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"relay-submit.d.ts","sourceRoot":"","sources":["../../../src/strategy/relay/relay-submit.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAKV,eAAe,EACf,iBAAiB,EAClB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAK3C,OAAO,KAAK,EACV,yBAAyB,EACzB,iCAAiC,EACjC,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAwCxB,OAAO,KAAK,EAEV,UAAU,EAIX,MAAM,YAAY,CAAC;AAUpB,MAAM,MAAM,gBAAgB,GAAG;IAAE,KAAK,EAAE,iBAAiB,EAAE,CAAA;CAAE,CAAC;AAE9D;;;;;GAKG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,yBAAyB,CAAC,UAAU,CAAC,GAC7C,OAAO,CAAC;IAAE,eAAe,CAAC,EAAE,GAAG,CAAA;CAAE,CAAC,CAMpC;AAED,wBAAsB,mBAAmB,CAAC,EACxC,SAAS,EACT,KAAK,EACL,WAAW,GACZ,EAAE;IACD,SAAS,EAAE,iCAAiC,CAAC;IAC7C,KAAK,EAAE,mBAAmB,CAAC,UAAU,CAAC,CAAC;IACvC,WAAW,EAAE,eAAe,CAAC;CAC9B,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAO5B"}
1
+ {"version":3,"file":"relay-submit.d.ts","sourceRoot":"","sources":["../../../src/strategy/relay/relay-submit.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAKV,eAAe,EACf,iBAAiB,EAClB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAK3C,OAAO,KAAK,EACV,yBAAyB,EACzB,iCAAiC,EACjC,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAuCxB,OAAO,KAAK,EAEV,UAAU,EAIX,MAAM,YAAY,CAAC;AAUpB,MAAM,MAAM,gBAAgB,GAAG;IAAE,KAAK,EAAE,iBAAiB,EAAE,CAAA;CAAE,CAAC;AAE9D;;;;;GAKG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,yBAAyB,CAAC,UAAU,CAAC,GAC7C,OAAO,CAAC;IAAE,eAAe,CAAC,EAAE,GAAG,CAAA;CAAE,CAAC,CAMpC;AAED,wBAAsB,mBAAmB,CAAC,EACxC,SAAS,EACT,KAAK,EACL,WAAW,GACZ,EAAE;IACD,SAAS,EAAE,iCAAiC,CAAC;IAC7C,KAAK,EAAE,mBAAmB,CAAC,UAAU,CAAC,CAAC;IACvC,WAAW,EAAE,eAAe,CAAC;CAC9B,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAO5B"}
@@ -7,10 +7,10 @@ import { accountSupports7702 } from '../../utils/7702.js';
7
7
  import { prefixError } from '../../utils/error-prefix.js';
8
8
  import { getFeatureFlags, getRelayPollingInterval, getRelayPollingTimeout, } from '../../utils/feature-flags.js';
9
9
  import { logGasPaymentOutcome, resolveGasPayment, } from '../../utils/gas-payment.js';
10
- import { submitMoneyAccountVaultDeposit } from '../../utils/ma-vault-deposit.js';
11
10
  import { getNetworkClientId } from '../../utils/provider.js';
11
+ import { submitSecondLeg } from '../../utils/second-leg.js';
12
12
  import { getLiveTokenBalance, normalizeTokenAddress, TokenAddressTarget, } from '../../utils/token.js';
13
- import { collectTransactionIds, getTransaction, getTransferredAmountFromTxHash, updateTransaction, waitForTransactionConfirmed, } from '../../utils/transaction.js';
13
+ import { collectTransactionIds, getTransaction, updateTransaction, waitForTransactionConfirmed, } from '../../utils/transaction.js';
14
14
  import { FALLBACK_HASH, RELAY_DEPOSIT_TYPES, RELAY_FAILURE_STATUSES, RELAY_PENDING_STATUSES, } from './constants.js';
15
15
  import { submitHyperliquidWithdraw } from './hyperliquid-withdraw.js';
16
16
  import { sweepPolymarketDepositWallet, submitPolymarketWithdraw, } from './polymarket/withdraw.js';
@@ -106,94 +106,80 @@ async function executeSingleQuote(quote, messenger, transaction) {
106
106
  throw new Error(`Request failed with status: ${completion.status}`);
107
107
  }
108
108
  }
109
- updateTransaction({
110
- transactionId: transaction.id,
111
- messenger,
112
- note: 'Intent complete after Relay completion',
113
- }, (tx) => {
114
- tx.isIntentComplete = true;
115
- });
116
109
  // Non-atomic flow: the quote bridged funds to `recipient` without embedding
117
110
  // the second leg. Now that Relay has settled, resolve the settled amount from
118
111
  // the on-chain Transfer log and submit the second-leg batch (approve + vault
119
112
  // deposit) sponsored from `recipient`.
120
- if (quote.request.atomic === false && completion.status === 'success') {
121
- const { transactionHash } = await submitPostNonAtomic({
113
+ const { transactionHash: secondLegHash } = quote.request.atomic === false && completion.status === 'success'
114
+ ? await submitPostNonAtomic({
122
115
  completion,
123
116
  messenger,
124
117
  quote,
125
118
  submittedSourceHash,
126
119
  transaction,
127
- });
128
- return { transactionHash: transactionHash ?? completion.targetHash };
129
- }
130
- return { transactionHash: completion.targetHash };
120
+ })
121
+ : {};
122
+ // Only complete once every leg has landed, so a failed second leg does not
123
+ // leave the parent transaction flagged as achieved.
124
+ updateTransaction({
125
+ transactionId: transaction.id,
126
+ messenger,
127
+ note: 'Intent complete after Relay completion',
128
+ }, (tx) => {
129
+ tx.isIntentComplete = true;
130
+ });
131
+ return { transactionHash: secondLegHash ?? completion.targetHash };
131
132
  }
132
133
  /**
133
- * Runs the second leg of a non-atomic Relay quote. Resolves the settled amount
134
- * from the on-chain Transfer log, then submits the batch via
135
- * `submitMoneyAccountVaultDeposit`. Post-quote flows fetch pre-built calls via
136
- * the client `getPaymentOverrideData` callback; non-post-quote flows fall
137
- * through to the transaction's own nested calls re-encoded via
138
- * `getAmountData`. Funds settled on `quote.request.recipient`, derived at
139
- * quote time by `resolveNonAtomicRecipient`.
134
+ * Runs the second leg of a non-atomic Relay quote on the target chain from
135
+ * `quote.request.recipient`, where the funds settled (derived at quote time by
136
+ * `resolveNonAtomicRecipient`). Post-quote flows build their calls via the
137
+ * client `getPaymentOverrideData` callback; non-post-quote flows fall through
138
+ * to the transaction's own nested calls re-encoded via `getAmountData`.
140
139
  *
141
140
  * @param options - Submit options.
142
141
  * @param options.completion - Outcome of `waitForRelayCompletion`.
143
142
  * @param options.messenger - Controller messenger.
144
143
  * @param options.quote - The Relay quote that was submitted.
145
144
  * @param options.submittedSourceHash - Hash of the submitted source
146
- * transaction, used to read the settled amount when Relay skips polling on
145
+ * transaction, used as the settlement hash when Relay skips polling on
147
146
  * same-chain flows.
148
147
  * @param options.transaction - Original transaction meta.
149
148
  * @returns Hash of the final submitted child transaction, if available.
150
149
  */
151
150
  async function submitPostNonAtomic({ completion, messenger, quote, submittedSourceHash, transaction, }) {
152
- const sourceAmountRaw = await resolveSettledAmount({
153
- completion,
151
+ const { from, isPostQuote, recipient, targetChainId, targetTokenAddress } = quote.request;
152
+ return await submitSecondLeg({
153
+ chainId: targetChainId,
154
+ from: recipient ?? from,
155
+ getCalls: isPostQuote
156
+ ? async (sourceAmountRaw) => await buildPostQuoteDepositCalls({
157
+ messenger,
158
+ quote,
159
+ sourceAmountRaw,
160
+ transaction,
161
+ })
162
+ : undefined,
154
163
  messenger,
155
- quote,
156
- submittedSourceHash,
157
- });
158
- const override = quote.request.isPostQuote
159
- ? await buildPostQuoteDepositCalls({
160
- messenger,
161
- sourceAmountRaw,
162
- transaction,
164
+ settlementHash: getSettlementHash({
165
+ completion,
163
166
  quote,
164
- })
165
- : undefined;
166
- const recipient = override?.recipient ?? quote.request.recipient ?? quote.request.from;
167
- return submitMoneyAccountVaultDeposit({
168
- messenger,
169
- moneyAccountAddress: recipient,
170
- depositCalls: override?.calls,
171
- sourceAmountRaw,
167
+ submittedSourceHash,
168
+ }),
169
+ tokenAddress: targetTokenAddress,
172
170
  transaction,
173
- vaultDisabled: false,
174
171
  });
175
172
  }
176
173
  /**
177
- * Builds the post-completion batch for a post-quote flow whose parent
178
- * transaction carries no vault calls. Delegates to the client
179
- * `getPaymentOverrideData` callback with the settled amount.
180
- *
181
- * The callback MUST return a non-empty batch. Post-quote parent metas (e.g.
182
- * Perps/Predict withdraws) carry no vault-side nested calls, so falling back
183
- * to `getAmountData` in `resolveVaultDepositBatch` cannot recover the second
184
- * leg once Relay has already settled funds to the recipient. Throw eagerly so
185
- * the failure surfaces at the correct call site with an actionable message.
186
- *
187
- * The callback may also return the `recipient` that funds settled on, which the
188
- * caller prefers as the source of truth for the second-leg account.
174
+ * Builds the second-leg batch for a post-quote flow whose parent transaction
175
+ * carries no vault calls, via the client `getPaymentOverrideData` callback.
189
176
  *
190
177
  * @param options - Build options.
191
178
  * @param options.messenger - Controller messenger.
192
179
  * @param options.quote - The Relay quote that was submitted.
193
180
  * @param options.sourceAmountRaw - Settled amount in raw units.
194
181
  * @param options.transaction - Original transaction meta.
195
- * @returns The batch calls and optional recipient.
196
- * @throws If the callback returns an empty batch.
182
+ * @returns The batch calls.
197
183
  */
198
184
  async function buildPostQuoteDepositCalls({ messenger, quote, sourceAmountRaw, transaction, }) {
199
185
  const { transactionData } = messenger.call('TransactionPayController:getState');
@@ -201,75 +187,38 @@ async function buildPostQuoteDepositCalls({ messenger, quote, sourceAmountRaw, t
201
187
  const amountHuman = new BigNumber(sourceAmountRaw)
202
188
  .shiftedBy(-decimals)
203
189
  .toFixed();
204
- const { calls, recipient } = await messenger.call('TransactionPayController:getPaymentOverrideData', {
190
+ const { calls } = await messenger.call('TransactionPayController:getPaymentOverrideData', {
205
191
  amount: amountHuman,
206
192
  transaction,
207
193
  transactionData: transactionData[transaction.id],
208
194
  });
209
- if (!calls.length) {
210
- throw new Error('Missing post-quote deposit calls');
211
- }
212
- return { calls, recipient };
195
+ return calls;
213
196
  }
214
197
  /**
215
- * Resolves the actual amount that landed on the recipient after a Relay bridge.
216
- *
217
- * Cross-chain relays surface a real target-chain hash from polling; same-chain
218
- * relays skip polling (the `FALLBACK_HASH` placeholder) but the submitted
219
- * source transaction itself moved the funds, so its hash is read instead. In
220
- * both cases the exact settled amount comes from the on-chain Transfer log; a
221
- * read failure or missing amount throws rather than guessing, since using the
222
- * quote minimum would knowingly strand dust and defeat an EXACT_INPUT quote.
198
+ * Resolves the hash of the transaction that delivered the funds to the
199
+ * recipient.
223
200
  *
224
- * Relay execute submissions return `FALLBACK_HASH` instead of a real source
225
- * hash, leaving nothing to read; only then is the quote's minimum output used
226
- * as the last available source.
201
+ * Cross-chain relays surface the target-chain hash from polling. Same-chain
202
+ * relays skip polling, but the submitted source transaction itself moved the
203
+ * funds, so its hash is used instead. Relay execute submissions return
204
+ * `FALLBACK_HASH` rather than a real hash, leaving nothing to read.
227
205
  *
228
206
  * @param options - Resolution options.
229
207
  * @param options.completion - Outcome of `waitForRelayCompletion`.
230
- * @param options.messenger - Controller messenger.
231
208
  * @param options.quote - The Relay quote that was submitted.
232
209
  * @param options.submittedSourceHash - Hash of the submitted source
233
- * transaction, used when polling was skipped on same-chain flows.
234
- * @returns The raw (atomic) settled amount as a decimal string.
210
+ * transaction.
211
+ * @returns The settlement hash, or `undefined` when none is available.
235
212
  */
236
- async function resolveSettledAmount({ completion, messenger, quote, submittedSourceHash, }) {
237
- const recipient = (quote.request.recipient ?? quote.request.from);
238
- const isSameChain = quote.request.sourceChainId === quote.request.targetChainId;
239
- const hasPolledTargetHash = Boolean(completion.targetHash && completion.targetHash !== FALLBACK_HASH);
240
- let settlementHash;
241
- if (hasPolledTargetHash) {
242
- settlementHash = completion.targetHash;
243
- }
244
- else if (isSameChain && submittedSourceHash !== FALLBACK_HASH) {
245
- settlementHash = submittedSourceHash;
246
- }
247
- if (recipient && settlementHash) {
248
- const { amountRaw: onChainAmount } = await getTransferredAmountFromTxHash({
249
- messenger,
250
- txHash: settlementHash,
251
- chainId: quote.request.targetChainId,
252
- tokenAddress: quote.request.targetTokenAddress,
253
- walletAddress: recipient,
254
- });
255
- if (!onChainAmount) {
256
- throw new Error('Cannot resolve settled amount from on-chain transaction');
257
- }
258
- log('Resolved settled amount from on-chain transaction', {
259
- settlementHash,
260
- onChainAmount,
261
- });
262
- return onChainAmount;
213
+ function getSettlementHash({ completion, quote, submittedSourceHash, }) {
214
+ if (completion.targetHash && completion.targetHash !== FALLBACK_HASH) {
215
+ return completion.targetHash;
263
216
  }
264
- const fallback = quote.original.details.currencyOut.minimumAmount;
265
- if (!fallback) {
266
- throw new Error('Cannot resolve post-completion amount');
217
+ const isSameChain = quote.request.sourceChainId === quote.request.targetChainId;
218
+ if (isSameChain && submittedSourceHash !== FALLBACK_HASH) {
219
+ return submittedSourceHash;
267
220
  }
268
- log('Resolved settled amount from quote minimum output', {
269
- fallback,
270
- targetHash: completion.targetHash,
271
- });
272
- return fallback;
221
+ return undefined;
273
222
  }
274
223
  function setRelaySourceHash(transaction, messenger, sourceHash) {
275
224
  updateTransaction({