@metamask-previews/transaction-pay-controller 28.0.2-preview-98c551e → 28.0.2-preview-e81860e6b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Changed
11
11
 
12
+ - Subsidized (fixed-spread) max direct Money Account Relay deposits now use `EXACT_OUTPUT` quoting with vault calls embedded atomically in the Relay quote. ([#10224](https://github.com/MetaMask/core/pull/10224))
13
+ - A new `atomic-promotion-failed` quote error reason is added; failed atomic promotions are terminal and will block rather than silently fall back.
14
+ - Non-subsidized max behavior is unchanged.
12
15
  - Bump `@metamask/utils` from `^11.12.0` to `^12.0.0` ([#10192](https://github.com/MetaMask/core/pull/10192))
13
16
 
14
17
  ## [28.0.2]
@@ -1 +1 @@
1
- {"version":3,"file":"relay-quotes.d.ts","sourceRoot":"","sources":["../../../src/strategy/relay/relay-quotes.ts"],"names":[],"mappings":"AA2BA,OAAO,KAAK,EAGV,2BAA2B,EAG3B,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAkCxB,OAAO,KAAK,EACV,UAAU,EAIX,MAAM,YAAY,CAAC;AAuBpB;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,mBAAmB,CAAC,UAAU,CAAC,EAAE,CAAC,CAkD5C"}
1
+ {"version":3,"file":"relay-quotes.d.ts","sourceRoot":"","sources":["../../../src/strategy/relay/relay-quotes.ts"],"names":[],"mappings":"AA2BA,OAAO,KAAK,EAGV,2BAA2B,EAG3B,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAqCxB,OAAO,KAAK,EACV,UAAU,EAIX,MAAM,YAAY,CAAC;AAuBpB;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,mBAAmB,CAAC,UAAU,CAAC,EAAE,CAAC,CAyD5C"}
@@ -13,11 +13,14 @@ import { getGasStationCostInSourceTokenRaw, getGasStationEligibility, } from '..
13
13
  import { calculateGasCost } from '../../utils/gas.js';
14
14
  import { estimateQuoteGasLimits } from '../../utils/quote-gas.js';
15
15
  import { getNativeToken, getTokenBalance, getTokenFiatRate, normalizeTokenAddress, TokenAddressTarget, } from '../../utils/token.js';
16
+ import { QuoteError } from '../../utils/validation.js';
17
+ import { isMoneyAccountDepositTransaction } from '../fiat/utils.js';
16
18
  import { TOKEN_TRANSFER_FOUR_BYTE } from './constants.js';
17
19
  import { applyHyperliquidActivationFee } from './hyperliquid-activation.js';
18
20
  import { applyPolymarketDepositWalletOverrides, getPredictWithdrawSafeAddress, isPredictWithdraw, } from './polymarket/withdraw.js';
19
21
  import { fetchRelayQuote } from './relay-api.js';
20
22
  import { getRelayMaxGasStationQuote } from './relay-max-gas-station.js';
23
+ import { isSubsidizedRelayQuote } from './relay-submit-execute.js';
21
24
  import { validateRelayQuotes } from './relay-validation.js';
22
25
  const log = createModuleLogger(projectLogger, 'relay-strategy');
23
26
  // Buffer applied to the gas cost when reserving native tokens for gas in
@@ -35,6 +38,7 @@ const ZERO_AMOUNT = { fiat: '0', human: '0', raw: '0', usd: '0' };
35
38
  export async function getRelayQuotes(request) {
36
39
  const { requests } = request;
37
40
  log('Fetching quotes', requests);
41
+ let quotes = [];
38
42
  try {
39
43
  const normalizedRequests = await Promise.all(requests
40
44
  .filter((singleRequest) => {
@@ -47,7 +51,7 @@ export async function getRelayQuotes(request) {
47
51
  .map((singleRequest) => normalizeRequest(singleRequest, request.transaction))
48
52
  .map((normalizedRequest) => applyHyperliquidActivationFee(normalizedRequest, request.messenger, request.transaction, request.signal)));
49
53
  log('Normalized requests', normalizedRequests);
50
- const quotes = await Promise.all(normalizedRequests.map((singleRequest) => getQuoteWithMaxAmountHandling(singleRequest, request)));
54
+ quotes = await Promise.all(normalizedRequests.map((singleRequest) => getQuoteWithMaxAmountHandling(singleRequest, request)));
51
55
  await validateRelayQuotes({
52
56
  messenger: request.messenger,
53
57
  quotes,
@@ -58,6 +62,9 @@ export async function getRelayQuotes(request) {
58
62
  }
59
63
  catch (error) {
60
64
  log('Error fetching quotes', { error });
65
+ if (quotes.some(isPromotedSubsidizedMaxMoneyAccountQuote)) {
66
+ throwAtomicPromotionFailed(error);
67
+ }
61
68
  throw error;
62
69
  }
63
70
  }
@@ -66,7 +73,171 @@ async function getQuoteWithMaxAmountHandling(request, fullRequest) {
66
73
  if (!isMaxAmount) {
67
74
  return getQuoteWithPostQuoteGasHandling(request, fullRequest);
68
75
  }
69
- return getRelayMaxGasStationQuote(request, fullRequest, getSingleQuote);
76
+ const discoveryQuote = await getRelayMaxGasStationQuote(request, fullRequest, getSingleQuote);
77
+ return maybePromoteSubsidizedMaxMoneyAccountQuote({
78
+ discoveryQuote,
79
+ fullRequest,
80
+ request,
81
+ });
82
+ }
83
+ async function maybePromoteSubsidizedMaxMoneyAccountQuote({ discoveryQuote, fullRequest, request, }) {
84
+ if (!shouldAttemptAtomicPromotion(request, fullRequest.transaction, discoveryQuote)) {
85
+ return discoveryQuote;
86
+ }
87
+ try {
88
+ const targetAmount = validatePositiveIntegerString(discoveryQuote.original.details.currencyOut.amount);
89
+ const transactionClone = cloneTransactionForPromotion(fullRequest.transaction);
90
+ const promotionTransaction = await applyAmountDataUpdates({
91
+ amount: targetAmount,
92
+ messenger: fullRequest.messenger,
93
+ transaction: transactionClone,
94
+ });
95
+ const promotedQuote = await getSingleQuote({
96
+ ...request,
97
+ atomic: true,
98
+ isMaxAmount: false,
99
+ targetAmountMinimum: targetAmount,
100
+ }, {
101
+ ...fullRequest,
102
+ transaction: promotionTransaction,
103
+ });
104
+ if (request.sourceTokenAddress.toLowerCase() ===
105
+ getNativeToken(request.sourceChainId).toLowerCase() &&
106
+ new BigNumber(promotedQuote.fees.sourceNetwork.max.raw)
107
+ .plus(new BigNumber(promotedQuote.sourceAmount.raw))
108
+ .isGreaterThan(new BigNumber(request.sourceTokenAmount))) {
109
+ throw new Error('Promoted quote exceeds max spend budget');
110
+ }
111
+ assertAtomicPromotionIsValid({
112
+ discoveryQuote,
113
+ promotedQuote,
114
+ request,
115
+ targetAmount,
116
+ });
117
+ return {
118
+ ...promotedQuote,
119
+ request: {
120
+ ...promotedQuote.request,
121
+ atomic: true,
122
+ isMaxAmount: true,
123
+ },
124
+ };
125
+ }
126
+ catch (error) {
127
+ return throwAtomicPromotionFailed(error);
128
+ }
129
+ }
130
+ function throwAtomicPromotionFailed(error) {
131
+ throw new QuoteError({
132
+ detail: [error instanceof Error ? error.message : String(error)],
133
+ message: 'Atomic quote promotion failed',
134
+ reason: 'atomic-promotion-failed',
135
+ });
136
+ }
137
+ function isPromotedSubsidizedMaxMoneyAccountQuote(quote) {
138
+ return (quote.request.isMaxAmount === true &&
139
+ quote.request.atomic === true &&
140
+ isSubsidizedRelayQuote(quote.original));
141
+ }
142
+ function shouldAttemptAtomicPromotion(request, transaction, discoveryQuote) {
143
+ return (isMoneyAccountDepositTransaction(transaction) &&
144
+ request.isMaxAmount === true &&
145
+ request.isPostQuote !== true &&
146
+ request.atomic !== true &&
147
+ isSubsidizedRelayQuote(discoveryQuote.original));
148
+ }
149
+ function validatePositiveIntegerString(value) {
150
+ const amount = new BigNumber(value);
151
+ if (!amount.isFinite() || !amount.isInteger() || !amount.isGreaterThan(0)) {
152
+ throw new Error(`Invalid target amount: ${value}`);
153
+ }
154
+ return amount.toFixed(0);
155
+ }
156
+ function cloneTransactionForPromotion(transaction) {
157
+ return {
158
+ ...transaction,
159
+ nestedTransactions: transaction.nestedTransactions?.map((nestedTransaction) => ({
160
+ ...nestedTransaction,
161
+ })),
162
+ requiredAssets: transaction.requiredAssets?.map((requiredAsset) => ({
163
+ ...requiredAsset,
164
+ })),
165
+ };
166
+ }
167
+ async function applyAmountDataUpdates({ amount, messenger, transaction, }) {
168
+ const { updates } = await messenger.call('TransactionPayController:getAmountData', {
169
+ amount,
170
+ transaction,
171
+ });
172
+ if (!updates.length) {
173
+ throw new Error('getAmountData returned no updates for atomic promotion');
174
+ }
175
+ const nestedTransactions = transaction.nestedTransactions?.map((nestedTransaction) => ({
176
+ ...nestedTransaction,
177
+ }));
178
+ if (!nestedTransactions?.length) {
179
+ throw new Error('Missing nested transactions for atomic promotion');
180
+ }
181
+ for (const { nestedTransactionIndex, data } of updates) {
182
+ if (!nestedTransactions[nestedTransactionIndex]) {
183
+ throw new Error('getAmountData returned an unusable nested transaction update');
184
+ }
185
+ nestedTransactions[nestedTransactionIndex].data = data;
186
+ }
187
+ const requiredAssets = transaction.requiredAssets?.map((requiredAsset) => ({
188
+ ...requiredAsset,
189
+ }));
190
+ if (!requiredAssets?.[0]) {
191
+ throw new Error('Missing required assets for atomic promotion');
192
+ }
193
+ requiredAssets[0].amount = toHex(BigInt(amount));
194
+ return {
195
+ ...transaction,
196
+ nestedTransactions,
197
+ requiredAssets,
198
+ };
199
+ }
200
+ function assertAtomicPromotionIsValid({ discoveryQuote, promotedQuote, request, targetAmount, }) {
201
+ if (!isSubsidizedRelayQuote(promotedQuote.original)) {
202
+ throw new Error('Promoted quote lost subsidy');
203
+ }
204
+ /* istanbul ignore next: atomic re-quotes always request exact-output; defensive guard. */
205
+ if (promotedQuote.original.request.tradeType !== 'EXACT_OUTPUT') {
206
+ throw new Error('Promoted quote did not return EXACT_OUTPUT');
207
+ }
208
+ /* istanbul ignore next: atomic re-quotes always embed funding and delegation calls; defensive guard. */
209
+ if (!promotedQuote.original.request.txs?.length) {
210
+ throw new Error('Promoted quote is missing embedded calls');
211
+ }
212
+ const sourceCost = getPromotedSourceCost({ promotedQuote, request });
213
+ const budget = new BigNumber(request.sourceTokenAmount);
214
+ if (sourceCost.isGreaterThan(budget)) {
215
+ throw new Error('Promoted quote exceeds max spend budget');
216
+ }
217
+ /* istanbul ignore next: re-quote hardcodes isMaxAmount false; defensive guard. */
218
+ if (promotedQuote.request.isMaxAmount !== false) {
219
+ throw new Error('Promoted quote request isMaxAmount was not cleared before restore');
220
+ }
221
+ /* istanbul ignore next: re-quote hardcodes atomic true; defensive guard. */
222
+ if (promotedQuote.request.atomic !== true) {
223
+ throw new Error('Promoted quote request atomic flag was not set');
224
+ }
225
+ /* istanbul ignore next: re-quote hardcodes the discovery target; defensive guard. */
226
+ if (promotedQuote.request.targetAmountMinimum !== targetAmount) {
227
+ throw new Error('Promoted quote target amount minimum was not preserved');
228
+ }
229
+ if (discoveryQuote.original.details.currencyOut.amount !== targetAmount) {
230
+ throw new Error('Discovery quote target amount changed before promotion');
231
+ }
232
+ }
233
+ function getPromotedSourceCost({ promotedQuote, request, }) {
234
+ const sourceAmount = new BigNumber(promotedQuote.sourceAmount.raw);
235
+ const sourceTokenIsNative = request.sourceTokenAddress.toLowerCase() ===
236
+ getNativeToken(request.sourceChainId).toLowerCase();
237
+ if (!sourceTokenIsNative && !promotedQuote.fees.isSourceGasFeeToken) {
238
+ return sourceAmount;
239
+ }
240
+ return sourceAmount.plus(new BigNumber(promotedQuote.fees.sourceNetwork.max.raw));
70
241
  }
71
242
  /**
72
243
  * For post-quote flows, fetch an initial quote to compute gas cost in source
@@ -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;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAMnE,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,eAA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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 { TransactionType } from '@metamask/transaction-controller';\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 isEIP7702Chain,\n isRelayExecuteEnabled,\n} from '../../utils/feature-flags.js';\nimport {\n getGasStationCostInSourceTokenRaw,\n getGasStationEligibility,\n} from '../../utils/gas-station.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 getTokenBalance,\n getTokenFiatRate,\n normalizeTokenAddress,\n TokenAddressTarget,\n} from '../../utils/token.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 { getRelayMaxGasStationQuote } from './relay-max-gas-station.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 await validateRelayQuotes({\n messenger: request.messenger,\n quotes,\n signal: request.signal,\n transaction: request.transaction,\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 getRelayMaxGasStationQuote(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 hasTransactions = Boolean(body.txs?.length);\n const requiresExactOutput =\n hasTransactions ||\n transaction.type === TransactionType.perpsDepositAndOrder ||\n transaction.type === TransactionType.predictDepositAndOrder;\n const finalBody: RelayQuoteRequest = {\n ...body,\n amount:\n body.amount ??\n (requiresExactOutput ? targetAmountMinimum : sourceTokenAmount),\n tradeType: requiresExactOutput ? 'EXACT_OUTPUT' : 'EXACT_INPUT',\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 if (isMaxAmount) {\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 * When the execute flow is active (indicated by `quote.metamask.isExecute`),\n * network fees are zeroed because the relayer covers them.\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 if (quote.metamask?.isExecute) {\n log('Zeroing network fees for execute flow');\n\n return {\n estimate: ZERO_AMOUNT,\n max: ZERO_AMOUNT,\n gasLimits: [],\n is7702: false,\n };\n }\n\n // HyperLiquid withdrawals are gasless -- the \"deposit\" step is an HL\n // sendAsset (off-chain signature), not an on-chain transaction.\n if (request.isHyperliquidSource) {\n log('Zeroing network fees for HyperLiquid withdrawal (gasless)');\n\n return {\n estimate: ZERO_AMOUNT,\n max: ZERO_AMOUNT,\n gasLimits: [],\n is7702: false,\n };\n }\n\n if (\n accountSupports7702 &&\n transaction.isGasFeeSponsored &&\n request.sourceChainId === transaction.chainId &&\n request.targetChainId === transaction.chainId\n ) {\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 nativeBalance = getTokenBalance(\n messenger,\n from,\n sourceChainId,\n getNativeToken(sourceChainId),\n );\n\n const result = { estimate, max, gasLimits, is7702 };\n\n if (new BigNumber(nativeBalance).isGreaterThanOrEqualTo(max.raw)) {\n return result;\n }\n\n if (accountSupports7702 === false) {\n log('Skipping gas station as account does not support EIP-7702', {\n from,\n });\n\n return result;\n }\n\n const gasStationEligibility = getGasStationEligibility(\n messenger,\n sourceChainId,\n );\n\n if (gasStationEligibility.isDisabledChain) {\n log('Skipping gas station as disabled chain', {\n sourceChainId,\n });\n\n return result;\n }\n\n if (!gasStationEligibility.chainSupportsGasStation) {\n log('Skipping gas station as chain does not support EIP-7702', {\n sourceChainId,\n });\n\n return result;\n }\n\n log('Checking gas fee tokens as insufficient native balance', {\n nativeBalance,\n max: max.raw,\n });\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 if (isPredictWithdrawFlow && request.refundTo) {\n log('Using proxy address for predict withdraw gas station simulation', {\n proxyAddress: request.refundTo,\n sourceTokenAddress,\n totalGasEstimate,\n });\n\n const gasFeeTokenCost = await getGasStationCostInSourceTokenRaw({\n firstStepData: {\n data,\n to,\n value,\n },\n messenger,\n request: {\n from: request.refundTo,\n sourceChainId,\n sourceTokenAddress,\n },\n totalGasEstimate,\n totalItemCount: relayParams.length + 1,\n });\n\n if (gasFeeTokenCost) {\n log('Using predict withdraw gas fee token for source network', {\n gasFeeTokenCost,\n });\n\n return {\n isGasFeeToken: true,\n estimate: gasFeeTokenCost,\n max: gasFeeTokenCost,\n gasLimits,\n is7702,\n };\n }\n\n return result;\n }\n\n const gasFeeTokenCost = await getGasStationCostInSourceTokenRaw({\n firstStepData: {\n data,\n to,\n value,\n },\n messenger,\n request: {\n from,\n sourceChainId,\n sourceTokenAddress,\n },\n totalGasEstimate,\n totalItemCount: Math.max(relayParams.length, gasLimits.length),\n });\n\n if (!gasFeeTokenCost) {\n return result;\n }\n\n log('Using gas fee token for source network', {\n gasFeeTokenCost,\n });\n\n return {\n isGasFeeToken: true,\n estimate: gasFeeTokenCost,\n max: gasFeeTokenCost,\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' as Hex),\n from: txParams.from as Hex,\n gas: gas ? String(gas) : undefined,\n maxFeePerGas: '0',\n maxPriorityFeePerGas: '0',\n to,\n value: (txParams.value as string) ?? '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":[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pB,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 { TransactionType } from '@metamask/transaction-controller';\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 isEIP7702Chain,\n isRelayExecuteEnabled,\n} from '../../utils/feature-flags.js';\nimport {\n getGasStationCostInSourceTokenRaw,\n getGasStationEligibility,\n} from '../../utils/gas-station.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 getTokenBalance,\n getTokenFiatRate,\n normalizeTokenAddress,\n TokenAddressTarget,\n} from '../../utils/token.js';\nimport { QuoteError } from '../../utils/validation.js';\nimport { isMoneyAccountDepositTransaction } from '../fiat/utils.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 { getRelayMaxGasStationQuote } from './relay-max-gas-station.js';\nimport { isSubsidizedRelayQuote } from './relay-submit-execute.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 let quotes: TransactionPayQuote<RelayQuote>[] = [];\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 quotes = await Promise.all(\n normalizedRequests.map((singleRequest) =>\n getQuoteWithMaxAmountHandling(singleRequest, request),\n ),\n );\n\n await validateRelayQuotes({\n messenger: request.messenger,\n quotes,\n signal: request.signal,\n transaction: request.transaction,\n });\n\n return quotes;\n } catch (error) {\n log('Error fetching quotes', { error });\n\n if (quotes.some(isPromotedSubsidizedMaxMoneyAccountQuote)) {\n throwAtomicPromotionFailed(error);\n }\n\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 const discoveryQuote = await getRelayMaxGasStationQuote(\n request,\n fullRequest,\n getSingleQuote,\n );\n\n return maybePromoteSubsidizedMaxMoneyAccountQuote({\n discoveryQuote,\n fullRequest,\n request,\n });\n}\n\nasync function maybePromoteSubsidizedMaxMoneyAccountQuote({\n discoveryQuote,\n fullRequest,\n request,\n}: {\n discoveryQuote: TransactionPayQuote<RelayQuote>;\n fullRequest: PayStrategyGetQuotesRequest;\n request: QuoteRequest;\n}): Promise<TransactionPayQuote<RelayQuote>> {\n if (\n !shouldAttemptAtomicPromotion(\n request,\n fullRequest.transaction,\n discoveryQuote,\n )\n ) {\n return discoveryQuote;\n }\n\n try {\n const targetAmount = validatePositiveIntegerString(\n discoveryQuote.original.details.currencyOut.amount,\n );\n\n const transactionClone = cloneTransactionForPromotion(\n fullRequest.transaction,\n );\n const promotionTransaction = await applyAmountDataUpdates({\n amount: targetAmount,\n messenger: fullRequest.messenger,\n transaction: transactionClone,\n });\n\n const promotedQuote = await getSingleQuote(\n {\n ...request,\n atomic: true,\n isMaxAmount: false,\n targetAmountMinimum: targetAmount,\n },\n {\n ...fullRequest,\n transaction: promotionTransaction,\n },\n );\n\n if (\n request.sourceTokenAddress.toLowerCase() ===\n getNativeToken(request.sourceChainId).toLowerCase() &&\n new BigNumber(promotedQuote.fees.sourceNetwork.max.raw)\n .plus(new BigNumber(promotedQuote.sourceAmount.raw))\n .isGreaterThan(new BigNumber(request.sourceTokenAmount))\n ) {\n throw new Error('Promoted quote exceeds max spend budget');\n }\n\n assertAtomicPromotionIsValid({\n discoveryQuote,\n promotedQuote,\n request,\n targetAmount,\n });\n\n return {\n ...promotedQuote,\n request: {\n ...promotedQuote.request,\n atomic: true,\n isMaxAmount: true,\n },\n };\n } catch (error) {\n return throwAtomicPromotionFailed(error);\n }\n}\n\nfunction throwAtomicPromotionFailed(error: unknown): never {\n throw new QuoteError({\n detail: [error instanceof Error ? error.message : String(error)],\n message: 'Atomic quote promotion failed',\n reason: 'atomic-promotion-failed',\n });\n}\n\nfunction isPromotedSubsidizedMaxMoneyAccountQuote(\n quote: TransactionPayQuote<RelayQuote>,\n): boolean {\n return (\n quote.request.isMaxAmount === true &&\n quote.request.atomic === true &&\n isSubsidizedRelayQuote(quote.original)\n );\n}\n\nfunction shouldAttemptAtomicPromotion(\n request: QuoteRequest,\n transaction: TransactionMeta,\n discoveryQuote: TransactionPayQuote<RelayQuote>,\n): boolean {\n return (\n isMoneyAccountDepositTransaction(transaction) &&\n request.isMaxAmount === true &&\n request.isPostQuote !== true &&\n request.atomic !== true &&\n isSubsidizedRelayQuote(discoveryQuote.original)\n );\n}\n\nfunction validatePositiveIntegerString(value: string): string {\n const amount = new BigNumber(value);\n\n if (!amount.isFinite() || !amount.isInteger() || !amount.isGreaterThan(0)) {\n throw new Error(`Invalid target amount: ${value}`);\n }\n\n return amount.toFixed(0);\n}\n\nfunction cloneTransactionForPromotion(\n transaction: TransactionMeta,\n): TransactionMeta {\n return {\n ...transaction,\n nestedTransactions: transaction.nestedTransactions?.map(\n (nestedTransaction) => ({\n ...nestedTransaction,\n }),\n ),\n requiredAssets: transaction.requiredAssets?.map((requiredAsset) => ({\n ...requiredAsset,\n })),\n };\n}\n\nasync function applyAmountDataUpdates({\n amount,\n messenger,\n transaction,\n}: {\n amount: string;\n messenger: TransactionPayControllerMessenger;\n transaction: TransactionMeta;\n}): Promise<TransactionMeta> {\n const { updates } = await messenger.call(\n 'TransactionPayController:getAmountData',\n {\n amount,\n transaction,\n },\n );\n\n if (!updates.length) {\n throw new Error('getAmountData returned no updates for atomic promotion');\n }\n\n const nestedTransactions = transaction.nestedTransactions?.map(\n (nestedTransaction) => ({\n ...nestedTransaction,\n }),\n );\n\n if (!nestedTransactions?.length) {\n throw new Error('Missing nested transactions for atomic promotion');\n }\n\n for (const { nestedTransactionIndex, data } of updates) {\n if (!nestedTransactions[nestedTransactionIndex]) {\n throw new Error(\n 'getAmountData returned an unusable nested transaction update',\n );\n }\n\n nestedTransactions[nestedTransactionIndex].data = data;\n }\n\n const requiredAssets = transaction.requiredAssets?.map((requiredAsset) => ({\n ...requiredAsset,\n }));\n\n if (!requiredAssets?.[0]) {\n throw new Error('Missing required assets for atomic promotion');\n }\n\n requiredAssets[0].amount = toHex(BigInt(amount));\n\n return {\n ...transaction,\n nestedTransactions,\n requiredAssets,\n };\n}\n\nfunction assertAtomicPromotionIsValid({\n discoveryQuote,\n promotedQuote,\n request,\n targetAmount,\n}: {\n discoveryQuote: TransactionPayQuote<RelayQuote>;\n promotedQuote: TransactionPayQuote<RelayQuote>;\n request: QuoteRequest;\n targetAmount: string;\n}): void {\n if (!isSubsidizedRelayQuote(promotedQuote.original)) {\n throw new Error('Promoted quote lost subsidy');\n }\n\n /* istanbul ignore next: atomic re-quotes always request exact-output; defensive guard. */\n if (promotedQuote.original.request.tradeType !== 'EXACT_OUTPUT') {\n throw new Error('Promoted quote did not return EXACT_OUTPUT');\n }\n\n /* istanbul ignore next: atomic re-quotes always embed funding and delegation calls; defensive guard. */\n if (!promotedQuote.original.request.txs?.length) {\n throw new Error('Promoted quote is missing embedded calls');\n }\n\n const sourceCost = getPromotedSourceCost({ promotedQuote, request });\n\n const budget = new BigNumber(request.sourceTokenAmount);\n\n if (sourceCost.isGreaterThan(budget)) {\n throw new Error('Promoted quote exceeds max spend budget');\n }\n\n /* istanbul ignore next: re-quote hardcodes isMaxAmount false; defensive guard. */\n if (promotedQuote.request.isMaxAmount !== false) {\n throw new Error(\n 'Promoted quote request isMaxAmount was not cleared before restore',\n );\n }\n\n /* istanbul ignore next: re-quote hardcodes atomic true; defensive guard. */\n if (promotedQuote.request.atomic !== true) {\n throw new Error('Promoted quote request atomic flag was not set');\n }\n\n /* istanbul ignore next: re-quote hardcodes the discovery target; defensive guard. */\n if (promotedQuote.request.targetAmountMinimum !== targetAmount) {\n throw new Error('Promoted quote target amount minimum was not preserved');\n }\n\n if (discoveryQuote.original.details.currencyOut.amount !== targetAmount) {\n throw new Error('Discovery quote target amount changed before promotion');\n }\n}\n\nfunction getPromotedSourceCost({\n promotedQuote,\n request,\n}: {\n promotedQuote: TransactionPayQuote<RelayQuote>;\n request: QuoteRequest;\n}): BigNumber {\n const sourceAmount = new BigNumber(promotedQuote.sourceAmount.raw);\n const sourceTokenIsNative =\n request.sourceTokenAddress.toLowerCase() ===\n getNativeToken(request.sourceChainId).toLowerCase();\n\n if (!sourceTokenIsNative && !promotedQuote.fees.isSourceGasFeeToken) {\n return sourceAmount;\n }\n\n return sourceAmount.plus(\n new BigNumber(promotedQuote.fees.sourceNetwork.max.raw),\n );\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 hasTransactions = Boolean(body.txs?.length);\n const requiresExactOutput =\n hasTransactions ||\n transaction.type === TransactionType.perpsDepositAndOrder ||\n transaction.type === TransactionType.predictDepositAndOrder;\n const finalBody: RelayQuoteRequest = {\n ...body,\n amount:\n body.amount ??\n (requiresExactOutput ? targetAmountMinimum : sourceTokenAmount),\n tradeType: requiresExactOutput ? 'EXACT_OUTPUT' : 'EXACT_INPUT',\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 if (isMaxAmount) {\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 * When the execute flow is active (indicated by `quote.metamask.isExecute`),\n * network fees are zeroed because the relayer covers them.\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 if (quote.metamask?.isExecute) {\n log('Zeroing network fees for execute flow');\n\n return {\n estimate: ZERO_AMOUNT,\n max: ZERO_AMOUNT,\n gasLimits: [],\n is7702: false,\n };\n }\n\n // HyperLiquid withdrawals are gasless -- the \"deposit\" step is an HL\n // sendAsset (off-chain signature), not an on-chain transaction.\n if (request.isHyperliquidSource) {\n log('Zeroing network fees for HyperLiquid withdrawal (gasless)');\n\n return {\n estimate: ZERO_AMOUNT,\n max: ZERO_AMOUNT,\n gasLimits: [],\n is7702: false,\n };\n }\n\n if (\n accountSupports7702 &&\n transaction.isGasFeeSponsored &&\n request.sourceChainId === transaction.chainId &&\n request.targetChainId === transaction.chainId\n ) {\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 nativeBalance = getTokenBalance(\n messenger,\n from,\n sourceChainId,\n getNativeToken(sourceChainId),\n );\n\n const result = { estimate, max, gasLimits, is7702 };\n\n if (new BigNumber(nativeBalance).isGreaterThanOrEqualTo(max.raw)) {\n return result;\n }\n\n if (accountSupports7702 === false) {\n log('Skipping gas station as account does not support EIP-7702', {\n from,\n });\n\n return result;\n }\n\n const gasStationEligibility = getGasStationEligibility(\n messenger,\n sourceChainId,\n );\n\n if (gasStationEligibility.isDisabledChain) {\n log('Skipping gas station as disabled chain', {\n sourceChainId,\n });\n\n return result;\n }\n\n if (!gasStationEligibility.chainSupportsGasStation) {\n log('Skipping gas station as chain does not support EIP-7702', {\n sourceChainId,\n });\n\n return result;\n }\n\n log('Checking gas fee tokens as insufficient native balance', {\n nativeBalance,\n max: max.raw,\n });\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 if (isPredictWithdrawFlow && request.refundTo) {\n log('Using proxy address for predict withdraw gas station simulation', {\n proxyAddress: request.refundTo,\n sourceTokenAddress,\n totalGasEstimate,\n });\n\n const gasFeeTokenCost = await getGasStationCostInSourceTokenRaw({\n firstStepData: {\n data,\n to,\n value,\n },\n messenger,\n request: {\n from: request.refundTo,\n sourceChainId,\n sourceTokenAddress,\n },\n totalGasEstimate,\n totalItemCount: relayParams.length + 1,\n });\n\n if (gasFeeTokenCost) {\n log('Using predict withdraw gas fee token for source network', {\n gasFeeTokenCost,\n });\n\n return {\n isGasFeeToken: true,\n estimate: gasFeeTokenCost,\n max: gasFeeTokenCost,\n gasLimits,\n is7702,\n };\n }\n\n return result;\n }\n\n const gasFeeTokenCost = await getGasStationCostInSourceTokenRaw({\n firstStepData: {\n data,\n to,\n value,\n },\n messenger,\n request: {\n from,\n sourceChainId,\n sourceTokenAddress,\n },\n totalGasEstimate,\n totalItemCount: Math.max(relayParams.length, gasLimits.length),\n });\n\n if (!gasFeeTokenCost) {\n return result;\n }\n\n log('Using gas fee token for source network', {\n gasFeeTokenCost,\n });\n\n return {\n isGasFeeToken: true,\n estimate: gasFeeTokenCost,\n max: gasFeeTokenCost,\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' as Hex),\n from: txParams.from as Hex,\n gas: gas ? String(gas) : undefined,\n maxFeePerGas: '0',\n maxPriorityFeePerGas: '0',\n to,\n value: (txParams.value as string) ?? '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"]}
@@ -4,6 +4,7 @@ import type { Hex } from '@metamask/utils';
4
4
  import type { TransactionPayControllerMessenger, TransactionPayQuote } from '../../types.js';
5
5
  import type { RelayExecuteRequest, RelayQuote } from './types.js';
6
6
  export declare function submitViaRelayExecute(quote: TransactionPayQuote<RelayQuote>, transaction: TransactionMeta, messenger: TransactionPayControllerMessenger, allParams: TransactionParams[]): Promise<Hex>;
7
+ export declare function isSubsidizedRelayQuote(quote: RelayQuote): boolean;
7
8
  export declare function getRelayExecuteRequest({ allParams, isSubsidized, messenger, quote, regenerateBatchParams, requestId, transaction, }: {
8
9
  allParams: TransactionParams[];
9
10
  isSubsidized?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"relay-submit-execute.d.ts","sourceRoot":"","sources":["../../../src/strategy/relay/relay-submit-execute.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,KAAK,EAEV,eAAe,EAChB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAK3C,OAAO,KAAK,EACV,iCAAiC,EACjC,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAKxB,OAAO,KAAK,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAKlE,wBAAsB,qBAAqB,CACzC,KAAK,EAAE,mBAAmB,CAAC,UAAU,CAAC,EACtC,WAAW,EAAE,eAAe,EAC5B,SAAS,EAAE,iCAAiC,EAC5C,SAAS,EAAE,iBAAiB,EAAE,GAC7B,OAAO,CAAC,GAAG,CAAC,CAWd;AAqHD,wBAAsB,sBAAsB,CAAC,EAC3C,SAAS,EACT,YAAoB,EACpB,SAAS,EACT,KAAK,EACL,qBAA6B,EAC7B,SAAS,EACT,WAAW,GACZ,EAAE;IACD,SAAS,EAAE,iBAAiB,EAAE,CAAC;IA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C,UAAU,CAAC,CAAC;IACvC,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,eAAe,CAAC;CAC9B,GAAG,OAAO,CAAC,IAAI,CAAC,mBAAmB,EAAE,UAAU,CAAC,CAAC,CA2DjD"}
@@ -38,7 +38,7 @@ async function submitViaRelayExecuteInternal(quote, transaction, messenger, allP
38
38
  replaceFirstStepRequestId(quote.original, result.requestId);
39
39
  return FALLBACK_HASH;
40
40
  }
41
- function isSubsidizedRelayQuote(quote) {
41
+ export function isSubsidizedRelayQuote(quote) {
42
42
  return Number(quote.fees?.subsidized?.amountUsd ?? '0') > 0;
43
43
  }
44
44
  function stripRelayExecuteMarker(requestId) {
@@ -1 +1 @@
1
- {"version":3,"file":"relay-submit-execute.js","sourceRoot":"","sources":["../../../src/strategy/relay/relay-submit-execute.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,kCAAkC,CAAC;AAOnF,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAKhD,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAGpD,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC;AAChE,MAAM,0BAA0B,GAAG,WAAW,CAAC;AAE/C,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,KAAsC,EACtC,WAA4B,EAC5B,SAA4C,EAC5C,SAA8B;IAE9B,IAAI,CAAC;QACH,OAAO,MAAM,6BAA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,IAAI,EAAE,CAAC;IAEjD,IAAI,qBAAqB,EAAE,CAAC;QAC1B,+EAA+E;QAC/E,gFAAgF;QAChF,mFAAmF;QACnF,iFAAiF;QACjF,iEAAiE;QACjE,MAAM,WAAW,GACf,kBAAkB,CAAC,MAAM,KAAK,CAAC;YAC7B,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;YACvB,CAAC,CAAC,+BAA+B,CAAC,IAAI,EAAE,kBAAkB,CAAC,CAAC;QAChE,QAAQ,GAAG;YACT,GAAG,QAAQ;YACX,EAAE,EAAE,WAAW,CAAC,EAAE;YAClB,KAAK,EAAE,WAAW,CAAC,KAAK,IAAI,KAAK;YACjC,IAAI,EAAE,WAAW,CAAC,IAAI;SACvB,CAAC;IACJ,CAAC;IAED,MAAM,oBAAoB,GAAoB;QAC5C,GAAG,WAAW;QACd,OAAO,EAAE,aAAa;QACtB,eAAe;QACf,kBAAkB;QAClB,QAAQ;KACU,CAAC;IAErB,MAAM,UAAU,GAAG,MAAM,SAAS,CAAC,IAAI,CACrC,mDAAmD,EACnD,EAAE,WAAW,EAAE,oBAAoB,EAAE,YAAY,EAAE,CACpD,CAAC;IAEF,GAAG,CAAC,uCAAuC,EAAE,UAAU,CAAC,CAAC;IAEzD,OAAO;QACL,aAAa,EAAE,UAAU;QACzB,IAAI,EAAE;YACJ,OAAO,EAAE,MAAM,CAAC,aAAa,CAAC;YAC9B,EAAE,EAAE,UAAU,CAAC,EAAE;YACjB,IAAI,EAAE,UAAU,CAAC,IAAI;YACrB,KAAK,EAAE,IAAI,SAAS,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE;YAChD,GAAG,oBAAoB,CAAC,UAAU,CAAC,iBAAiB,CAAC;SACtD;QACD,gBAAgB,EAAE;YAChB,aAAa,EAAE,KAAK;SACrB;QACD,SAAS;KACV,CAAC;AACJ,CAAC","sourcesContent":["import { generateEIP7702BatchTransaction } from '@metamask/transaction-controller';\nimport type { TransactionParams } from '@metamask/transaction-controller';\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 { projectLogger } from '../../logger.js';\nimport type {\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types.js';\nimport { prefixError } from '../../utils/error-prefix.js';\nimport { getNetworkClientId } from '../../utils/provider.js';\nimport { FALLBACK_HASH } from './constants.js';\nimport { submitRelayExecute } from './relay-api.js';\nimport type { RelayExecuteRequest, RelayQuote } from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'relay-strategy');\nconst RELAY_EXECUTE_ERROR_PREFIX = 'Execute: ';\n\nexport async function submitViaRelayExecute(\n quote: TransactionPayQuote<RelayQuote>,\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n allParams: TransactionParams[],\n): Promise<Hex> {\n try {\n return await submitViaRelayExecuteInternal(\n quote,\n transaction,\n messenger,\n allParams,\n );\n } catch (error) {\n throw prefixError(error, RELAY_EXECUTE_ERROR_PREFIX);\n }\n}\n\nasync function submitViaRelayExecuteInternal(\n quote: TransactionPayQuote<RelayQuote>,\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n allParams: TransactionParams[],\n): Promise<Hex> {\n const isSubsidized = isSubsidizedRelayQuote(quote.original);\n const requestId = getRelayExecuteRequestId(quote.original);\n const metamask = getRelayExecuteMetamask(quote.original, isSubsidized);\n\n const core = await getRelayExecuteRequest({\n allParams,\n isSubsidized,\n messenger,\n quote,\n regenerateBatchParams: true,\n requestId,\n transaction,\n });\n\n const executeBody: RelayExecuteRequest = { ...core, metamask };\n\n log('Submitting to Relay execute', { executeBody, from: quote.request.from });\n\n const result = await submitRelayExecute(messenger, executeBody);\n\n log('Relay execute response', result);\n\n // Server may return a different requestId (e.g. after JIT quote for subsidized).\n // Replace the original quote requestId so waitForRelayCompletion polls the correct request.\n replaceFirstStepRequestId(quote.original, result.requestId);\n\n return FALLBACK_HASH;\n}\n\nfunction isSubsidizedRelayQuote(quote: RelayQuote): boolean {\n return Number(quote.fees?.subsidized?.amountUsd ?? '0') > 0;\n}\n\nfunction stripRelayExecuteMarker(requestId: string): string {\n return requestId.includes('#mm')\n ? requestId.slice(0, requestId.indexOf('#mm'))\n : requestId;\n}\n\nfunction getRelayExecuteRequestId(quote: RelayQuote): string {\n const requestId = quote.steps?.[0]?.requestId;\n if (!requestId) {\n throw new Error('Missing requestId in quote step');\n }\n return stripRelayExecuteMarker(requestId);\n}\n\nfunction getRelayExecuteMetamask(\n quote: RelayQuote,\n isSubsidized: boolean,\n): {\n isSubsidized: boolean;\n quoteRequest: RelayQuote['request'];\n signature: string;\n} {\n const signature = quote.metamask?.signature;\n if (!signature) {\n throw new Error(\n 'Missing metamask.signature — cannot submit to /relay/execute without the HMAC token',\n );\n }\n return {\n isSubsidized,\n quoteRequest: quote.request,\n signature,\n };\n}\n\nfunction mapAuthorizationList(\n authorizationList: AuthorizationList | undefined,\n): {\n authorizationList?: {\n chainId: number;\n address: Hex;\n nonce: number;\n yParity: number;\n r: Hex;\n s: Hex;\n }[];\n} {\n if (!authorizationList?.length) {\n return {};\n }\n return {\n authorizationList: authorizationList.map((auth) => ({\n chainId: Number(auth.chainId),\n address: auth.address,\n nonce: Number(auth.nonce),\n yParity: Number(auth.yParity),\n r: auth.r as Hex,\n s: auth.s as Hex,\n })),\n };\n}\n\nfunction replaceFirstStepRequestId(quote: RelayQuote, requestId: string): void {\n /* istanbul ignore next: requestId is read from steps[0] earlier, so steps is non-empty here; defensive guard. */\n const steps = quote.steps ?? [];\n /* istanbul ignore if: requestId is read from steps[0] earlier, so steps is non-empty here; defensive guard. */\n if (steps.length === 0) {\n throw new Error('Cannot update requestId — quote has no steps');\n }\n\n const existingStep = steps[0];\n const remainingSteps = steps.slice(1);\n\n quote.steps = [{ ...existingStep, requestId }, ...remainingSteps];\n}\n\nexport async function getRelayExecuteRequest({\n allParams,\n isSubsidized = false,\n messenger,\n quote,\n regenerateBatchParams = false,\n requestId,\n transaction,\n}: {\n allParams: TransactionParams[];\n isSubsidized?: boolean;\n messenger: TransactionPayControllerMessenger;\n quote: TransactionPayQuote<RelayQuote>;\n regenerateBatchParams?: boolean;\n requestId: string;\n transaction: TransactionMeta;\n}): Promise<Omit<RelayExecuteRequest, 'metamask'>> {\n const { from, sourceChainId } = quote.request;\n const networkClientId = getNetworkClientId(messenger, sourceChainId);\n\n const nestedTransactions = allParams.map((param) => ({\n data: (param.data ?? '0x') as Hex,\n to: param.to as Hex,\n value: (param.value ?? '0x0') as Hex,\n }));\n\n let txParams = { ...transaction.txParams, from };\n\n if (regenerateBatchParams) {\n // Regenerate `txParams` so it matches the current quote's nested transactions.\n // The original `transaction.txParams` may be stale (from a previous quote), and\n // downstream delegation caveats are built from `txParams.data`, so it must reflect\n // the transactions being redeemed. A single nested transaction is used directly;\n // multiple are wrapped into an atomic EIP-7702 (ERC-7821) batch.\n const batchParams =\n nestedTransactions.length === 1\n ? nestedTransactions[0]\n : generateEIP7702BatchTransaction(from, nestedTransactions);\n txParams = {\n ...txParams,\n to: batchParams.to,\n value: batchParams.value ?? '0x0',\n data: batchParams.data,\n };\n }\n\n const executionTransaction: TransactionMeta = {\n ...transaction,\n chainId: sourceChainId,\n networkClientId,\n nestedTransactions,\n txParams,\n } as TransactionMeta;\n\n const delegation = await messenger.call(\n 'TransactionPayController:getDelegationTransaction',\n { transaction: executionTransaction, isSubsidized },\n );\n\n log('Delegation result for execute request', delegation);\n\n return {\n executionKind: 'rawCalls',\n data: {\n chainId: Number(sourceChainId),\n to: delegation.to,\n data: delegation.data,\n value: new BigNumber(delegation.value).toFixed(),\n ...mapAuthorizationList(delegation.authorizationList),\n },\n executionOptions: {\n subsidizeFees: false,\n },\n requestId,\n };\n}\n"]}
1
+ {"version":3,"file":"relay-submit-execute.js","sourceRoot":"","sources":["../../../src/strategy/relay/relay-submit-execute.ts"],"names":[],"mappings":"AAAA,OAAO,E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AAQ;KACU,CAAC;IAErB,MAAM,UAAU,GAAG,MAAM,SAAS,CAAC,IAAI,CACrC,mDAAmD,EACnD,EAAE,WAAW,EAAE,oBAAoB,EAAE,YAAY,EAAE,CACpD,CAAC;IAEF,GAAG,CAAC,uCAAuC,EAAE,UAAU,CAAC,CAAC;IAEzD,OAAO;QACL,aAAa,EAAE,UAAU;QACzB,IAAI,EAAE;YACJ,OAAO,EAAE,MAAM,CAAC,aAAa,CAAC;YAC9B,EAAE,EAAE,UAAU,CAAC,EAAE;YACjB,IAAI,EAAE,UAAU,CAAC,IAAI;YACrB,KAAK,EAAE,IAAI,SAAS,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE;YAChD,GAAG,oBAAoB,CAAC,UAAU,CAAC,iBAAiB,CAAC;SACtD;QACD,gBAAgB,EAAE;YAChB,aAAa,EAAE,KAAK;SACrB;QACD,SAAS;KACV,CAAC;AACJ,CAAC","sourcesContent":["import { generateEIP7702BatchTransaction } from '@metamask/transaction-controller';\nimport type { TransactionParams } from '@metamask/transaction-controller';\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 { projectLogger } from '../../logger.js';\nimport type {\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types.js';\nimport { prefixError } from '../../utils/error-prefix.js';\nimport { getNetworkClientId } from '../../utils/provider.js';\nimport { FALLBACK_HASH } from './constants.js';\nimport { submitRelayExecute } from './relay-api.js';\nimport type { RelayExecuteRequest, RelayQuote } from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'relay-strategy');\nconst RELAY_EXECUTE_ERROR_PREFIX = 'Execute: ';\n\nexport async function submitViaRelayExecute(\n quote: TransactionPayQuote<RelayQuote>,\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n allParams: TransactionParams[],\n): Promise<Hex> {\n try {\n return await submitViaRelayExecuteInternal(\n quote,\n transaction,\n messenger,\n allParams,\n );\n } catch (error) {\n throw prefixError(error, RELAY_EXECUTE_ERROR_PREFIX);\n }\n}\n\nasync function submitViaRelayExecuteInternal(\n quote: TransactionPayQuote<RelayQuote>,\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n allParams: TransactionParams[],\n): Promise<Hex> {\n const isSubsidized = isSubsidizedRelayQuote(quote.original);\n const requestId = getRelayExecuteRequestId(quote.original);\n const metamask = getRelayExecuteMetamask(quote.original, isSubsidized);\n\n const core = await getRelayExecuteRequest({\n allParams,\n isSubsidized,\n messenger,\n quote,\n regenerateBatchParams: true,\n requestId,\n transaction,\n });\n\n const executeBody: RelayExecuteRequest = { ...core, metamask };\n\n log('Submitting to Relay execute', { executeBody, from: quote.request.from });\n\n const result = await submitRelayExecute(messenger, executeBody);\n\n log('Relay execute response', result);\n\n // Server may return a different requestId (e.g. after JIT quote for subsidized).\n // Replace the original quote requestId so waitForRelayCompletion polls the correct request.\n replaceFirstStepRequestId(quote.original, result.requestId);\n\n return FALLBACK_HASH;\n}\n\nexport function isSubsidizedRelayQuote(quote: RelayQuote): boolean {\n return Number(quote.fees?.subsidized?.amountUsd ?? '0') > 0;\n}\n\nfunction stripRelayExecuteMarker(requestId: string): string {\n return requestId.includes('#mm')\n ? requestId.slice(0, requestId.indexOf('#mm'))\n : requestId;\n}\n\nfunction getRelayExecuteRequestId(quote: RelayQuote): string {\n const requestId = quote.steps?.[0]?.requestId;\n if (!requestId) {\n throw new Error('Missing requestId in quote step');\n }\n return stripRelayExecuteMarker(requestId);\n}\n\nfunction getRelayExecuteMetamask(\n quote: RelayQuote,\n isSubsidized: boolean,\n): {\n isSubsidized: boolean;\n quoteRequest: RelayQuote['request'];\n signature: string;\n} {\n const signature = quote.metamask?.signature;\n if (!signature) {\n throw new Error(\n 'Missing metamask.signature — cannot submit to /relay/execute without the HMAC token',\n );\n }\n return {\n isSubsidized,\n quoteRequest: quote.request,\n signature,\n };\n}\n\nfunction mapAuthorizationList(\n authorizationList: AuthorizationList | undefined,\n): {\n authorizationList?: {\n chainId: number;\n address: Hex;\n nonce: number;\n yParity: number;\n r: Hex;\n s: Hex;\n }[];\n} {\n if (!authorizationList?.length) {\n return {};\n }\n return {\n authorizationList: authorizationList.map((auth) => ({\n chainId: Number(auth.chainId),\n address: auth.address,\n nonce: Number(auth.nonce),\n yParity: Number(auth.yParity),\n r: auth.r as Hex,\n s: auth.s as Hex,\n })),\n };\n}\n\nfunction replaceFirstStepRequestId(quote: RelayQuote, requestId: string): void {\n /* istanbul ignore next: requestId is read from steps[0] earlier, so steps is non-empty here; defensive guard. */\n const steps = quote.steps ?? [];\n /* istanbul ignore if: requestId is read from steps[0] earlier, so steps is non-empty here; defensive guard. */\n if (steps.length === 0) {\n throw new Error('Cannot update requestId — quote has no steps');\n }\n\n const existingStep = steps[0];\n const remainingSteps = steps.slice(1);\n\n quote.steps = [{ ...existingStep, requestId }, ...remainingSteps];\n}\n\nexport async function getRelayExecuteRequest({\n allParams,\n isSubsidized = false,\n messenger,\n quote,\n regenerateBatchParams = false,\n requestId,\n transaction,\n}: {\n allParams: TransactionParams[];\n isSubsidized?: boolean;\n messenger: TransactionPayControllerMessenger;\n quote: TransactionPayQuote<RelayQuote>;\n regenerateBatchParams?: boolean;\n requestId: string;\n transaction: TransactionMeta;\n}): Promise<Omit<RelayExecuteRequest, 'metamask'>> {\n const { from, sourceChainId } = quote.request;\n const networkClientId = getNetworkClientId(messenger, sourceChainId);\n\n const nestedTransactions = allParams.map((param) => ({\n data: (param.data ?? '0x') as Hex,\n to: param.to as Hex,\n value: (param.value ?? '0x0') as Hex,\n }));\n\n let txParams = { ...transaction.txParams, from };\n\n if (regenerateBatchParams) {\n // Regenerate `txParams` so it matches the current quote's nested transactions.\n // The original `transaction.txParams` may be stale (from a previous quote), and\n // downstream delegation caveats are built from `txParams.data`, so it must reflect\n // the transactions being redeemed. A single nested transaction is used directly;\n // multiple are wrapped into an atomic EIP-7702 (ERC-7821) batch.\n const batchParams =\n nestedTransactions.length === 1\n ? nestedTransactions[0]\n : generateEIP7702BatchTransaction(from, nestedTransactions);\n txParams = {\n ...txParams,\n to: batchParams.to,\n value: batchParams.value ?? '0x0',\n data: batchParams.data,\n };\n }\n\n const executionTransaction: TransactionMeta = {\n ...transaction,\n chainId: sourceChainId,\n networkClientId,\n nestedTransactions,\n txParams,\n } as TransactionMeta;\n\n const delegation = await messenger.call(\n 'TransactionPayController:getDelegationTransaction',\n { transaction: executionTransaction, isSubsidized },\n );\n\n log('Delegation result for execute request', delegation);\n\n return {\n executionKind: 'rawCalls',\n data: {\n chainId: Number(sourceChainId),\n to: delegation.to,\n data: delegation.data,\n value: new BigNumber(delegation.value).toFixed(),\n ...mapAuthorizationList(delegation.authorizationList),\n },\n executionOptions: {\n subsidizeFees: false,\n },\n requestId,\n };\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -314,7 +314,7 @@ export type TransactionPaySourceAmount = {
314
314
  * Used for analytics and tests. Human-readable copy is carried by `message`
315
315
  * and `detail` on {@link QuoteErrorInfo}.
316
316
  */
317
- export type QuoteErrorReason = 'balance-unavailable' | 'insufficient-source-balance' | 'insufficient-transfer-balance' | 'no-quotes' | 'simulation-failed';
317
+ export type QuoteErrorReason = 'atomic-promotion-failed' | 'balance-unavailable' | 'insufficient-source-balance' | 'insufficient-transfer-balance' | 'no-quotes' | 'simulation-failed';
318
318
  /**
319
319
  * Structured description of why a quote failed validation.
320
320
  *
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,+CAA+C,EAC/C,gCAAgC,EACjC,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EACV,oCAAoC,EACpC,uBAAuB,EACvB,qCAAqC,EACtC,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,kCAAkC,EAAE,MAAM,8BAA8B,CAAC;AACv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AE,8BAA8B,CAAC;CAC1C,CAAC;AAEF,gEAAgE;AAChE,MAAM,MAAM,gCAAgC,GAAG,CAAC,EAC9C,WAAW,EACX,YAAY,GACb,EAAE;IACD,WAAW,EAAE,eAAe,CAAC;IAC7B,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,KAAK,OAAO,CAAC;IACZ,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,IAAI,EAAE,GAAG,CAAC;IACV,EAAE,EAAE,GAAG,CAAC;IACR,KAAK,EAAE,GAAG,CAAC;CACZ,CAAC,CAAC;AAEH,qEAAqE;AACrE,MAAM,MAAM,mBAAmB,GAAG;IAChC,qEAAqE;IACrE,uBAAuB,EAAE,CAAC,MAAM,EAAE;QAAE,GAAG,EAAE,GAAG,CAAA;KAAE,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IAEhE,4EAA4E;IAC5E,wBAAwB,EAAE,CAAC,MAAM,EAAE;QACjC,GAAG,EAAE,GAAG,CAAC;QACT,aAAa,EAAE,GAAG,CAAC;QACnB,KAAK,EAAE;YAAE,MAAM,EAAE,GAAG,CAAC;YAAC,IAAI,EAAE,GAAG,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAE,EAAE,CAAC;KACpD,KAAK,OAAO,CAAC;QAAE,UAAU,EAAE,GAAG,CAAA;KAAE,CAAC,CAAC;CACpC,CAAC;AAEF,0CAA0C;AAC1C,MAAM,MAAM,MAAM,GAAG,SAAS,GAAG;IAC/B,gEAAgE;IAChE,KAAK,EAAE,MAAM,CAAC;IAEd,gEAAgE;IAChE,GAAG,EAAE,MAAM,CAAC;CACb,CAAC"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA4QA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type {\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n CurrencyRateStateChange,\n TokenBalancesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type { TokenRatesControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { TokenRatesControllerStateChangeEvent } from '@metamask/assets-controllers';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n} from '@metamask/assets-controllers';\nimport type { AccountTrackerControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringControllerUnlockEvent,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkConfigurationByChainIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuotesAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SentinelApiServiceActions } from '@metamask/sentinel-api-service';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n BatchTransactionParams,\n TransactionControllerAddTransactionAction,\n TransactionControllerGetGasFeeTokensAction,\n TransactionControllerGetStateAction,\n TransactionControllerStateChangeEvent,\n TransactionControllerUpdateTransactionAction,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n CONTROLLER_NAME,\n PaymentOverride,\n TransactionPayStrategy,\n} from './constants.js';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types.js';\n\nexport type AllowedActions =\n | AccountTrackerControllerGetStateAction\n | AssetsControllerGetStateForTransactionPayAction\n | CurrencyRateControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByChainIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuotesAction\n | RemoteFeatureFlagControllerGetStateAction\n | TokenBalancesControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | TokensControllerGetStateAction\n | SentinelApiServiceActions\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | CurrencyRateStateChange\n | KeyringControllerUnlockEvent\n | TokenRatesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction (or `paymentOverride` batch) is executed\n * atomically with the Relay quote. Defaults to `true` (embedded in the quote\n * and executed by the Relay solver). When `false`, Pay does not embed the\n * target/override calls in the quote; the quote only bridges the required\n * asset to `recipient`, and the calls are submitted separately after Relay\n * completion. Used by flows whose second-leg amount is only known after\n * Relay settles (EXACT_INPUT max flows) or that require the second leg to\n * originate from a different signer than the Relay solver.\n */\n atomic?: boolean;\n\n /**\n * Whether the source of funds is HyperLiquid (HyperCore).\n * When true, the Relay strategy uses the HyperLiquid 2-step withdrawal\n * flow: (1) authorize nonce-mapping, (2) sendAsset to Relay solver.\n */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n */\n isPostQuote?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request. Use this for post-quote flows where the user's funds originate\n * from a smart contract account (e.g. Predict Safe proxy) so that refunds\n * go back to that account rather than the EOA.\n */\n refundTo?: Hex;\n};\n\n/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Request passed to {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataRequest = {\n /** Amount of the source token in human-readable format. */\n amount: string;\n\n /** Metadata of the original transaction. */\n transaction: TransactionMeta;\n\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Response returned by {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataResponse = {\n /** Batch transaction params to prepend to the submit batch. */\n calls: BatchTransactionParams[];\n\n /** Optional recipient address for the funding token transfer. */\n recipient?: Hex;\n\n /** Optional EIP-7702 authorization list from delegation. */\n authorizationList?: AuthorizationList;\n};\n\n/**\n * Callback invoked during submit when `paymentOverride` is defined.\n * Returns batch transaction params to prepend to the submit batch.\n */\nexport type GetPaymentOverrideDataCallback = (\n request: GetPaymentOverrideDataRequest,\n) => Promise<GetPaymentOverrideDataResponse>;\n\nexport type GetAmountDataRequest = {\n /** Raw token amount (atomic units) to encode into calldata. */\n amount: string;\n\n /** Metadata of the transaction whose nested calls need updating. */\n transaction: TransactionMeta;\n};\n\nexport type GetAmountDataResponse = {\n /** Per-nested-call data updates; empty when no update is needed. */\n updates: { nestedTransactionIndex: number; data: Hex }[];\n};\n\n/**\n * Optional callback that re-encodes nested transaction calldata for a given\n * token amount. Used by transaction types with non-standard nested data\n * (e.g. vault approve + deposit) that cannot be derived from the amount alone\n * without client-side context (vault config, RPC providers, etc.).\n */\nexport type GetAmountDataCallback = (\n request: GetAmountDataRequest,\n) => Promise<GetAmountDataResponse>;\n\n/** Request passed to {@link GetBalanceCallback}. */\nexport type GetBalanceRequest = {\n /** Metadata of the transaction whose source balance is being resolved. */\n transaction: TransactionMeta;\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Balance override returned by {@link GetBalanceCallback}. */\nexport type GetBalanceResponse = {\n /** Balance in atomic format without factoring token decimals. */\n balanceRaw: string;\n};\n\n/**\n * Optional client-supplied callback that overrides the built-in\n * pay-token / required-token balance lookup used for `isMaxAmount`\n * source-amount calculation. Enables alternate balance sources\n * (perps, predict, money-account, post-quote, etc.) without adding\n * conditional branches inside the controller. MUST be synchronous:\n * it runs inside the controller state-update block.\n * Return `undefined` to fall back to the built-in token balance.\n */\nexport type GetBalanceCallback = (\n request: GetBalanceRequest,\n) => GetBalanceResponse | undefined;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /** Optional callback to re-encode nested transaction calldata for a given amount. */\n getAmountData?: GetAmountDataCallback;\n\n /** Optional callback to override the source balance used for max-amount calculation. */\n getBalance?: GetBalanceCallback;\n\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** Optional fiat execution configuration. */\n fiatOptions?: TransactionPayFiatOptions;\n\n /**\n * Optional callback invoked during quote execution when `paymentOverride` is defined.\n * Returns additional transactions to be submitted alongside the quote batch.\n */\n getPaymentOverrideData?: GetPaymentOverrideDataCallback;\n\n /** Callback to select the PayStrategy for a transaction. */\n getStrategy?: (transaction: TransactionMeta) => TransactionPayStrategy;\n\n /** Callback to select ordered PayStrategies for a transaction. */\n getStrategies?: (transaction: TransactionMeta) => TransactionPayStrategy[];\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Callbacks for the Polymarket relayer; required only for the Polymarket deposit-wallet flow. */\n polymarket?: PolymarketCallbacks;\n\n /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** Optional fiat execution configuration. */\nexport type TransactionPayFiatOptions = {\n /** Test funding source used to bypass fiat on-ramp execution during local QA. */\n testFundingSource?: Hex;\n\n /** Optional human amount to transfer from the test funding source. */\n testAmountOverride?: string;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Fiat payment method state. */\n fiatPayment?: TransactionFiatPayment;\n\n /** Whether quotes are currently being retrieved. */\n isLoading: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n * Used when funds need to be moved after a transaction completes\n * (e.g., bridging output to a different token/chain).\n */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /**\n * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Most relevant structured validation error from the latest quote attempt. */\n quoteError?: QuoteErrorInfo;\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */\n caipAssetId?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/**\n * Machine-readable discriminator for a quote validation failure.\n *\n * Used for analytics and tests. Human-readable copy is carried by `message`\n * and `detail` on {@link QuoteErrorInfo}.\n */\nexport type QuoteErrorReason =\n | 'balance-unavailable'\n | 'insufficient-source-balance'\n | 'insufficient-transfer-balance'\n | 'no-quotes'\n | 'simulation-failed';\n\n/**\n * Structured description of why a quote failed validation.\n *\n * `message` and `detail` are formatted (English) copy ready to display; `reason`\n * is a machine-readable discriminator for analytics and tests.\n */\nexport type QuoteErrorInfo = {\n /** Short, display-ready summary of the failure. */\n message: string;\n\n /** Machine-readable discriminator for the failure. */\n reason: QuoteErrorReason;\n\n /** Optional display-ready detail rows (e.g. Required / Current / Missing). */\n detail?: string[];\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether this quote is the direct mUSD-to-Money-Account fiat flow. */\n isDirectMusdMoneyAccount?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** Optional recipient address for Relay requests. When set, overrides the default `from` address. */\n recipient?: Hex;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /** Whether to skip processTransactions in relay-quotes. Defaults to `isPostQuote`. */\n skipProcessTransactions?: boolean;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n\n /**\n * One-time HyperLiquid activation fee (USD) reserved from the source amount\n * for an unactivated HyperCore account. The source amount sent to the\n * provider is reduced by this amount so HyperLiquid retains enough balance\n * for the fee, and the amount is surfaced as part of the provider fee.\n */\n hyperliquidActivationFeeUsd?: string;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Whether fees are subtracted from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /**\n * Resolved wallet address for the transaction.\n * This is `accountOverride ?? txParams.from`, pre-computed by the quote\n * orchestrator so that individual strategies do not need to re-derive it.\n */\n from: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Whether the selected quotes subtract fees from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n isSubsidized,\n}: {\n transaction: TransactionMeta;\n isSubsidized?: boolean;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** Client-supplied callbacks for the Polymarket relayer protocol. */\nexport type PolymarketCallbacks = {\n /** Derive the deposit-wallet address (CREATE2) for the given EOA. */\n getDepositWalletAddress: (params: { eoa: Hex }) => Promise<Hex>;\n\n /** Sign and broadcast a deposit-wallet batch, returning the source hash. */\n submitDepositWalletBatch: (params: {\n eoa: Hex;\n depositWallet: Hex;\n calls: { target: Hex; data: Hex; value: string }[];\n }) => Promise<{ sourceHash: Hex }>;\n};\n\n/** Single amount in alternate formats. */\nexport type Amount = FiatValue & {\n /** Amount in human-readable format factoring token decimals. */\n human: string;\n\n /** Amount in atomic format without factoring token decimals. */\n raw: string;\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA4QA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type {\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n CurrencyRateStateChange,\n TokenBalancesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type { TokenRatesControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { TokenRatesControllerStateChangeEvent } from '@metamask/assets-controllers';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n} from '@metamask/assets-controllers';\nimport type { AccountTrackerControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringControllerUnlockEvent,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkConfigurationByChainIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuotesAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SentinelApiServiceActions } from '@metamask/sentinel-api-service';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n BatchTransactionParams,\n TransactionControllerAddTransactionAction,\n TransactionControllerGetGasFeeTokensAction,\n TransactionControllerGetStateAction,\n TransactionControllerStateChangeEvent,\n TransactionControllerUpdateTransactionAction,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n CONTROLLER_NAME,\n PaymentOverride,\n TransactionPayStrategy,\n} from './constants.js';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types.js';\n\nexport type AllowedActions =\n | AccountTrackerControllerGetStateAction\n | AssetsControllerGetStateForTransactionPayAction\n | CurrencyRateControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByChainIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuotesAction\n | RemoteFeatureFlagControllerGetStateAction\n | TokenBalancesControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | TokensControllerGetStateAction\n | SentinelApiServiceActions\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | CurrencyRateStateChange\n | KeyringControllerUnlockEvent\n | TokenRatesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction (or `paymentOverride` batch) is executed\n * atomically with the Relay quote. Defaults to `true` (embedded in the quote\n * and executed by the Relay solver). When `false`, Pay does not embed the\n * target/override calls in the quote; the quote only bridges the required\n * asset to `recipient`, and the calls are submitted separately after Relay\n * completion. Used by flows whose second-leg amount is only known after\n * Relay settles (EXACT_INPUT max flows) or that require the second leg to\n * originate from a different signer than the Relay solver.\n */\n atomic?: boolean;\n\n /**\n * Whether the source of funds is HyperLiquid (HyperCore).\n * When true, the Relay strategy uses the HyperLiquid 2-step withdrawal\n * flow: (1) authorize nonce-mapping, (2) sendAsset to Relay solver.\n */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n */\n isPostQuote?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request. Use this for post-quote flows where the user's funds originate\n * from a smart contract account (e.g. Predict Safe proxy) so that refunds\n * go back to that account rather than the EOA.\n */\n refundTo?: Hex;\n};\n\n/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Request passed to {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataRequest = {\n /** Amount of the source token in human-readable format. */\n amount: string;\n\n /** Metadata of the original transaction. */\n transaction: TransactionMeta;\n\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Response returned by {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataResponse = {\n /** Batch transaction params to prepend to the submit batch. */\n calls: BatchTransactionParams[];\n\n /** Optional recipient address for the funding token transfer. */\n recipient?: Hex;\n\n /** Optional EIP-7702 authorization list from delegation. */\n authorizationList?: AuthorizationList;\n};\n\n/**\n * Callback invoked during submit when `paymentOverride` is defined.\n * Returns batch transaction params to prepend to the submit batch.\n */\nexport type GetPaymentOverrideDataCallback = (\n request: GetPaymentOverrideDataRequest,\n) => Promise<GetPaymentOverrideDataResponse>;\n\nexport type GetAmountDataRequest = {\n /** Raw token amount (atomic units) to encode into calldata. */\n amount: string;\n\n /** Metadata of the transaction whose nested calls need updating. */\n transaction: TransactionMeta;\n};\n\nexport type GetAmountDataResponse = {\n /** Per-nested-call data updates; empty when no update is needed. */\n updates: { nestedTransactionIndex: number; data: Hex }[];\n};\n\n/**\n * Optional callback that re-encodes nested transaction calldata for a given\n * token amount. Used by transaction types with non-standard nested data\n * (e.g. vault approve + deposit) that cannot be derived from the amount alone\n * without client-side context (vault config, RPC providers, etc.).\n */\nexport type GetAmountDataCallback = (\n request: GetAmountDataRequest,\n) => Promise<GetAmountDataResponse>;\n\n/** Request passed to {@link GetBalanceCallback}. */\nexport type GetBalanceRequest = {\n /** Metadata of the transaction whose source balance is being resolved. */\n transaction: TransactionMeta;\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Balance override returned by {@link GetBalanceCallback}. */\nexport type GetBalanceResponse = {\n /** Balance in atomic format without factoring token decimals. */\n balanceRaw: string;\n};\n\n/**\n * Optional client-supplied callback that overrides the built-in\n * pay-token / required-token balance lookup used for `isMaxAmount`\n * source-amount calculation. Enables alternate balance sources\n * (perps, predict, money-account, post-quote, etc.) without adding\n * conditional branches inside the controller. MUST be synchronous:\n * it runs inside the controller state-update block.\n * Return `undefined` to fall back to the built-in token balance.\n */\nexport type GetBalanceCallback = (\n request: GetBalanceRequest,\n) => GetBalanceResponse | undefined;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /** Optional callback to re-encode nested transaction calldata for a given amount. */\n getAmountData?: GetAmountDataCallback;\n\n /** Optional callback to override the source balance used for max-amount calculation. */\n getBalance?: GetBalanceCallback;\n\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** Optional fiat execution configuration. */\n fiatOptions?: TransactionPayFiatOptions;\n\n /**\n * Optional callback invoked during quote execution when `paymentOverride` is defined.\n * Returns additional transactions to be submitted alongside the quote batch.\n */\n getPaymentOverrideData?: GetPaymentOverrideDataCallback;\n\n /** Callback to select the PayStrategy for a transaction. */\n getStrategy?: (transaction: TransactionMeta) => TransactionPayStrategy;\n\n /** Callback to select ordered PayStrategies for a transaction. */\n getStrategies?: (transaction: TransactionMeta) => TransactionPayStrategy[];\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Callbacks for the Polymarket relayer; required only for the Polymarket deposit-wallet flow. */\n polymarket?: PolymarketCallbacks;\n\n /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** Optional fiat execution configuration. */\nexport type TransactionPayFiatOptions = {\n /** Test funding source used to bypass fiat on-ramp execution during local QA. */\n testFundingSource?: Hex;\n\n /** Optional human amount to transfer from the test funding source. */\n testAmountOverride?: string;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Fiat payment method state. */\n fiatPayment?: TransactionFiatPayment;\n\n /** Whether quotes are currently being retrieved. */\n isLoading: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n * Used when funds need to be moved after a transaction completes\n * (e.g., bridging output to a different token/chain).\n */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /**\n * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Most relevant structured validation error from the latest quote attempt. */\n quoteError?: QuoteErrorInfo;\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */\n caipAssetId?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/**\n * Machine-readable discriminator for a quote validation failure.\n *\n * Used for analytics and tests. Human-readable copy is carried by `message`\n * and `detail` on {@link QuoteErrorInfo}.\n */\nexport type QuoteErrorReason =\n | 'atomic-promotion-failed'\n | 'balance-unavailable'\n | 'insufficient-source-balance'\n | 'insufficient-transfer-balance'\n | 'no-quotes'\n | 'simulation-failed';\n\n/**\n * Structured description of why a quote failed validation.\n *\n * `message` and `detail` are formatted (English) copy ready to display; `reason`\n * is a machine-readable discriminator for analytics and tests.\n */\nexport type QuoteErrorInfo = {\n /** Short, display-ready summary of the failure. */\n message: string;\n\n /** Machine-readable discriminator for the failure. */\n reason: QuoteErrorReason;\n\n /** Optional display-ready detail rows (e.g. Required / Current / Missing). */\n detail?: string[];\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether this quote is the direct mUSD-to-Money-Account fiat flow. */\n isDirectMusdMoneyAccount?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** Optional recipient address for Relay requests. When set, overrides the default `from` address. */\n recipient?: Hex;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /** Whether to skip processTransactions in relay-quotes. Defaults to `isPostQuote`. */\n skipProcessTransactions?: boolean;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n\n /**\n * One-time HyperLiquid activation fee (USD) reserved from the source amount\n * for an unactivated HyperCore account. The source amount sent to the\n * provider is reduced by this amount so HyperLiquid retains enough balance\n * for the fee, and the amount is surfaced as part of the provider fee.\n */\n hyperliquidActivationFeeUsd?: string;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Whether fees are subtracted from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /**\n * Resolved wallet address for the transaction.\n * This is `accountOverride ?? txParams.from`, pre-computed by the quote\n * orchestrator so that individual strategies do not need to re-derive it.\n */\n from: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Whether the selected quotes subtract fees from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n isSubsidized,\n}: {\n transaction: TransactionMeta;\n isSubsidized?: boolean;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** Client-supplied callbacks for the Polymarket relayer protocol. */\nexport type PolymarketCallbacks = {\n /** Derive the deposit-wallet address (CREATE2) for the given EOA. */\n getDepositWalletAddress: (params: { eoa: Hex }) => Promise<Hex>;\n\n /** Sign and broadcast a deposit-wallet batch, returning the source hash. */\n submitDepositWalletBatch: (params: {\n eoa: Hex;\n depositWallet: Hex;\n calls: { target: Hex; data: Hex; value: string }[];\n }) => Promise<{ sourceHash: Hex }>;\n};\n\n/** Single amount in alternate formats. */\nexport type Amount = FiatValue & {\n /** Amount in human-readable format factoring token decimals. */\n human: string;\n\n /** Amount in atomic format without factoring token decimals. */\n raw: string;\n};\n"]}
@@ -474,6 +474,18 @@ async function getQuotes(transaction, from, requests, paymentToken, isQuoteRequi
474
474
  error ??= isQuoteError(caughtError)
475
475
  ? caughtError.info
476
476
  : { message: caughtError.message, reason: 'no-quotes' };
477
+ if (isQuoteError(caughtError) &&
478
+ caughtError.info.reason === 'atomic-promotion-failed') {
479
+ log('Terminal atomic-promotion-failed, aborting remaining strategies', {
480
+ strategy: name,
481
+ transactionId,
482
+ });
483
+ return {
484
+ batchTransactions: [],
485
+ error: caughtError.info,
486
+ quotes: [],
487
+ };
488
+ }
477
489
  if (isQuoteError(caughtError) &&
478
490
  caughtError.info.reason === 'insufficient-source-balance' &&
479
491
  caughtError.quotes?.length) {
@@ -1 +1 @@
1
- {"version":3,"file":"quotes.js","sourceRoot":"","sources":["../../src/utils/quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAIrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAmB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAa7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,wBAAwB,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,aAAa;AAEzD,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;AAExD,MAAM,qBAAqB,GAAG,IAAI,GAAG,EAA2B,CAAC;AAUjE;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,OAA4B;IAE5B,MAAM,EACJ,aAAa,EACb,S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AQ,EAAE,IAAI;gBACd,aAAa;aACd,CAAC,CAAC;YACH,SAAS;QACX,CAAC;IACH,CAAC;IAED,GAAG,CAAC,qBAAqB,EAAE,EAAE,aAAa,EAAE,CAAC,CAAC;IAE9C,OAAO;QACL,iBAAiB,EAAE,EAAE;QACrB,KAAK;QACL,MAAM,EAAE,EAAE;KACX,CAAC;AACJ,CAAC","sourcesContent":["import { TransactionStatus } from '@metamask/transaction-controller';\nimport type { BatchTransaction } from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { PaymentOverride, TransactionPayStrategy } from '../constants.js';\nimport { projectLogger } from '../logger.js';\nimport type {\n QuoteRequest,\n QuoteErrorInfo,\n TransactionData,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPaySourceAmount,\n TransactionPayTotals,\n TransactionPaymentToken,\n UpdateTransactionDataCallback,\n} from '../types.js';\nimport { accountSupports7702 } from './7702.js';\nimport { buildNoOpQuote } from './no-op-quote.js';\nimport {\n checkStrategyQuoteSupport,\n checkStrategySupport,\n getStrategiesByName,\n getStrategyByName,\n} from './strategy.js';\nimport {\n computeTokenAmounts,\n getLiveTokenBalance,\n getTokenFiatRate,\n} from './token.js';\nimport { calculateTotals } from './totals.js';\nimport { getTransaction, updateTransaction } from './transaction.js';\nimport { isQuoteError } from './validation.js';\n\nconst DEFAULT_REFRESH_INTERVAL = 30 * 1000; // 30 Seconds\n\nconst log = createModuleLogger(projectLogger, 'quotes');\n\nconst inFlightQuoteRequests = new Map<string, AbortController>();\n\nexport type UpdateQuotesRequest = {\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[];\n messenger: TransactionPayControllerMessenger;\n transactionData: TransactionData | undefined;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n};\n\n/**\n * Update the quotes for a specific transaction.\n *\n * Calls for the same `transactionId` are serialised: a fresh call aborts any\n * previous in-flight call so a slower stale response cannot overwrite a newer\n * one in state.\n *\n * @param request - Request parameters.\n * @returns Boolean indicating if the quotes were updated. Returns `false` when\n * the call was aborted by a subsequent call for the same transaction.\n */\nexport async function updateQuotes(\n request: UpdateQuotesRequest,\n): Promise<boolean> {\n const {\n getStrategies,\n messenger,\n transactionData,\n transactionId,\n updateTransactionData,\n } = request;\n\n const transaction = getTransaction(transactionId, messenger);\n\n if (!transaction || !transactionData) {\n throw new Error('Transaction not found');\n }\n\n if (transaction?.status !== TransactionStatus.unapproved) {\n return false;\n }\n\n log('Updating quotes', { transactionId });\n\n const {\n accountOverride,\n atomic,\n fiatPayment,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n isQuoteRequired,\n paymentOverride,\n paymentToken: originalPaymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n } = transactionData;\n\n const from = accountOverride ?? (transaction.txParams.from as Hex);\n\n const controller = abortPreviousAndCreateController(transactionId);\n const { signal } = controller;\n\n updateTransactionData(transactionId, (data) => {\n data.isLoading = true;\n data.quoteError = undefined;\n });\n\n try {\n const paymentToken = await refreshPaymentTokenBalance({\n from,\n messenger,\n paymentToken: originalPaymentToken,\n signal,\n transactionId,\n updateTransactionData,\n });\n\n if (signal.aborted) {\n log('Quote request aborted before building requests', { transactionId });\n return false;\n }\n\n const requests = buildQuoteRequests({\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount: isMaxAmount ?? false,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n transactionId,\n });\n\n const supports7702 = accountSupports7702(messenger, from);\n\n const { batchTransactions, error, quotes } = await getQuotes(\n transaction,\n from,\n requests,\n paymentToken,\n isQuoteRequired ?? false,\n supports7702,\n getStrategies,\n messenger,\n fiatPayment?.selectedPaymentMethodId,\n signal,\n );\n\n if (signal.aborted) {\n log('Quote request aborted before persisting results', { transactionId });\n return false;\n }\n\n // No-op quotes mark direct routes. They have no fees or amounts and the\n // transaction is signed and submitted locally, so totals and transaction\n // sync must treat them as \"no quotes\".\n const executableQuotes = quotes.filter(\n (quote) => quote.strategy !== TransactionPayStrategy.None,\n );\n\n const totals = calculateTotals({\n fiatPaymentAmount: fiatPayment?.amountFiat,\n messenger,\n quotes: executableQuotes as TransactionPayQuote<unknown>[],\n tokens,\n transaction,\n });\n\n log('Calculated totals', { transactionId, totals });\n\n syncTransaction({\n batchTransactions,\n selectedFiatPayment: fiatPayment?.selectedPaymentMethodId,\n hasQuotes: executableQuotes.length > 0,\n isPostQuote,\n messenger: messenger as never,\n paymentToken,\n strategy: executableQuotes[0]?.strategy,\n totals,\n transactionId,\n });\n\n updateTransactionData(transactionId, (data) => {\n data.quotes = quotes as never;\n data.quoteError = error;\n data.quotesLastUpdated = Date.now();\n data.totals = totals;\n });\n } catch (error) {\n if (signal.aborted) {\n log('Quote request aborted', { transactionId, reason: signal.reason });\n return false;\n }\n throw error;\n } finally {\n if (!signal.aborted) {\n updateTransactionData(transactionId, (data) => {\n data.isLoading = false;\n });\n }\n clearControllerIfCurrent(transactionId, controller);\n }\n\n return true;\n}\n\n/**\n * Sync batch transactions to the transaction meta.\n *\n * @param request - Request object.\n * @param request.batchTransactions - Batch transactions to sync.\n * @param request.hasQuotes - Whether MM Pay produced any quotes for this transaction.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.messenger - Messenger instance.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.selectedFiatPayment - Selected fiat payment method ID.\n * @param request.strategy - Strategy of the executable quotes.\n * @param request.totals - Calculated totals.\n * @param request.transactionId - ID of the transaction to sync.\n */\nfunction syncTransaction({\n batchTransactions,\n hasQuotes,\n isPostQuote,\n messenger,\n paymentToken,\n selectedFiatPayment,\n strategy,\n totals,\n transactionId,\n}: {\n batchTransactions: BatchTransaction[];\n selectedFiatPayment?: string;\n hasQuotes: boolean;\n isPostQuote?: boolean;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n strategy?: TransactionPayStrategy;\n totals: TransactionPayTotals;\n transactionId: string;\n}): void {\n if (!paymentToken && !selectedFiatPayment) {\n return;\n }\n\n updateTransaction(\n {\n transactionId,\n messenger: messenger as never,\n note: 'Update transaction pay data',\n },\n (tx: TransactionMeta) => {\n tx.batchTransactions = batchTransactions;\n tx.batchTransactionsOptions = {};\n\n // When MM Pay has produced quotes, it owns submission of this transaction\n // via its strategy publish hook, so the parent must be marked externally\n // signed to skip the local `KeyringController:signTransaction` call.\n // When there are no quotes (e.g. user selected the target token as the\n // payment token in a Predict flow), the transaction falls back to normal\n // local signing, so the flag is cleared to allow that.\n // If gas is sponsored, TC owns this field — it is set based on the\n // Sentinel simulation result and must not be cleared here. Same-token\n // flows (e.g. Monad mUSD withdrawal via a Money Account) produce no\n // quotes but still need external sign because the account cannot sign\n // locally.\n if (!tx.isGasFeeSponsored) {\n tx.isExternalSign = hasQuotes;\n }\n\n tx.metamaskPay = {\n bridgeFeeFiat: totals.fees.provider.usd,\n chainId: paymentToken?.chainId,\n isPostQuote,\n networkFeeFiat: totals.fees.sourceNetwork.estimate.usd,\n strategy,\n targetFiat: totals.targetAmount.usd,\n tokenAddress: paymentToken?.address,\n totalFiat: totals.total.usd,\n };\n },\n );\n}\n\n/**\n * Refresh quotes for all transactions if expired.\n *\n * @param messenger - Messenger instance.\n * @param updateTransactionData - Callback to update transaction data.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n */\nexport async function refreshQuotes(\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n): Promise<void> {\n const state = messenger.call('TransactionPayController:getState');\n const transactionIds = Object.keys(state.transactionData);\n\n for (const transactionId of transactionIds) {\n const transactionData = state.transactionData[transactionId];\n const { isLoading, quotes, quotesLastUpdated } = transactionData;\n\n if (isLoading || !quotes?.length) {\n continue;\n }\n\n // No-op quotes mark direct routes and have nothing to refresh. They are\n // regenerated whenever the transaction data changes.\n if (\n quotes.every((quote) => quote.strategy === TransactionPayStrategy.None)\n ) {\n continue;\n }\n\n const strategyName = quotes[0].strategy;\n const strategy = getStrategyByName(strategyName);\n\n const refreshInterval =\n (await strategy.getRefreshInterval?.({\n chainId: quotes[0].request.sourceChainId,\n messenger,\n })) ?? DEFAULT_REFRESH_INTERVAL;\n\n const isExpired = Date.now() - (quotesLastUpdated ?? 0) > refreshInterval;\n\n if (!isExpired) {\n continue;\n }\n\n const isUpdated = await updateQuotes({\n getStrategies,\n messenger,\n transactionData,\n transactionId,\n updateTransactionData,\n });\n\n if (isUpdated) {\n log('Refreshed quotes', { transactionId, strategy: strategyName });\n }\n }\n}\n\nfunction abortPreviousAndCreateController(\n transactionId: string,\n): AbortController {\n const previous = inFlightQuoteRequests.get(transactionId);\n\n if (previous && !previous.signal.aborted) {\n log('Aborting previous quote request', { transactionId });\n previous.abort(new Error('Superseded by newer quote request'));\n }\n\n const controller = new AbortController();\n inFlightQuoteRequests.set(transactionId, controller);\n return controller;\n}\n\nfunction clearControllerIfCurrent(\n transactionId: string,\n controller: AbortController,\n): void {\n if (inFlightQuoteRequests.get(transactionId) === controller) {\n inFlightQuoteRequests.delete(transactionId);\n }\n}\n\n/**\n * Build quote requests required to retrieve quotes.\n *\n * @param request - Request parameters.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction.\n * @param request.tokens - Required tokens for the transaction.\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests.\n */\nfunction buildQuoteRequests({\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n transactionId,\n}: {\n atomic?: boolean;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n isPostQuote?: boolean;\n paymentOverride?: PaymentOverride;\n paymentToken: TransactionPaymentToken | undefined;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n tokens: TransactionPayRequiredToken[];\n transactionId: string;\n}): QuoteRequest[] {\n if (!paymentToken) {\n return [];\n }\n\n if (isPostQuote) {\n return buildPostQuoteRequests({\n atomic,\n destinationToken: paymentToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n });\n }\n\n // Standard flow: source = paymentToken, target = required tokens\n const requests = (sourceAmounts ?? []).map((sourceAmount) => {\n const token = tokens.find(\n (singleToken) => singleToken.address === sourceAmount.targetTokenAddress,\n ) as TransactionPayRequiredToken;\n\n return {\n atomic,\n from,\n isMaxAmount,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: paymentToken.balanceRaw,\n sourceChainId: paymentToken.chainId,\n sourceTokenAddress: paymentToken.address,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: token.allowUnderMinimum ? '0' : token.amountRaw,\n targetChainId: token.chainId,\n targetTokenAddress: token.address,\n };\n });\n\n if (!requests.length) {\n log('No quote requests', { transactionId });\n }\n\n return requests;\n}\n\n/**\n * Build quote requests for post-quote flows.\n * In this flow, the source is the transaction's required token,\n * and the target is the user's selected destination token (paymentToken).\n *\n * @param request - Request parameters.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.destinationToken - Destination token (paymentToken in post-quote mode).\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction (includes source token info).\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests for post-quote flow.\n */\nfunction buildPostQuoteRequests({\n atomic,\n destinationToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n}: {\n atomic?: boolean;\n destinationToken: TransactionPaymentToken;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n paymentOverride?: PaymentOverride;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n transactionId: string;\n}): QuoteRequest[] {\n // Find the source amount where targetTokenAddress matches the destination token\n const sourceAmount = sourceAmounts?.find(\n (amount) =>\n amount.targetTokenAddress.toLowerCase() ===\n destinationToken.address.toLowerCase(),\n );\n\n // Same-token-same-chain cases are already filtered in source-amounts.ts\n if (\n !sourceAmount?.sourceBalanceRaw ||\n !sourceAmount.sourceChainId ||\n !sourceAmount.sourceTokenAddress\n ) {\n log('No valid source amount found for post-quote request', {\n transactionId,\n });\n return [];\n }\n\n const request: QuoteRequest = {\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote: true,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: sourceAmount.sourceBalanceRaw,\n sourceChainId: sourceAmount.sourceChainId,\n sourceTokenAddress: sourceAmount.sourceTokenAddress,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: '0',\n targetChainId: destinationToken.chainId,\n targetTokenAddress: destinationToken.address,\n };\n\n log('Post-quote request built', { transactionId, request });\n\n // Currently only single token post-quote flows are supported.\n // Multiple token support would require multiple quotes for each required token.\n return [request];\n}\n\nasync function refreshPaymentTokenBalance({\n from,\n messenger,\n paymentToken,\n signal,\n transactionId,\n updateTransactionData,\n}: {\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n signal: AbortSignal;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n}): Promise<TransactionPaymentToken | undefined> {\n if (!paymentToken) {\n return undefined;\n }\n\n try {\n const fiatRates = getTokenFiatRate(\n messenger,\n paymentToken.address,\n paymentToken.chainId,\n );\n\n if (!fiatRates) {\n return paymentToken;\n }\n\n const liveBalance = await getLiveTokenBalance(\n messenger,\n from,\n paymentToken.chainId,\n paymentToken.address,\n );\n\n if (signal.aborted) {\n log('Payment token balance refresh aborted', { transactionId });\n return paymentToken;\n }\n\n const {\n raw: balanceRaw,\n human: balanceHuman,\n usd: balanceUsd,\n fiat: balanceFiat,\n } = computeTokenAmounts(liveBalance, paymentToken.decimals, fiatRates);\n\n const updatedToken = {\n ...paymentToken,\n balanceFiat,\n balanceHuman,\n balanceRaw,\n balanceUsd,\n };\n\n updateTransactionData(transactionId, (data) => {\n data.paymentToken = updatedToken;\n });\n\n log('Refreshed payment token balance', { transactionId, balanceRaw });\n\n return updatedToken;\n } catch (error) {\n log('Failed to refresh payment token balance', { transactionId, error });\n return paymentToken;\n }\n}\n\n/**\n * Retrieve quotes for a transaction.\n *\n * @param transaction - Transaction metadata.\n * @param from - Resolved wallet address (`accountOverride ?? txParams.from`).\n * @param requests - Quote requests.\n * @param paymentToken - Selected payment token, if any.\n * @param isQuoteRequired - Whether a quote is always required for the transaction.\n * @param isAccountEIP7702Compatible - Whether the account supports EIP-7702.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n * @param messenger - Controller messenger.\n * @param fiatPaymentMethod - Selected fiat payment method ID, if applicable.\n * @param signal - Signal that aborts when the quote request is superseded.\n * @returns An object containing batch transactions and quotes.\n */\nasync function getQuotes(\n transaction: TransactionMeta,\n from: Hex,\n requests: QuoteRequest[],\n paymentToken: TransactionPaymentToken | undefined,\n isQuoteRequired: boolean,\n isAccountEIP7702Compatible: boolean,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n messenger: TransactionPayControllerMessenger,\n fiatPaymentMethod?: string,\n signal?: AbortSignal,\n): Promise<{\n batchTransactions: BatchTransaction[];\n error?: QuoteErrorInfo;\n quotes: TransactionPayQuote<Json>[];\n}> {\n const { id: transactionId } = transaction;\n const strategies = getStrategiesByName(\n getStrategies(transaction),\n (strategyName) => {\n log('Skipping unknown strategy', {\n strategy: strategyName,\n transactionId,\n });\n },\n );\n\n if (!requests?.length && !fiatPaymentMethod) {\n // A selected payment token with no conversion requests means the route is\n // direct. Return an explicit no-op quote so clients and the publish hook\n // can distinguish \"no conversion needed\" from \"quote needed but missing\".\n // Not applicable when a quote is always required, as an empty requests\n // list then means the source amounts could not be calculated.\n const noOpQuote =\n paymentToken && !isQuoteRequired\n ? buildNoOpQuote(from, paymentToken)\n : undefined;\n\n if (noOpQuote) {\n log('Built no-op quote for direct route', { transactionId });\n }\n\n return {\n batchTransactions: [],\n quotes: noOpQuote ? [noOpQuote] : [],\n };\n }\n\n const request = {\n accountSupports7702: isAccountEIP7702Compatible,\n fiatPaymentMethod,\n from,\n messenger,\n requests,\n signal,\n transaction,\n };\n\n let error: QuoteErrorInfo | undefined;\n\n for (const { name, strategy } of strategies) {\n try {\n const support = await checkStrategySupport(strategy, request);\n\n if (!support) {\n log('Strategy does not support request', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n const quotes = (await strategy.getQuotes(\n request,\n )) as TransactionPayQuote<Json>[];\n\n if (!quotes.length) {\n log('Strategy returned no quotes', { strategy: name, transactionId });\n continue;\n }\n\n const isQuoteSupported = await checkStrategyQuoteSupport(strategy, {\n messenger,\n quotes,\n signal,\n transaction,\n });\n\n if (!isQuoteSupported) {\n log('Strategy does not support quotes', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n log('Updated', { transactionId, quotes });\n\n const batchTransactions = strategy.getBatchTransactions\n ? await strategy.getBatchTransactions({\n messenger,\n quotes,\n signal,\n })\n : [];\n\n log('Batch transactions', { transactionId, batchTransactions });\n\n return {\n batchTransactions,\n quotes,\n };\n } catch (caughtError) {\n if (signal?.aborted) {\n throw caughtError;\n }\n\n error ??= isQuoteError(caughtError)\n ? caughtError.info\n : { message: (caughtError as Error).message, reason: 'no-quotes' };\n\n if (\n isQuoteError(caughtError) &&\n caughtError.info.reason === 'insufficient-source-balance' &&\n caughtError.quotes?.length\n ) {\n log('Keeping quotes despite insufficient source balance', {\n strategy: name,\n transactionId,\n });\n return {\n batchTransactions: [],\n error: caughtError.info,\n quotes: caughtError.quotes as TransactionPayQuote<Json>[],\n };\n }\n\n log('Strategy failed, trying next', {\n error: caughtError,\n strategy: name,\n transactionId,\n });\n continue;\n }\n }\n\n log('No quotes available', { transactionId });\n\n return {\n batchTransactions: [],\n error,\n quotes: [],\n };\n}\n"]}
1
+ {"version":3,"file":"quotes.js","sourceRoot":"","sources":["../../src/utils/quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAIrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAmB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAa7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,mBAAmB,EACnB,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,OAAO,EAAG,WAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;YAErE,IACE,YAAY,CAAC,WAAW,CAAC;gBACzB,WAAW,CAAC,IAAI,CAAC,MAAM,KAAK,yBAAyB,EACrD,CAAC;gBACD,GAAG,CAAC,iEAAiE,EAAE;oBACrE,QAAQ,EAAE,IAAI;oBACd,aAAa;iBACd,CAAC,CAAC;gBACH,OAAO;oBACL,iBAAiB,EAAE,EAAE;oBACrB,KAAK,EAAE,WAAW,CAAC,IAAI;oBACvB,MAAM,EAAE,EAAE;iBACX,CAAC;YACJ,CAAC;YAED,IACE,YAAY,CAAC,WAAW,CAAC;gBACzB,WAAW,CAAC,IAAI,CAAC,MAAM,KAAK,6BAA6B;gBACzD,WAAW,CAAC,MAAM,EAAE,MAAM,EAC1B,CAAC;gBACD,GAAG,CAAC,oDAAoD,EAAE;oBACxD,QAAQ,EAAE,IAAI;oBACd,aAAa;iBACd,CAAC,CAAC;gBACH,OAAO;oBACL,iBAAiB,EAAE,EAAE;oBACrB,KAAK,EAAE,WAAW,CAAC,IAAI;oBACvB,MAAM,EAAE,WAAW,CAAC,MAAqC;iBAC1D,CAAC;YACJ,CAAC;YAED,GAAG,CAAC,8BAA8B,EAAE;gBAClC,KAAK,EAAE,WAAW;gBAClB,QAAQ,EAAE,IAAI;gBACd,aAAa;aACd,CAAC,CAAC;YACH,SAAS;QACX,CAAC;IACH,CAAC;IAED,GAAG,CAAC,qBAAqB,EAAE,EAAE,aAAa,EAAE,CAAC,CAAC;IAE9C,OAAO;QACL,iBAAiB,EAAE,EAAE;QACrB,KAAK;QACL,MAAM,EAAE,EAAE;KACX,CAAC;AACJ,CAAC","sourcesContent":["import { TransactionStatus } from '@metamask/transaction-controller';\nimport type { BatchTransaction } from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { PaymentOverride, TransactionPayStrategy } from '../constants.js';\nimport { projectLogger } from '../logger.js';\nimport type {\n QuoteRequest,\n QuoteErrorInfo,\n TransactionData,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPaySourceAmount,\n TransactionPayTotals,\n TransactionPaymentToken,\n UpdateTransactionDataCallback,\n} from '../types.js';\nimport { accountSupports7702 } from './7702.js';\nimport { buildNoOpQuote } from './no-op-quote.js';\nimport {\n checkStrategyQuoteSupport,\n checkStrategySupport,\n getStrategiesByName,\n getStrategyByName,\n} from './strategy.js';\nimport {\n computeTokenAmounts,\n getLiveTokenBalance,\n getTokenFiatRate,\n} from './token.js';\nimport { calculateTotals } from './totals.js';\nimport { getTransaction, updateTransaction } from './transaction.js';\nimport { isQuoteError } from './validation.js';\n\nconst DEFAULT_REFRESH_INTERVAL = 30 * 1000; // 30 Seconds\n\nconst log = createModuleLogger(projectLogger, 'quotes');\n\nconst inFlightQuoteRequests = new Map<string, AbortController>();\n\nexport type UpdateQuotesRequest = {\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[];\n messenger: TransactionPayControllerMessenger;\n transactionData: TransactionData | undefined;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n};\n\n/**\n * Update the quotes for a specific transaction.\n *\n * Calls for the same `transactionId` are serialised: a fresh call aborts any\n * previous in-flight call so a slower stale response cannot overwrite a newer\n * one in state.\n *\n * @param request - Request parameters.\n * @returns Boolean indicating if the quotes were updated. Returns `false` when\n * the call was aborted by a subsequent call for the same transaction.\n */\nexport async function updateQuotes(\n request: UpdateQuotesRequest,\n): Promise<boolean> {\n const {\n getStrategies,\n messenger,\n transactionData,\n transactionId,\n updateTransactionData,\n } = request;\n\n const transaction = getTransaction(transactionId, messenger);\n\n if (!transaction || !transactionData) {\n throw new Error('Transaction not found');\n }\n\n if (transaction?.status !== TransactionStatus.unapproved) {\n return false;\n }\n\n log('Updating quotes', { transactionId });\n\n const {\n accountOverride,\n atomic,\n fiatPayment,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n isQuoteRequired,\n paymentOverride,\n paymentToken: originalPaymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n } = transactionData;\n\n const from = accountOverride ?? (transaction.txParams.from as Hex);\n\n const controller = abortPreviousAndCreateController(transactionId);\n const { signal } = controller;\n\n updateTransactionData(transactionId, (data) => {\n data.isLoading = true;\n data.quoteError = undefined;\n });\n\n try {\n const paymentToken = await refreshPaymentTokenBalance({\n from,\n messenger,\n paymentToken: originalPaymentToken,\n signal,\n transactionId,\n updateTransactionData,\n });\n\n if (signal.aborted) {\n log('Quote request aborted before building requests', { transactionId });\n return false;\n }\n\n const requests = buildQuoteRequests({\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount: isMaxAmount ?? false,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n transactionId,\n });\n\n const supports7702 = accountSupports7702(messenger, from);\n\n const { batchTransactions, error, quotes } = await getQuotes(\n transaction,\n from,\n requests,\n paymentToken,\n isQuoteRequired ?? false,\n supports7702,\n getStrategies,\n messenger,\n fiatPayment?.selectedPaymentMethodId,\n signal,\n );\n\n if (signal.aborted) {\n log('Quote request aborted before persisting results', { transactionId });\n return false;\n }\n\n // No-op quotes mark direct routes. They have no fees or amounts and the\n // transaction is signed and submitted locally, so totals and transaction\n // sync must treat them as \"no quotes\".\n const executableQuotes = quotes.filter(\n (quote) => quote.strategy !== TransactionPayStrategy.None,\n );\n\n const totals = calculateTotals({\n fiatPaymentAmount: fiatPayment?.amountFiat,\n messenger,\n quotes: executableQuotes as TransactionPayQuote<unknown>[],\n tokens,\n transaction,\n });\n\n log('Calculated totals', { transactionId, totals });\n\n syncTransaction({\n batchTransactions,\n selectedFiatPayment: fiatPayment?.selectedPaymentMethodId,\n hasQuotes: executableQuotes.length > 0,\n isPostQuote,\n messenger: messenger as never,\n paymentToken,\n strategy: executableQuotes[0]?.strategy,\n totals,\n transactionId,\n });\n\n updateTransactionData(transactionId, (data) => {\n data.quotes = quotes as never;\n data.quoteError = error;\n data.quotesLastUpdated = Date.now();\n data.totals = totals;\n });\n } catch (error) {\n if (signal.aborted) {\n log('Quote request aborted', { transactionId, reason: signal.reason });\n return false;\n }\n throw error;\n } finally {\n if (!signal.aborted) {\n updateTransactionData(transactionId, (data) => {\n data.isLoading = false;\n });\n }\n clearControllerIfCurrent(transactionId, controller);\n }\n\n return true;\n}\n\n/**\n * Sync batch transactions to the transaction meta.\n *\n * @param request - Request object.\n * @param request.batchTransactions - Batch transactions to sync.\n * @param request.hasQuotes - Whether MM Pay produced any quotes for this transaction.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.messenger - Messenger instance.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.selectedFiatPayment - Selected fiat payment method ID.\n * @param request.strategy - Strategy of the executable quotes.\n * @param request.totals - Calculated totals.\n * @param request.transactionId - ID of the transaction to sync.\n */\nfunction syncTransaction({\n batchTransactions,\n hasQuotes,\n isPostQuote,\n messenger,\n paymentToken,\n selectedFiatPayment,\n strategy,\n totals,\n transactionId,\n}: {\n batchTransactions: BatchTransaction[];\n selectedFiatPayment?: string;\n hasQuotes: boolean;\n isPostQuote?: boolean;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n strategy?: TransactionPayStrategy;\n totals: TransactionPayTotals;\n transactionId: string;\n}): void {\n if (!paymentToken && !selectedFiatPayment) {\n return;\n }\n\n updateTransaction(\n {\n transactionId,\n messenger: messenger as never,\n note: 'Update transaction pay data',\n },\n (tx: TransactionMeta) => {\n tx.batchTransactions = batchTransactions;\n tx.batchTransactionsOptions = {};\n\n // When MM Pay has produced quotes, it owns submission of this transaction\n // via its strategy publish hook, so the parent must be marked externally\n // signed to skip the local `KeyringController:signTransaction` call.\n // When there are no quotes (e.g. user selected the target token as the\n // payment token in a Predict flow), the transaction falls back to normal\n // local signing, so the flag is cleared to allow that.\n // If gas is sponsored, TC owns this field — it is set based on the\n // Sentinel simulation result and must not be cleared here. Same-token\n // flows (e.g. Monad mUSD withdrawal via a Money Account) produce no\n // quotes but still need external sign because the account cannot sign\n // locally.\n if (!tx.isGasFeeSponsored) {\n tx.isExternalSign = hasQuotes;\n }\n\n tx.metamaskPay = {\n bridgeFeeFiat: totals.fees.provider.usd,\n chainId: paymentToken?.chainId,\n isPostQuote,\n networkFeeFiat: totals.fees.sourceNetwork.estimate.usd,\n strategy,\n targetFiat: totals.targetAmount.usd,\n tokenAddress: paymentToken?.address,\n totalFiat: totals.total.usd,\n };\n },\n );\n}\n\n/**\n * Refresh quotes for all transactions if expired.\n *\n * @param messenger - Messenger instance.\n * @param updateTransactionData - Callback to update transaction data.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n */\nexport async function refreshQuotes(\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n): Promise<void> {\n const state = messenger.call('TransactionPayController:getState');\n const transactionIds = Object.keys(state.transactionData);\n\n for (const transactionId of transactionIds) {\n const transactionData = state.transactionData[transactionId];\n const { isLoading, quotes, quotesLastUpdated } = transactionData;\n\n if (isLoading || !quotes?.length) {\n continue;\n }\n\n // No-op quotes mark direct routes and have nothing to refresh. They are\n // regenerated whenever the transaction data changes.\n if (\n quotes.every((quote) => quote.strategy === TransactionPayStrategy.None)\n ) {\n continue;\n }\n\n const strategyName = quotes[0].strategy;\n const strategy = getStrategyByName(strategyName);\n\n const refreshInterval =\n (await strategy.getRefreshInterval?.({\n chainId: quotes[0].request.sourceChainId,\n messenger,\n })) ?? DEFAULT_REFRESH_INTERVAL;\n\n const isExpired = Date.now() - (quotesLastUpdated ?? 0) > refreshInterval;\n\n if (!isExpired) {\n continue;\n }\n\n const isUpdated = await updateQuotes({\n getStrategies,\n messenger,\n transactionData,\n transactionId,\n updateTransactionData,\n });\n\n if (isUpdated) {\n log('Refreshed quotes', { transactionId, strategy: strategyName });\n }\n }\n}\n\nfunction abortPreviousAndCreateController(\n transactionId: string,\n): AbortController {\n const previous = inFlightQuoteRequests.get(transactionId);\n\n if (previous && !previous.signal.aborted) {\n log('Aborting previous quote request', { transactionId });\n previous.abort(new Error('Superseded by newer quote request'));\n }\n\n const controller = new AbortController();\n inFlightQuoteRequests.set(transactionId, controller);\n return controller;\n}\n\nfunction clearControllerIfCurrent(\n transactionId: string,\n controller: AbortController,\n): void {\n if (inFlightQuoteRequests.get(transactionId) === controller) {\n inFlightQuoteRequests.delete(transactionId);\n }\n}\n\n/**\n * Build quote requests required to retrieve quotes.\n *\n * @param request - Request parameters.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction.\n * @param request.tokens - Required tokens for the transaction.\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests.\n */\nfunction buildQuoteRequests({\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n transactionId,\n}: {\n atomic?: boolean;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n isPostQuote?: boolean;\n paymentOverride?: PaymentOverride;\n paymentToken: TransactionPaymentToken | undefined;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n tokens: TransactionPayRequiredToken[];\n transactionId: string;\n}): QuoteRequest[] {\n if (!paymentToken) {\n return [];\n }\n\n if (isPostQuote) {\n return buildPostQuoteRequests({\n atomic,\n destinationToken: paymentToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n });\n }\n\n // Standard flow: source = paymentToken, target = required tokens\n const requests = (sourceAmounts ?? []).map((sourceAmount) => {\n const token = tokens.find(\n (singleToken) => singleToken.address === sourceAmount.targetTokenAddress,\n ) as TransactionPayRequiredToken;\n\n return {\n atomic,\n from,\n isMaxAmount,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: paymentToken.balanceRaw,\n sourceChainId: paymentToken.chainId,\n sourceTokenAddress: paymentToken.address,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: token.allowUnderMinimum ? '0' : token.amountRaw,\n targetChainId: token.chainId,\n targetTokenAddress: token.address,\n };\n });\n\n if (!requests.length) {\n log('No quote requests', { transactionId });\n }\n\n return requests;\n}\n\n/**\n * Build quote requests for post-quote flows.\n * In this flow, the source is the transaction's required token,\n * and the target is the user's selected destination token (paymentToken).\n *\n * @param request - Request parameters.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.destinationToken - Destination token (paymentToken in post-quote mode).\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction (includes source token info).\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests for post-quote flow.\n */\nfunction buildPostQuoteRequests({\n atomic,\n destinationToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n}: {\n atomic?: boolean;\n destinationToken: TransactionPaymentToken;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n paymentOverride?: PaymentOverride;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n transactionId: string;\n}): QuoteRequest[] {\n // Find the source amount where targetTokenAddress matches the destination token\n const sourceAmount = sourceAmounts?.find(\n (amount) =>\n amount.targetTokenAddress.toLowerCase() ===\n destinationToken.address.toLowerCase(),\n );\n\n // Same-token-same-chain cases are already filtered in source-amounts.ts\n if (\n !sourceAmount?.sourceBalanceRaw ||\n !sourceAmount.sourceChainId ||\n !sourceAmount.sourceTokenAddress\n ) {\n log('No valid source amount found for post-quote request', {\n transactionId,\n });\n return [];\n }\n\n const request: QuoteRequest = {\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote: true,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: sourceAmount.sourceBalanceRaw,\n sourceChainId: sourceAmount.sourceChainId,\n sourceTokenAddress: sourceAmount.sourceTokenAddress,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: '0',\n targetChainId: destinationToken.chainId,\n targetTokenAddress: destinationToken.address,\n };\n\n log('Post-quote request built', { transactionId, request });\n\n // Currently only single token post-quote flows are supported.\n // Multiple token support would require multiple quotes for each required token.\n return [request];\n}\n\nasync function refreshPaymentTokenBalance({\n from,\n messenger,\n paymentToken,\n signal,\n transactionId,\n updateTransactionData,\n}: {\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n signal: AbortSignal;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n}): Promise<TransactionPaymentToken | undefined> {\n if (!paymentToken) {\n return undefined;\n }\n\n try {\n const fiatRates = getTokenFiatRate(\n messenger,\n paymentToken.address,\n paymentToken.chainId,\n );\n\n if (!fiatRates) {\n return paymentToken;\n }\n\n const liveBalance = await getLiveTokenBalance(\n messenger,\n from,\n paymentToken.chainId,\n paymentToken.address,\n );\n\n if (signal.aborted) {\n log('Payment token balance refresh aborted', { transactionId });\n return paymentToken;\n }\n\n const {\n raw: balanceRaw,\n human: balanceHuman,\n usd: balanceUsd,\n fiat: balanceFiat,\n } = computeTokenAmounts(liveBalance, paymentToken.decimals, fiatRates);\n\n const updatedToken = {\n ...paymentToken,\n balanceFiat,\n balanceHuman,\n balanceRaw,\n balanceUsd,\n };\n\n updateTransactionData(transactionId, (data) => {\n data.paymentToken = updatedToken;\n });\n\n log('Refreshed payment token balance', { transactionId, balanceRaw });\n\n return updatedToken;\n } catch (error) {\n log('Failed to refresh payment token balance', { transactionId, error });\n return paymentToken;\n }\n}\n\n/**\n * Retrieve quotes for a transaction.\n *\n * @param transaction - Transaction metadata.\n * @param from - Resolved wallet address (`accountOverride ?? txParams.from`).\n * @param requests - Quote requests.\n * @param paymentToken - Selected payment token, if any.\n * @param isQuoteRequired - Whether a quote is always required for the transaction.\n * @param isAccountEIP7702Compatible - Whether the account supports EIP-7702.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n * @param messenger - Controller messenger.\n * @param fiatPaymentMethod - Selected fiat payment method ID, if applicable.\n * @param signal - Signal that aborts when the quote request is superseded.\n * @returns An object containing batch transactions and quotes.\n */\nasync function getQuotes(\n transaction: TransactionMeta,\n from: Hex,\n requests: QuoteRequest[],\n paymentToken: TransactionPaymentToken | undefined,\n isQuoteRequired: boolean,\n isAccountEIP7702Compatible: boolean,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n messenger: TransactionPayControllerMessenger,\n fiatPaymentMethod?: string,\n signal?: AbortSignal,\n): Promise<{\n batchTransactions: BatchTransaction[];\n error?: QuoteErrorInfo;\n quotes: TransactionPayQuote<Json>[];\n}> {\n const { id: transactionId } = transaction;\n const strategies = getStrategiesByName(\n getStrategies(transaction),\n (strategyName) => {\n log('Skipping unknown strategy', {\n strategy: strategyName,\n transactionId,\n });\n },\n );\n\n if (!requests?.length && !fiatPaymentMethod) {\n // A selected payment token with no conversion requests means the route is\n // direct. Return an explicit no-op quote so clients and the publish hook\n // can distinguish \"no conversion needed\" from \"quote needed but missing\".\n // Not applicable when a quote is always required, as an empty requests\n // list then means the source amounts could not be calculated.\n const noOpQuote =\n paymentToken && !isQuoteRequired\n ? buildNoOpQuote(from, paymentToken)\n : undefined;\n\n if (noOpQuote) {\n log('Built no-op quote for direct route', { transactionId });\n }\n\n return {\n batchTransactions: [],\n quotes: noOpQuote ? [noOpQuote] : [],\n };\n }\n\n const request = {\n accountSupports7702: isAccountEIP7702Compatible,\n fiatPaymentMethod,\n from,\n messenger,\n requests,\n signal,\n transaction,\n };\n\n let error: QuoteErrorInfo | undefined;\n\n for (const { name, strategy } of strategies) {\n try {\n const support = await checkStrategySupport(strategy, request);\n\n if (!support) {\n log('Strategy does not support request', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n const quotes = (await strategy.getQuotes(\n request,\n )) as TransactionPayQuote<Json>[];\n\n if (!quotes.length) {\n log('Strategy returned no quotes', { strategy: name, transactionId });\n continue;\n }\n\n const isQuoteSupported = await checkStrategyQuoteSupport(strategy, {\n messenger,\n quotes,\n signal,\n transaction,\n });\n\n if (!isQuoteSupported) {\n log('Strategy does not support quotes', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n log('Updated', { transactionId, quotes });\n\n const batchTransactions = strategy.getBatchTransactions\n ? await strategy.getBatchTransactions({\n messenger,\n quotes,\n signal,\n })\n : [];\n\n log('Batch transactions', { transactionId, batchTransactions });\n\n return {\n batchTransactions,\n quotes,\n };\n } catch (caughtError) {\n if (signal?.aborted) {\n throw caughtError;\n }\n\n error ??= isQuoteError(caughtError)\n ? caughtError.info\n : { message: (caughtError as Error).message, reason: 'no-quotes' };\n\n if (\n isQuoteError(caughtError) &&\n caughtError.info.reason === 'atomic-promotion-failed'\n ) {\n log('Terminal atomic-promotion-failed, aborting remaining strategies', {\n strategy: name,\n transactionId,\n });\n return {\n batchTransactions: [],\n error: caughtError.info,\n quotes: [],\n };\n }\n\n if (\n isQuoteError(caughtError) &&\n caughtError.info.reason === 'insufficient-source-balance' &&\n caughtError.quotes?.length\n ) {\n log('Keeping quotes despite insufficient source balance', {\n strategy: name,\n transactionId,\n });\n return {\n batchTransactions: [],\n error: caughtError.info,\n quotes: caughtError.quotes as TransactionPayQuote<Json>[],\n };\n }\n\n log('Strategy failed, trying next', {\n error: caughtError,\n strategy: name,\n transactionId,\n });\n continue;\n }\n }\n\n log('No quotes available', { transactionId });\n\n return {\n batchTransactions: [],\n error,\n quotes: [],\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/transaction-pay-controller",
3
- "version": "28.0.2-preview-98c551e",
3
+ "version": "28.0.2-preview-e81860e6b",
4
4
  "description": "Manages alternate payment strategies to provide required funds for transactions in MetaMask",
5
5
  "keywords": [
6
6
  "Ethereum",