@metamask-previews/transaction-pay-controller 30.1.0-preview-51ecba2 → 30.1.0-preview-b50d61887
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 +0 -8
- package/dist/strategy/server/server-quotes.d.ts.map +1 -1
- package/dist/strategy/server/server-quotes.js +51 -163
- package/dist/strategy/server/server-quotes.js.map +1 -1
- package/dist/strategy/server/server-submit.d.ts.map +1 -1
- package/dist/strategy/server/server-submit.js +16 -118
- package/dist/strategy/server/server-submit.js.map +1 -1
- package/dist/strategy/server/server-support.d.ts +3 -1
- package/dist/strategy/server/server-support.d.ts.map +1 -1
- package/dist/strategy/server/server-support.js +5 -0
- package/dist/strategy/server/server-support.js.map +1 -1
- package/dist/strategy/server/types.d.ts +0 -7
- package/dist/strategy/server/types.d.ts.map +1 -1
- package/dist/strategy/server/types.js.map +1 -1
- package/package.json +1 -1
- package/dist/strategy/server/deposit-step.d.ts +0 -18
- package/dist/strategy/server/deposit-step.d.ts.map +0 -1
- package/dist/strategy/server/deposit-step.js +0 -37
- package/dist/strategy/server/deposit-step.js.map +0 -1
|
@@ -6,13 +6,11 @@ import { projectLogger } from '../../logger.js';
|
|
|
6
6
|
import { accountSupports7702 } from '../../utils/7702.js';
|
|
7
7
|
import { getServerPollingInterval, getServerPollingTimeout, } from '../../utils/feature-flags.js';
|
|
8
8
|
import { GasPaymentMode, logGasPaymentOutcome, resolveGasPayment, } from '../../utils/gas-payment.js';
|
|
9
|
-
import { submitPolymarketWithdraw, sweepPolymarketDepositWallet, } from '../../utils/polymarket/withdraw.js';
|
|
10
9
|
import { getNetworkClientId } from '../../utils/provider.js';
|
|
11
10
|
import { submitSecondLeg } from '../../utils/second-leg.js';
|
|
12
11
|
import { getLiveTokenBalance, normalizeTokenAddress, TokenAddressTarget, } from '../../utils/token.js';
|
|
13
12
|
import { collectTransactionIds, getTransaction, updateTransaction, waitForTransactionConfirmed, } from '../../utils/transaction.js';
|
|
14
13
|
import { RELAY_DEPOSIT_TYPES } from '../relay/constants.js';
|
|
15
|
-
import { getServerDepositData } from './deposit-step.js';
|
|
16
14
|
import { getServerStatus, submitServerIntent } from './server-api.js';
|
|
17
15
|
import { ServerStatus } from './types.js';
|
|
18
16
|
const log = createModuleLogger(projectLogger, 'server-strategy');
|
|
@@ -59,39 +57,17 @@ async function executeSingleServerQuote(quote, messenger, transaction) {
|
|
|
59
57
|
}, (tx) => {
|
|
60
58
|
tx.txParams.nonce = undefined;
|
|
61
59
|
});
|
|
62
|
-
const isDepositWallet = Boolean(quote.request.isPolymarketDepositWallet);
|
|
63
60
|
// Phase 1: off-chain signature steps (e.g. Relay authorize, HyperLiquid deposit).
|
|
64
61
|
// Use quote.request.from (resolved accountOverride) not transaction.txParams.from.
|
|
65
62
|
const signatureSteps = quote.original.steps.filter(isSignatureStep);
|
|
66
63
|
for (const step of signatureSteps) {
|
|
67
64
|
await submitSignatureStep(step, quote.request.from, messenger);
|
|
68
65
|
}
|
|
69
|
-
// Phase 2: on-chain transaction steps (if any).
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
}
|
|
75
|
-
else {
|
|
76
|
-
await submitTransactionSteps(quote, messenger, transaction);
|
|
77
|
-
}
|
|
78
|
-
// Phase 3: poll until the intent settles on the target chain.
|
|
79
|
-
const completion = await waitForServerCompletion(quote.original, messenger, transaction.id);
|
|
80
|
-
log('Server request completed', completion);
|
|
81
|
-
// A deposit wallet sweeps leftover USDC.e back into pUSD whatever the
|
|
82
|
-
// outcome, so a refund is restored before the failure is reported.
|
|
83
|
-
if (preSubmitUsdceBalance !== undefined) {
|
|
84
|
-
await sweepPolymarketDepositWallet({
|
|
85
|
-
from: quote.request.from,
|
|
86
|
-
isRefund: completion.status === ServerStatus.Refunded,
|
|
87
|
-
messenger,
|
|
88
|
-
preSubmitUsdceBalance,
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
if (completion.status !== ServerStatus.Confirmed) {
|
|
92
|
-
throw new Error(`Server intent ${completion.status.toLowerCase()}`);
|
|
93
|
-
}
|
|
94
|
-
const targetHash = completion.targetHash ?? MISSING_TARGET_HASH;
|
|
66
|
+
// Phase 2: on-chain transaction steps (if any).
|
|
67
|
+
await submitTransactionSteps(quote, messenger, transaction);
|
|
68
|
+
// Phase 3: poll until the intent is confirmed on the target chain.
|
|
69
|
+
const targetHash = await waitForServerCompletion(quote.original, messenger, transaction.id);
|
|
70
|
+
log('Server request completed', targetHash);
|
|
95
71
|
// Phase 4: submit the calls the quote could not execute itself, now that the
|
|
96
72
|
// funds have settled on the target chain.
|
|
97
73
|
const secondLegHash = quote.requiresSecondLeg
|
|
@@ -119,20 +95,10 @@ async function executeSingleServerQuote(quote, messenger, transaction) {
|
|
|
119
95
|
* @returns Hash of the second-leg transaction, if available.
|
|
120
96
|
*/
|
|
121
97
|
async function submitServerSecondLeg(quote, messenger, transaction, targetHash) {
|
|
122
|
-
const { from,
|
|
98
|
+
const { from, recipient, targetChainId, targetTokenAddress } = quote.request;
|
|
123
99
|
const { transactionHash } = await submitSecondLeg({
|
|
124
100
|
chainId: targetChainId,
|
|
125
101
|
from: recipient ?? from,
|
|
126
|
-
// Post-quote flows carry no calls of their own, so the payment override
|
|
127
|
-
// builds the batch for the settled amount.
|
|
128
|
-
getCalls: isPostQuote
|
|
129
|
-
? async (sourceAmountRaw) => await buildPaymentOverrideCalls({
|
|
130
|
-
messenger,
|
|
131
|
-
quote,
|
|
132
|
-
sourceAmountRaw,
|
|
133
|
-
transaction,
|
|
134
|
-
})
|
|
135
|
-
: undefined,
|
|
136
102
|
messenger,
|
|
137
103
|
settlementHash: targetHash === MISSING_TARGET_HASH ? undefined : targetHash,
|
|
138
104
|
tokenAddress: targetTokenAddress,
|
|
@@ -140,54 +106,6 @@ async function submitServerSecondLeg(quote, messenger, transaction, targetHash)
|
|
|
140
106
|
});
|
|
141
107
|
return transactionHash;
|
|
142
108
|
}
|
|
143
|
-
/**
|
|
144
|
-
* Build the second-leg batch from the payment override for the settled amount.
|
|
145
|
-
*
|
|
146
|
-
* @param options - Build options.
|
|
147
|
-
* @param options.messenger - Controller messenger.
|
|
148
|
-
* @param options.quote - Server quote that settled.
|
|
149
|
-
* @param options.sourceAmountRaw - Settled amount in raw units.
|
|
150
|
-
* @param options.transaction - Original transaction meta.
|
|
151
|
-
* @returns The batch calls.
|
|
152
|
-
*/
|
|
153
|
-
async function buildPaymentOverrideCalls({ messenger, quote, sourceAmountRaw, transaction, }) {
|
|
154
|
-
const { transactionData } = messenger.call('TransactionPayController:getState');
|
|
155
|
-
const amount = new BigNumber(sourceAmountRaw)
|
|
156
|
-
.shiftedBy(-quote.original.output.decimals)
|
|
157
|
-
.toFixed();
|
|
158
|
-
const { calls } = await messenger.call('TransactionPayController:getPaymentOverrideData', {
|
|
159
|
-
amount,
|
|
160
|
-
transaction,
|
|
161
|
-
transactionData: transactionData[transaction.id],
|
|
162
|
-
});
|
|
163
|
-
return calls;
|
|
164
|
-
}
|
|
165
|
-
/**
|
|
166
|
-
* Unwrap the deposit wallet's pUSD straight to the provider deposit address.
|
|
167
|
-
*
|
|
168
|
-
* @param quote - Server quote.
|
|
169
|
-
* @param messenger - Controller messenger.
|
|
170
|
-
* @param transaction - Original transaction meta.
|
|
171
|
-
* @returns The deposit wallet's USDC.e balance before submission, so the sweep
|
|
172
|
-
* can detect a refund.
|
|
173
|
-
*/
|
|
174
|
-
async function submitDepositWalletWithdraw(quote, messenger, transaction) {
|
|
175
|
-
const { preSubmitUsdceBalance, sourceHash } = await submitPolymarketWithdraw({
|
|
176
|
-
depositData: getServerDepositData(quote.original),
|
|
177
|
-
from: quote.request.from,
|
|
178
|
-
messenger,
|
|
179
|
-
sourceAmountRaw: quote.sourceAmount.raw,
|
|
180
|
-
});
|
|
181
|
-
updateTransaction({
|
|
182
|
-
transactionId: transaction.id,
|
|
183
|
-
messenger,
|
|
184
|
-
note: 'Add source hash from deposit wallet withdraw',
|
|
185
|
-
}, (tx) => {
|
|
186
|
-
tx.metamaskPay ??= {};
|
|
187
|
-
tx.metamaskPay.sourceHash = sourceHash;
|
|
188
|
-
});
|
|
189
|
-
return preSubmitUsdceBalance;
|
|
190
|
-
}
|
|
191
109
|
/**
|
|
192
110
|
* Submit the on-chain transaction steps for a server quote.
|
|
193
111
|
*
|
|
@@ -252,16 +170,11 @@ async function submitTransactionSteps(quote, messenger, transaction) {
|
|
|
252
170
|
* @returns Complete ordered array of transactions for submission.
|
|
253
171
|
*/
|
|
254
172
|
async function buildStepTransactions(quote, transactionSteps, transaction, messenger) {
|
|
255
|
-
const {
|
|
173
|
+
const { from, isPostQuote, paymentOverride } = quote.request;
|
|
256
174
|
const { gasLimits, maxFeePerGas, maxPriorityFeePerGas } = quote.original.client;
|
|
257
175
|
const originalType = getEffectiveTransactionType(transaction);
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
const stepGasLimits = gasLimits.slice(Math.max(gasLimits.length - transactionSteps.length, 0));
|
|
261
|
-
const quoteStepTransactions = transactionSteps.map((step, i) => buildStepTransaction(step, i, transactionSteps.length, from, stepGasLimits, maxFeePerGas, maxPriorityFeePerGas, originalType));
|
|
262
|
-
// Non-atomic flows run the override calls as a second leg once the funds
|
|
263
|
-
// settle, so prepending them here would run them twice.
|
|
264
|
-
if (paymentOverride && atomic !== false) {
|
|
176
|
+
const quoteStepTransactions = transactionSteps.map((step, i) => buildStepTransaction(step, i, transactionSteps.length, from, gasLimits, maxFeePerGas, maxPriorityFeePerGas, originalType));
|
|
177
|
+
if (paymentOverride) {
|
|
265
178
|
return prependPaymentOverrideTransactions(quoteStepTransactions, quote, transaction, messenger);
|
|
266
179
|
}
|
|
267
180
|
if (isPostQuote && transaction.txParams.to) {
|
|
@@ -416,7 +329,7 @@ async function prependPaymentOverrideTransactions(quoteStepTransactions, quote,
|
|
|
416
329
|
async function prependPostQuoteTransactions(quoteStepTransactions, quote, transaction, messenger) {
|
|
417
330
|
const hasAccountOverride = quote.request.from.toLowerCase() !==
|
|
418
331
|
transaction.txParams.from.toLowerCase();
|
|
419
|
-
const {
|
|
332
|
+
const { maxFeePerGas, maxPriorityFeePerGas } = quote.original.client;
|
|
420
333
|
let prependedParams;
|
|
421
334
|
if (hasAccountOverride) {
|
|
422
335
|
prependedParams = await buildDelegatedOriginalParams(transaction, messenger);
|
|
@@ -435,11 +348,6 @@ async function prependPostQuoteTransactions(quoteStepTransactions, quote, transa
|
|
|
435
348
|
prependedParams.maxPriorityFeePerGas = maxPriorityFeePerGas
|
|
436
349
|
? toHex(maxPriorityFeePerGas)
|
|
437
350
|
: undefined;
|
|
438
|
-
// The original transaction is estimated ahead of the quote steps, so it owns
|
|
439
|
-
// the leading limit when each transaction has its own.
|
|
440
|
-
if (gasLimits.length > quoteStepTransactions.length) {
|
|
441
|
-
prependedParams.gas = toHex(gasLimits[0]);
|
|
442
|
-
}
|
|
443
351
|
log('Prepending post-quote original tx', { hasAccountOverride });
|
|
444
352
|
return [{ params: prependedParams }, ...quoteStepTransactions];
|
|
445
353
|
}
|
|
@@ -714,17 +622,6 @@ function deriveEIP712DomainType(domain) {
|
|
|
714
622
|
.filter((key) => Object.prototype.hasOwnProperty.call(domain, key))
|
|
715
623
|
.map((key) => DOMAIN_FIELD_MAP[key]);
|
|
716
624
|
}
|
|
717
|
-
/**
|
|
718
|
-
* Poll the server until the intent reaches a terminal status.
|
|
719
|
-
*
|
|
720
|
-
* Failures are returned rather than thrown so callers can clean up first, such
|
|
721
|
-
* as sweeping a deposit wallet refund. Timeouts still throw.
|
|
722
|
-
*
|
|
723
|
-
* @param quote - Server quote being polled.
|
|
724
|
-
* @param messenger - Controller messenger.
|
|
725
|
-
* @param transactionId - ID of the parent transaction.
|
|
726
|
-
* @returns The terminal status and the target-chain hash when reported.
|
|
727
|
-
*/
|
|
728
625
|
async function waitForServerCompletion(quote, messenger, transactionId) {
|
|
729
626
|
const pollingInterval = getServerPollingInterval(messenger);
|
|
730
627
|
const pollingTimeout = getServerPollingTimeout(messenger);
|
|
@@ -761,11 +658,12 @@ async function waitForServerCompletion(quote, messenger, transactionId) {
|
|
|
761
658
|
tx.metamaskPay.sourceHash = sourceHash;
|
|
762
659
|
});
|
|
763
660
|
}
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
661
|
+
if (statusResponse.status === ServerStatus.Confirmed) {
|
|
662
|
+
return statusResponse.targetHash ?? MISSING_TARGET_HASH;
|
|
663
|
+
}
|
|
664
|
+
if (statusResponse.status === ServerStatus.Failed ||
|
|
665
|
+
statusResponse.status === ServerStatus.Refunded) {
|
|
666
|
+
throw new Error(`Server intent ${statusResponse.status.toLowerCase()}`);
|
|
769
667
|
}
|
|
770
668
|
}
|
|
771
669
|
if (hasTimeout && Date.now() - startTime >= pollingTimeout) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-submit.js","sourceRoot":"","sources":["../../../src/strategy/server/server-submit.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,eAAe,EACf,KAAK,GACN,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAQpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAMhD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EACL,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,eA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AAC;YACvE,MAAM,IAAI,KAAK,CAAC,2BAA2B,YAAY,EAAE,CAAC,CAAC;QAC7D,CAAC;QAED,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC;IACvE,CAAC;AACH,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n successfulFetch,\n toHex,\n} from '@metamask/controller-utils';\nimport { SignTypedDataVersion } from '@metamask/keyring-controller';\nimport type {\n BatchTransactionParams,\n TransactionMeta,\n TransactionParams,\n TransactionType,\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 PayStrategyExecuteRequest,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types.js';\nimport { accountSupports7702 } from '../../utils/7702.js';\nimport {\n getServerPollingInterval,\n getServerPollingTimeout,\n} from '../../utils/feature-flags.js';\nimport type { GasPayment } from '../../utils/gas-payment.js';\nimport {\n GasPaymentMode,\n logGasPaymentOutcome,\n resolveGasPayment,\n} from '../../utils/gas-payment.js';\nimport {\n submitPolymarketWithdraw,\n sweepPolymarketDepositWallet,\n} from '../../utils/polymarket/withdraw.js';\nimport { getNetworkClientId } from '../../utils/provider.js';\nimport { submitSecondLeg } from '../../utils/second-leg.js';\nimport {\n getLiveTokenBalance,\n normalizeTokenAddress,\n TokenAddressTarget,\n} from '../../utils/token.js';\nimport {\n collectTransactionIds,\n getTransaction,\n updateTransaction,\n waitForTransactionConfirmed,\n} from '../../utils/transaction.js';\nimport { RELAY_DEPOSIT_TYPES } from '../relay/constants.js';\nimport { getServerDepositData } from './deposit-step.js';\nimport { getServerStatus, submitServerIntent } from './server-api.js';\nimport type {\n ServerQuote,\n ServerSignatureStep,\n ServerTransactionStep,\n ServerStatusResponse,\n ServerSubmitRequest,\n} from './types.js';\nimport { ServerStatus } from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'server-strategy');\n\n/**\n * Placeholder returned when an intent confirms without reporting a\n * target-chain transaction hash, so there is no settlement to read amounts\n * from.\n */\nconst MISSING_TARGET_HASH = '0x' as Hex;\n\nconst DOMAIN_FIELD_MAP: Record<string, { name: string; type: string }> = {\n name: { name: 'name', type: 'string' },\n version: { name: 'version', type: 'string' },\n chainId: { name: 'chainId', type: 'uint256' },\n verifyingContract: { name: 'verifyingContract', type: 'address' },\n salt: { name: 'salt', type: 'bytes32' },\n};\n\n/**\n * A transaction to submit for a single quote step.\n *\n * The semantic transaction type is held alongside `params` rather than within\n * it, since `TransactionParams.type` is the EVM envelope type (`0x0` - `0x4`)\n * and is rejected by the transaction controller if given anything else.\n */\ntype StepTransaction = {\n params: TransactionParams;\n type?: TransactionType;\n};\n\n/** Terminal outcome of a server intent. */\ntype ServerCompletion = {\n status: ServerStatus.Confirmed | ServerStatus.Failed | ServerStatus.Refunded;\n targetHash?: Hex;\n};\n\nfunction isSignatureStep(\n step: ServerQuote['steps'][number],\n): step is ServerSignatureStep {\n return step.type === 'signature';\n}\n\nfunction isTransactionStep(\n step: ServerQuote['steps'][number],\n): step is ServerTransactionStep {\n return step.type === 'transaction';\n}\n\n/**\n * Submits server intent quotes.\n *\n * @param request - Request object.\n * @returns An object containing the transaction hash if available.\n */\nexport async function submitServerQuotes(\n request: PayStrategyExecuteRequest<ServerQuote>,\n): Promise<{ transactionHash?: Hex }> {\n log('Executing server quotes', request);\n\n const { quotes, messenger, transaction } = request;\n\n let transactionHash: Hex | undefined;\n\n for (const quote of quotes) {\n ({ transactionHash } = await executeSingleServerQuote(\n quote,\n messenger,\n transaction,\n ));\n }\n\n return { transactionHash };\n}\n\nasync function executeSingleServerQuote(\n quote: TransactionPayQuote<ServerQuote>,\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n): Promise<{ transactionHash?: Hex }> {\n log('Executing single server quote', quote);\n\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Remove nonce from skipped transaction',\n },\n (tx) => {\n tx.txParams.nonce = undefined;\n },\n );\n\n const isDepositWallet = Boolean(quote.request.isPolymarketDepositWallet);\n\n // Phase 1: off-chain signature steps (e.g. Relay authorize, HyperLiquid deposit).\n // Use quote.request.from (resolved accountOverride) not transaction.txParams.from.\n const signatureSteps = quote.original.steps.filter(isSignatureStep);\n\n for (const step of signatureSteps) {\n await submitSignatureStep(step, quote.request.from, messenger);\n }\n\n // Phase 2: on-chain transaction steps (if any). A deposit wallet withdraw\n // replaces them with an unwrap straight to the provider deposit address.\n let preSubmitUsdceBalance: bigint | undefined;\n\n if (isDepositWallet) {\n preSubmitUsdceBalance = await submitDepositWalletWithdraw(\n quote,\n messenger,\n transaction,\n );\n } else {\n await submitTransactionSteps(quote, messenger, transaction);\n }\n\n // Phase 3: poll until the intent settles on the target chain.\n const completion = await waitForServerCompletion(\n quote.original,\n messenger,\n transaction.id,\n );\n\n log('Server request completed', completion);\n\n // A deposit wallet sweeps leftover USDC.e back into pUSD whatever the\n // outcome, so a refund is restored before the failure is reported.\n if (preSubmitUsdceBalance !== undefined) {\n await sweepPolymarketDepositWallet({\n from: quote.request.from,\n isRefund: completion.status === ServerStatus.Refunded,\n messenger,\n preSubmitUsdceBalance,\n });\n }\n\n if (completion.status !== ServerStatus.Confirmed) {\n throw new Error(`Server intent ${completion.status.toLowerCase()}`);\n }\n\n const targetHash = completion.targetHash ?? MISSING_TARGET_HASH;\n\n // Phase 4: submit the calls the quote could not execute itself, now that the\n // funds have settled on the target chain.\n const secondLegHash = quote.requiresSecondLeg\n ? await submitServerSecondLeg(quote, messenger, transaction, targetHash)\n : undefined;\n\n // Only complete once every leg has landed, so a failed second leg does not\n // leave the parent transaction flagged as achieved.\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Intent complete after Server completion',\n },\n (tx) => {\n tx.isIntentComplete = true;\n },\n );\n\n return { transactionHash: secondLegHash ?? targetHash };\n}\n\n/**\n * Submit the calls a server quote could not execute itself, from the account\n * the funds settled on.\n *\n * @param quote - Server quote.\n * @param messenger - Controller messenger.\n * @param transaction - Original transaction meta.\n * @param targetHash - Hash of the settlement on the target chain.\n * @returns Hash of the second-leg transaction, if available.\n */\nasync function submitServerSecondLeg(\n quote: TransactionPayQuote<ServerQuote>,\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n targetHash: Hex | undefined,\n): Promise<Hex | undefined> {\n const { from, isPostQuote, recipient, targetChainId, targetTokenAddress } =\n quote.request;\n\n const { transactionHash } = await submitSecondLeg({\n chainId: targetChainId,\n from: recipient ?? from,\n // Post-quote flows carry no calls of their own, so the payment override\n // builds the batch for the settled amount.\n getCalls: isPostQuote\n ? async (sourceAmountRaw): Promise<BatchTransactionParams[]> =>\n await buildPaymentOverrideCalls({\n messenger,\n quote,\n sourceAmountRaw,\n transaction,\n })\n : undefined,\n messenger,\n settlementHash: targetHash === MISSING_TARGET_HASH ? undefined : targetHash,\n tokenAddress: targetTokenAddress,\n transaction,\n });\n\n return transactionHash;\n}\n\n/**\n * Build the second-leg batch from the payment override for the settled amount.\n *\n * @param options - Build options.\n * @param options.messenger - Controller messenger.\n * @param options.quote - Server quote that settled.\n * @param options.sourceAmountRaw - Settled amount in raw units.\n * @param options.transaction - Original transaction meta.\n * @returns The batch calls.\n */\nasync function buildPaymentOverrideCalls({\n messenger,\n quote,\n sourceAmountRaw,\n transaction,\n}: {\n messenger: TransactionPayControllerMessenger;\n quote: TransactionPayQuote<ServerQuote>;\n sourceAmountRaw: string;\n transaction: TransactionMeta;\n}): Promise<BatchTransactionParams[]> {\n const { transactionData } = messenger.call(\n 'TransactionPayController:getState',\n );\n\n const amount = new BigNumber(sourceAmountRaw)\n .shiftedBy(-quote.original.output.decimals)\n .toFixed();\n\n const { calls } = await messenger.call(\n 'TransactionPayController:getPaymentOverrideData',\n {\n amount,\n transaction,\n transactionData: transactionData[transaction.id],\n },\n );\n\n return calls;\n}\n\n/**\n * Unwrap the deposit wallet's pUSD straight to the provider deposit address.\n *\n * @param quote - Server quote.\n * @param messenger - Controller messenger.\n * @param transaction - Original transaction meta.\n * @returns The deposit wallet's USDC.e balance before submission, so the sweep\n * can detect a refund.\n */\nasync function submitDepositWalletWithdraw(\n quote: TransactionPayQuote<ServerQuote>,\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n): Promise<bigint> {\n const { preSubmitUsdceBalance, sourceHash } = await submitPolymarketWithdraw({\n depositData: getServerDepositData(quote.original),\n from: quote.request.from,\n messenger,\n sourceAmountRaw: quote.sourceAmount.raw,\n });\n\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Add source hash from deposit wallet withdraw',\n },\n (tx) => {\n tx.metamaskPay ??= {};\n tx.metamaskPay.sourceHash = sourceHash;\n },\n );\n\n return preSubmitUsdceBalance;\n}\n\n/**\n * Submit the on-chain transaction steps for a server quote.\n *\n * Validates the source balance, builds the complete set of transactions (including\n * any post-quote or payment-override prepends), then dispatches to the\n * gasless execute path or TransactionController depending on the quote.\n *\n * No-ops when the quote has no transaction steps (signature-only flows).\n *\n * @param quote - Server quote.\n * @param messenger - Controller messenger.\n * @param transaction - Original transaction meta.\n */\nasync function submitTransactionSteps(\n quote: TransactionPayQuote<ServerQuote>,\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n): Promise<void> {\n const transactionSteps = quote.original.steps.filter(isTransactionStep);\n\n if (transactionSteps.length === 0) {\n // Signature-only quotes (all steps are signature steps, no transaction\n // steps) have nothing to submit on-chain even when gasless is false.\n const hasSignatureSteps = quote.original.steps.some(isSignatureStep);\n if (!quote.original.gasless && !hasSignatureSteps) {\n throw new Error('Server quote has no steps to submit');\n }\n return;\n }\n\n const { isHyperliquidSource, isPostQuote, paymentOverride } = quote.request;\n\n // Skip balance check for HyperLiquid source flows (no on-chain debit),\n // post-quote flows (funds come from the Safe after the original tx executes),\n // and payment-override flows (funds are supplied by the override account).\n if (!isHyperliquidSource && !isPostQuote && !paymentOverride) {\n await validateSourceBalance(quote, messenger);\n }\n\n const stepTransactions = await buildStepTransactions(\n quote,\n transactionSteps,\n transaction,\n messenger,\n );\n\n const gasPayment = resolveGasPayment({\n isDelegated: quote.original.gasless,\n isSourceGasFeeToken: quote.fees.isSourceGasFeeToken,\n sourceTokenAddress: quote.request.sourceTokenAddress,\n sponsorship: {\n accountSupports7702: accountSupports7702(messenger, quote.request.from),\n request: quote.request,\n transaction,\n },\n });\n\n if (gasPayment.mode === GasPaymentMode.Delegation) {\n await submitViaServerExecute(\n quote,\n stepTransactions,\n messenger,\n transaction,\n );\n } else {\n await submitViaTransactionController(\n quote,\n stepTransactions,\n messenger,\n transaction,\n gasPayment,\n );\n }\n}\n\n/**\n * Build the complete flat array of transactions for on-chain submission.\n *\n * Converts server transaction steps to transactions, then prepends any\n * additional calls required by the payment override or post-quote flow. The\n * returned array is ready to pass directly to submitViaServerExecute or\n * submitViaTransactionController.\n *\n * @param quote - Server quote.\n * @param transactionSteps - Transaction steps from the quote (pre-filtered).\n * @param transaction - Original transaction meta.\n * @param messenger - Controller messenger.\n * @returns Complete ordered array of transactions for submission.\n */\nasync function buildStepTransactions(\n quote: TransactionPayQuote<ServerQuote>,\n transactionSteps: ServerTransactionStep[],\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): Promise<StepTransaction[]> {\n const { atomic, from, isPostQuote, paymentOverride } = quote.request;\n const { gasLimits, maxFeePerGas, maxPriorityFeePerGas } =\n quote.original.client;\n const originalType = getEffectiveTransactionType(transaction);\n\n // Client gas limits are estimated in submission order, so any prepended\n // transactions come first and the quote steps take the trailing limits.\n const stepGasLimits = gasLimits.slice(\n Math.max(gasLimits.length - transactionSteps.length, 0),\n );\n\n const quoteStepTransactions = transactionSteps.map((step, i) =>\n buildStepTransaction(\n step,\n i,\n transactionSteps.length,\n from,\n stepGasLimits,\n maxFeePerGas,\n maxPriorityFeePerGas,\n originalType,\n ),\n );\n\n // Non-atomic flows run the override calls as a second leg once the funds\n // settle, so prepending them here would run them twice.\n if (paymentOverride && atomic !== false) {\n return prependPaymentOverrideTransactions(\n quoteStepTransactions,\n quote,\n transaction,\n messenger,\n );\n }\n\n if (isPostQuote && transaction.txParams.to) {\n return prependPostQuoteTransactions(\n quoteStepTransactions,\n quote,\n transaction,\n messenger,\n );\n }\n\n return quoteStepTransactions;\n}\n\n/**\n * Converts a single server transaction step to a transaction.\n *\n * @param step - The transaction step.\n * @param index - Zero-based position within the transaction steps array.\n * @param totalSteps - Total number of transaction steps (for type mapping).\n * @param from - Sender address.\n * @param gasLimits - Per-step gas limits from client-side estimation.\n * @param clientMaxFeePerGas - Client-side max fee per gas fallback.\n * @param clientMaxPriorityFeePerGas - Client-side max priority fee per gas fallback.\n * @param originalType - Effective type of the parent transaction.\n * @returns Normalized transaction for this step.\n */\nfunction buildStepTransaction(\n step: ServerTransactionStep,\n index: number,\n totalSteps: number,\n from: Hex,\n gasLimits: number[],\n clientMaxFeePerGas: string | undefined,\n clientMaxPriorityFeePerGas: string | undefined,\n originalType: TransactionMeta['type'],\n): StepTransaction {\n let gas: Hex | undefined;\n const gasLimit = gasLimits[index];\n\n if (gasLimit) {\n gas = toHex(gasLimit);\n } else if (step.gasLimit) {\n gas = toHex(step.gasLimit);\n }\n\n const resolvedMaxFeePerGas = step.maxFeePerGas ?? clientMaxFeePerGas;\n const resolvedMaxPriorityFeePerGas =\n step.maxPriorityFeePerGas ?? clientMaxPriorityFeePerGas;\n\n const params: TransactionParams = {\n data: step.data,\n from,\n gas,\n maxFeePerGas: resolvedMaxFeePerGas\n ? toHex(resolvedMaxFeePerGas)\n : undefined,\n maxPriorityFeePerGas: resolvedMaxPriorityFeePerGas\n ? toHex(resolvedMaxPriorityFeePerGas)\n : undefined,\n to: step.to,\n value: toHex(step.value),\n };\n\n const type = getTransactionType(index, totalSteps, originalType);\n\n log('Built transaction for step', {\n index,\n step: {\n gasLimit: step.gasLimit,\n maxFeePerGas: step.maxFeePerGas,\n maxPriorityFeePerGas: step.maxPriorityFeePerGas,\n value: step.value,\n },\n params: {\n gas: params.gas,\n maxFeePerGas: params.maxFeePerGas,\n maxPriorityFeePerGas: params.maxPriorityFeePerGas,\n type,\n value: params.value,\n },\n });\n\n return { params, type };\n}\n\n/**\n * Determine the relay deposit transaction type for a step at the given index.\n *\n * Single-step quotes always use the deposit type. In multi-step quotes the\n * first step is an approval and subsequent steps are deposits — matching the\n * Relay strategy's convention.\n *\n * @param index - Zero-based index of the step within the transaction step array.\n * @param totalSteps - Total number of transaction steps.\n * @param originalType - Effective type of the parent transaction.\n * @returns The mapped TransactionType for this step.\n */\nfunction getTransactionType(\n index: number,\n totalSteps: number,\n originalType: TransactionMeta['type'],\n): TransactionType {\n const depositType = getRelayDepositType(originalType);\n\n if (totalSteps === 1) {\n return depositType;\n }\n\n return index === 0 ? ('tokenMethodApprove' as TransactionType) : depositType;\n}\n\n/**\n * Get the relay deposit transaction type based on the parent transaction type.\n *\n * @param originalType - Type of the parent transaction.\n * @returns The mapped relay deposit type, or `relayDeposit` as a fallback.\n */\nfunction getRelayDepositType(\n originalType: TransactionMeta['type'],\n): TransactionType {\n return (\n (originalType && RELAY_DEPOSIT_TYPES[originalType]) ??\n ('relayDeposit' as TransactionType)\n );\n}\n\n/**\n * Get the effective transaction type, resolving through batch-type parent\n * transactions to find the nested perps/predict type.\n *\n * @param transaction - The transaction metadata.\n * @returns The resolved type from nested transactions, or the top-level type.\n */\nfunction getEffectiveTransactionType(\n transaction: TransactionMeta,\n): TransactionMeta['type'] {\n if (transaction.type !== ('batch' as TransactionType)) {\n return transaction.type;\n }\n\n const nestedType = transaction.nestedTransactions?.find(\n (tx) => tx.type && RELAY_DEPOSIT_TYPES[tx.type] !== undefined,\n )?.type;\n\n return nestedType ?? transaction.type;\n}\n\n/**\n * Prepend payment override calls before the quote transaction steps.\n *\n * For money-account payment override flows the override account supplies\n * the source funds. The override transactions must be batched ahead of the\n * deposit steps.\n *\n * @param quoteStepTransactions - Transactions already built from the quote steps.\n * @param quote - Server quote.\n * @param transaction - Original transaction meta.\n * @param messenger - Controller messenger.\n * @returns Combined transactions with override calls prepended.\n */\nasync function prependPaymentOverrideTransactions(\n quoteStepTransactions: StepTransaction[],\n quote: TransactionPayQuote<ServerQuote>,\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): Promise<StepTransaction[]> {\n const { transactionData } = messenger.call(\n 'TransactionPayController:getState',\n );\n\n const { calls: overrideCalls } = await messenger.call(\n 'TransactionPayController:getPaymentOverrideData',\n {\n amount: quote.sourceAmount.human,\n transaction,\n transactionData: transactionData[transaction.id],\n },\n );\n\n if (!overrideCalls.length) {\n log('No payment override calls to prepend');\n return quoteStepTransactions;\n }\n\n log('Prepending payment override calls', { count: overrideCalls.length });\n\n const overrideTransactions = (overrideCalls as TransactionParams[]).map(\n (params) => ({\n params,\n }),\n );\n\n return [...overrideTransactions, ...quoteStepTransactions];\n}\n\n/**\n * Prepend the original transaction (or a delegation-wrapped version) before\n * the deposit steps for post-quote flows.\n *\n * In post-quote flows the source tokens are held in the Safe and only become\n * available after the original transaction executes as part of the batch.\n * When an accountOverride is active the override account cannot directly\n * execute the original call, so it is wrapped in a delegation transaction.\n *\n * @param quoteStepTransactions - Transactions already built from the quote steps.\n * @param quote - Server quote.\n * @param transaction - Original transaction meta.\n * @param messenger - Controller messenger.\n * @returns Combined transactions with the original tx prepended.\n */\nasync function prependPostQuoteTransactions(\n quoteStepTransactions: StepTransaction[],\n quote: TransactionPayQuote<ServerQuote>,\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): Promise<StepTransaction[]> {\n const hasAccountOverride =\n quote.request.from.toLowerCase() !==\n (transaction.txParams.from as Hex).toLowerCase();\n\n const { gasLimits, maxFeePerGas, maxPriorityFeePerGas } =\n quote.original.client;\n\n let prependedParams: TransactionParams;\n\n if (hasAccountOverride) {\n prependedParams = await buildDelegatedOriginalParams(\n transaction,\n messenger,\n );\n } else {\n prependedParams = {\n data: transaction.txParams.data,\n from: transaction.txParams.from,\n to: transaction.txParams.to,\n value: transaction.txParams.value,\n };\n }\n\n // Ensure the prepended tx carries the same fee caps as the quote steps so\n // it isn't submitted with undefined maxFeePerGas in a non-7702 batch.\n prependedParams.maxFeePerGas = maxFeePerGas ? toHex(maxFeePerGas) : undefined;\n prependedParams.maxPriorityFeePerGas = maxPriorityFeePerGas\n ? toHex(maxPriorityFeePerGas)\n : undefined;\n\n // The original transaction is estimated ahead of the quote steps, so it owns\n // the leading limit when each transaction has its own.\n if (gasLimits.length > quoteStepTransactions.length) {\n prependedParams.gas = toHex(gasLimits[0]);\n }\n\n log('Prepending post-quote original tx', { hasAccountOverride });\n\n return [{ params: prependedParams }, ...quoteStepTransactions];\n}\n\n/**\n * Build TransactionParams for a delegation that redeems the original\n * post-quote transaction on behalf of the override account.\n *\n * @param transaction - Original transaction meta to be redeemed.\n * @param messenger - Controller messenger.\n * @returns Transaction params for the delegation tx.\n */\nasync function buildDelegatedOriginalParams(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): Promise<TransactionParams> {\n const delegation = await messenger.call(\n 'TransactionPayController:getDelegationTransaction',\n { transaction },\n );\n\n log('Delegation result for post-quote original tx', delegation);\n\n return {\n data: delegation.data,\n from: transaction.txParams.from,\n to: delegation.to,\n value: delegation.value,\n };\n}\n\n/**\n * Validate that the user's source token balance covers the quote's required\n * source amount before submitting on-chain.\n *\n * Reads the live balance via RPC rather than the cached state so it reflects\n * any concurrent spends. Throws fast with a clear error instead of letting\n * the on-chain transaction revert.\n *\n * @param quote - Server quote containing the required source amount.\n * @param messenger - Controller messenger.\n */\nasync function validateSourceBalance(\n quote: TransactionPayQuote<ServerQuote>,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n const { from, sourceChainId, sourceTokenAddress } = quote.request;\n\n const normalizedSourceTokenAddress = normalizeTokenAddress(\n sourceTokenAddress,\n sourceChainId,\n TokenAddressTarget.MetaMask,\n );\n\n let currentBalance: string;\n\n try {\n currentBalance = await getLiveTokenBalance(\n messenger,\n from,\n sourceChainId,\n normalizedSourceTokenAddress,\n );\n } catch (error) {\n throw new Error(\n `Cannot validate payment token balance - ${(error as Error).message}`,\n );\n }\n\n const requiredAmount = new BigNumber(quote.sourceAmount.raw);\n const balance = new BigNumber(currentBalance);\n\n log('Validating source balance', {\n from,\n sourceChainId,\n sourceTokenAddress,\n currentBalance,\n requiredAmount: requiredAmount.toString(10),\n });\n\n if (balance.isLessThan(requiredAmount)) {\n throw new Error(\n `Insufficient source token balance for server deposit. ` +\n `Required: ${requiredAmount.toString(10)}, ` +\n `Available: ${balance.toString(10)}`,\n );\n }\n}\n\nasync function submitViaServerExecute(\n quote: TransactionPayQuote<ServerQuote>,\n stepTransactions: StepTransaction[],\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n): Promise<void> {\n const { from, sourceChainId } = quote.request;\n const networkClientId = getNetworkClientId(messenger, sourceChainId);\n\n const nestedTransactions = stepTransactions.map(({ params }) => ({\n data: (params.data ?? '0x') as Hex,\n to: params.to as Hex,\n value: (params.value ?? '0x0') as Hex,\n }));\n\n const sourceCallTransaction = {\n ...transaction,\n chainId: sourceChainId,\n networkClientId,\n nestedTransactions,\n txParams: {\n ...transaction.txParams,\n from,\n },\n } as TransactionMeta;\n\n const delegation = await messenger.call(\n 'TransactionPayController:getDelegationTransaction',\n { transaction: sourceCallTransaction },\n );\n\n log('Delegation result for server source calls', delegation);\n\n const submitBody: ServerSubmitRequest = {\n provider: quote.original.provider,\n id: quote.original.id,\n chainId: Number(sourceChainId),\n to: delegation.to,\n data: delegation.data,\n value: new BigNumber(delegation.value).toFixed(),\n ...(delegation.authorizationList?.length\n ? {\n authorizationList: delegation.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 };\n\n const submitResponse = await submitServerIntent(messenger, submitBody);\n\n if (!submitResponse.success) {\n throw new Error(\n `Server submit failed: ${submitResponse.error ?? 'unknown'}`,\n );\n }\n}\n\nasync function submitViaTransactionController(\n quote: TransactionPayQuote<ServerQuote>,\n stepTransactions: StepTransaction[],\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n gasPayment: GasPayment,\n): Promise<void> {\n const { from, sourceChainId } = quote.request;\n const { gasLimits, is7702 } = quote.original.client;\n const { excludeNativeTokenForFee, gasFeeToken } = gasPayment;\n\n const networkClientId = getNetworkClientId(messenger, sourceChainId);\n\n log('Submitting via TransactionController', {\n from,\n gasFeeToken,\n is7702,\n networkClientId,\n transactionCount: stepTransactions.length,\n sourceChainId,\n });\n\n const transactionIds: string[] = [];\n const { end } = collectTransactionIds(\n sourceChainId,\n from,\n messenger,\n (transactionId) => {\n transactionIds.push(transactionId);\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Add required transaction ID from server submission',\n },\n (tx) => {\n tx.requiredTransactionIds ??= [];\n tx.requiredTransactionIds.push(transactionId);\n },\n );\n },\n );\n\n try {\n if (stepTransactions.length === 1) {\n const { params, type } = stepTransactions[0];\n\n const addTransactionOptions = {\n excludeNativeTokenForFee,\n gasFeeToken,\n isGasFeeSponsored: gasPayment.isGasFeeSponsored,\n isInternal: true,\n networkClientId,\n origin: ORIGIN_METAMASK,\n requireApproval: false,\n type,\n };\n\n log('Calling addTransaction', {\n params,\n options: addTransactionOptions,\n });\n\n await messenger.call(\n 'TransactionController:addTransaction',\n params,\n addTransactionOptions,\n );\n } else {\n const gasLimit7702 = is7702 ? toHex(gasLimits[0]) : undefined;\n\n const batchTransactions = stepTransactions.map(({ params, type }) => {\n // params.gas was already resolved correctly by buildStepTransaction\n // (indexed by quote-step position), so use it directly. Indexing\n // the step position into gasLimits would be wrong when payment-\n // override or post-quote transactions are prepended.\n const gas = (gasLimit7702 ?? params.gas) as Hex | undefined;\n\n return {\n params: {\n data: params.data as Hex,\n gas,\n maxFeePerGas: params.maxFeePerGas as Hex,\n maxPriorityFeePerGas: params.maxPriorityFeePerGas as Hex,\n to: params.to as Hex,\n value: params.value as Hex,\n },\n type,\n };\n });\n\n const addTransactionBatchOptions = {\n from,\n ...(gasLimit7702 === undefined\n ? { disable7702: true }\n : {\n disable7702: false,\n disableHook: true,\n disableSequential: true,\n gasLimit7702,\n }),\n excludeNativeTokenForFee,\n gasFeeToken,\n isGasFeeSponsored: gasPayment.isGasFeeSponsored,\n isInternal: true,\n networkClientId,\n origin: ORIGIN_METAMASK,\n overwriteUpgrade: true,\n requireApproval: false,\n transactions: batchTransactions,\n };\n\n log('Calling addTransactionBatch', addTransactionBatchOptions);\n\n await messenger.call(\n 'TransactionController:addTransactionBatch',\n addTransactionBatchOptions,\n );\n }\n } finally {\n end();\n }\n\n log('Server transactions added', transactionIds);\n\n await Promise.all(\n transactionIds.map((txId) => waitForTransactionConfirmed(txId, messenger)),\n );\n\n log('Server transactions confirmed', transactionIds);\n\n logGasPaymentOutcome(\n gasPayment,\n transactionIds.map((txId) => getTransaction(txId, messenger)),\n );\n\n const lastId = transactionIds.at(-1);\n const sourceHash = lastId\n ? getTransaction(lastId, messenger)?.hash\n : undefined;\n\n if (sourceHash) {\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Add source hash from server transaction submission',\n },\n (tx) => {\n tx.metamaskPay ??= {};\n tx.metamaskPay.sourceHash = sourceHash as Hex;\n },\n );\n }\n}\n\nasync function submitSignatureStep(\n step: ServerSignatureStep,\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n const { sign, post } = step;\n\n const typedData = {\n domain: sign.domain,\n types: {\n ...sign.types,\n EIP712Domain: deriveEIP712DomainType(sign.domain),\n },\n primaryType: sign.primaryType,\n message: sign.value,\n };\n\n log('Signing typed data for signature step', {\n primaryType: sign.primaryType,\n });\n\n const signature = await messenger.call(\n 'KeyringController:signTypedMessage',\n { from, data: JSON.stringify(typedData) },\n SignTypedDataVersion.V4,\n );\n\n await postSignatureStepResult(\n post.endpoint,\n post.method,\n post.body,\n signature,\n post.signatureFormat,\n );\n}\n\nasync function postSignatureStepResult(\n endpoint: string,\n method: string,\n body: Record<string, unknown>,\n signature: string,\n signatureFormat: 'queryParam' | 'rsv',\n): Promise<void> {\n let url = endpoint;\n let postBody: Record<string, unknown>;\n\n if (signatureFormat === 'queryParam') {\n url = `${endpoint}?signature=${signature}`;\n postBody = body;\n } else {\n // eslint-disable-next-line id-length\n const r = signature.slice(0, 66);\n // eslint-disable-next-line id-length\n const s = `0x${signature.slice(66, 130)}`;\n // eslint-disable-next-line id-length\n const v = parseInt(signature.slice(130, 132), 16);\n postBody = { ...body, signature: { r, s, v } };\n }\n\n log('Posting signature step result', { url, signatureFormat });\n\n let result: unknown;\n\n try {\n const response = await successfulFetch(url, {\n method,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(postBody),\n });\n\n result = await response.json();\n } catch (error) {\n throw new Error(`Signature step POST failed: ${(error as Error).message}`);\n }\n\n log('Signature step POST response', result);\n\n // For rsv-format steps (HyperLiquid exchange endpoint) the response body\n // carries an explicit status field. Validate it here so a failed deposit\n // throws immediately rather than silently proceeding to the polling phase.\n if (signatureFormat === 'rsv') {\n const status = (result as { status?: string })?.status;\n\n if (status !== 'ok') {\n throw new Error(\n `Signature step rejected by server: ${JSON.stringify(result)}`,\n );\n }\n }\n}\n\nfunction deriveEIP712DomainType(\n domain: Record<string, unknown>,\n): { name: string; type: string }[] {\n return Object.keys(DOMAIN_FIELD_MAP)\n .filter((key) => Object.prototype.hasOwnProperty.call(domain, key))\n .map((key) => DOMAIN_FIELD_MAP[key]);\n}\n\n/**\n * Poll the server until the intent reaches a terminal status.\n *\n * Failures are returned rather than thrown so callers can clean up first, such\n * as sweeping a deposit wallet refund. Timeouts still throw.\n *\n * @param quote - Server quote being polled.\n * @param messenger - Controller messenger.\n * @param transactionId - ID of the parent transaction.\n * @returns The terminal status and the target-chain hash when reported.\n */\nasync function waitForServerCompletion(\n quote: ServerQuote,\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n): Promise<ServerCompletion> {\n const pollingInterval = getServerPollingInterval(messenger);\n const pollingTimeout = getServerPollingTimeout(messenger);\n const hasTimeout = pollingTimeout !== undefined && pollingTimeout > 0;\n\n log('Server polling config', { pollingInterval, pollingTimeout });\n\n const startTime = Date.now();\n\n let lastStatus: string | undefined;\n let sourceHashEmitted = false;\n\n while (true) {\n let statusResponse: ServerStatusResponse | undefined;\n\n try {\n const tx = getTransaction(transactionId, messenger);\n\n statusResponse = await getServerStatus(messenger, {\n provider: quote.provider,\n id: quote.id,\n hash: tx?.metamaskPay?.sourceHash ?? tx?.hash,\n });\n } catch (error) {\n log('Polling network error', error);\n }\n\n if (statusResponse) {\n lastStatus = statusResponse.status;\n log('Polled status', statusResponse.status, statusResponse);\n\n if (!sourceHashEmitted && statusResponse.sourceHash) {\n sourceHashEmitted = true;\n const { sourceHash } = statusResponse;\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Add source hash from server status',\n },\n (tx) => {\n tx.metamaskPay ??= {};\n tx.metamaskPay.sourceHash = sourceHash;\n },\n );\n }\n\n const { status, targetHash } = statusResponse;\n\n if (\n status === ServerStatus.Confirmed ||\n status === ServerStatus.Failed ||\n status === ServerStatus.Refunded\n ) {\n return { status, targetHash };\n }\n }\n\n if (hasTimeout && Date.now() - startTime >= pollingTimeout) {\n const statusDetail = lastStatus ? ` (last status: ${lastStatus})` : '';\n throw new Error(`Server polling timed out${statusDetail}`);\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollingInterval));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"server-submit.js","sourceRoot":"","sources":["../../../src/strategy/server/server-submit.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,eAAe,EACf,KAAK,GACN,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAOpE,OAAO,EAAE,k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D,MAAM,IAAI,KAAK,CAAC,iBAAiB,cAAc,CAAC,MAAM,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;YAC1E,CAAC;QACH,CAAC;QAED,IAAI,UAAU,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,IAAI,cAAc,EAAE,CAAC;YAC3D,MAAM,YAAY,GAAG,UAAU,CAAC,CAAC,CAAC,kBAAkB,UAAU,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;YACvE,MAAM,IAAI,KAAK,CAAC,2BAA2B,YAAY,EAAE,CAAC,CAAC;QAC7D,CAAC;QAED,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC;IACvE,CAAC;AACH,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n successfulFetch,\n toHex,\n} from '@metamask/controller-utils';\nimport { SignTypedDataVersion } from '@metamask/keyring-controller';\nimport type {\n TransactionMeta,\n TransactionParams,\n TransactionType,\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 PayStrategyExecuteRequest,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types.js';\nimport { accountSupports7702 } from '../../utils/7702.js';\nimport {\n getServerPollingInterval,\n getServerPollingTimeout,\n} from '../../utils/feature-flags.js';\nimport type { GasPayment } from '../../utils/gas-payment.js';\nimport {\n GasPaymentMode,\n logGasPaymentOutcome,\n resolveGasPayment,\n} from '../../utils/gas-payment.js';\nimport { getNetworkClientId } from '../../utils/provider.js';\nimport { submitSecondLeg } from '../../utils/second-leg.js';\nimport {\n getLiveTokenBalance,\n normalizeTokenAddress,\n TokenAddressTarget,\n} from '../../utils/token.js';\nimport {\n collectTransactionIds,\n getTransaction,\n updateTransaction,\n waitForTransactionConfirmed,\n} from '../../utils/transaction.js';\nimport { RELAY_DEPOSIT_TYPES } from '../relay/constants.js';\nimport { getServerStatus, submitServerIntent } from './server-api.js';\nimport type {\n ServerQuote,\n ServerSignatureStep,\n ServerTransactionStep,\n ServerStatusResponse,\n ServerSubmitRequest,\n} from './types.js';\nimport { ServerStatus } from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'server-strategy');\n\n/**\n * Placeholder returned when an intent confirms without reporting a\n * target-chain transaction hash, so there is no settlement to read amounts\n * from.\n */\nconst MISSING_TARGET_HASH = '0x' as Hex;\n\nconst DOMAIN_FIELD_MAP: Record<string, { name: string; type: string }> = {\n name: { name: 'name', type: 'string' },\n version: { name: 'version', type: 'string' },\n chainId: { name: 'chainId', type: 'uint256' },\n verifyingContract: { name: 'verifyingContract', type: 'address' },\n salt: { name: 'salt', type: 'bytes32' },\n};\n\n/**\n * A transaction to submit for a single quote step.\n *\n * The semantic transaction type is held alongside `params` rather than within\n * it, since `TransactionParams.type` is the EVM envelope type (`0x0` - `0x4`)\n * and is rejected by the transaction controller if given anything else.\n */\ntype StepTransaction = {\n params: TransactionParams;\n type?: TransactionType;\n};\n\nfunction isSignatureStep(\n step: ServerQuote['steps'][number],\n): step is ServerSignatureStep {\n return step.type === 'signature';\n}\n\nfunction isTransactionStep(\n step: ServerQuote['steps'][number],\n): step is ServerTransactionStep {\n return step.type === 'transaction';\n}\n\n/**\n * Submits server intent quotes.\n *\n * @param request - Request object.\n * @returns An object containing the transaction hash if available.\n */\nexport async function submitServerQuotes(\n request: PayStrategyExecuteRequest<ServerQuote>,\n): Promise<{ transactionHash?: Hex }> {\n log('Executing server quotes', request);\n\n const { quotes, messenger, transaction } = request;\n\n let transactionHash: Hex | undefined;\n\n for (const quote of quotes) {\n ({ transactionHash } = await executeSingleServerQuote(\n quote,\n messenger,\n transaction,\n ));\n }\n\n return { transactionHash };\n}\n\nasync function executeSingleServerQuote(\n quote: TransactionPayQuote<ServerQuote>,\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n): Promise<{ transactionHash?: Hex }> {\n log('Executing single server quote', quote);\n\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Remove nonce from skipped transaction',\n },\n (tx) => {\n tx.txParams.nonce = undefined;\n },\n );\n\n // Phase 1: off-chain signature steps (e.g. Relay authorize, HyperLiquid deposit).\n // Use quote.request.from (resolved accountOverride) not transaction.txParams.from.\n const signatureSteps = quote.original.steps.filter(isSignatureStep);\n\n for (const step of signatureSteps) {\n await submitSignatureStep(step, quote.request.from, messenger);\n }\n\n // Phase 2: on-chain transaction steps (if any).\n await submitTransactionSteps(quote, messenger, transaction);\n\n // Phase 3: poll until the intent is confirmed on the target chain.\n const targetHash = await waitForServerCompletion(\n quote.original,\n messenger,\n transaction.id,\n );\n\n log('Server request completed', targetHash);\n\n // Phase 4: submit the calls the quote could not execute itself, now that the\n // funds have settled on the target chain.\n const secondLegHash = quote.requiresSecondLeg\n ? await submitServerSecondLeg(quote, messenger, transaction, targetHash)\n : undefined;\n\n // Only complete once every leg has landed, so a failed second leg does not\n // leave the parent transaction flagged as achieved.\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Intent complete after Server completion',\n },\n (tx) => {\n tx.isIntentComplete = true;\n },\n );\n\n return { transactionHash: secondLegHash ?? targetHash };\n}\n\n/**\n * Submit the calls a server quote could not execute itself, from the account\n * the funds settled on.\n *\n * @param quote - Server quote.\n * @param messenger - Controller messenger.\n * @param transaction - Original transaction meta.\n * @param targetHash - Hash of the settlement on the target chain.\n * @returns Hash of the second-leg transaction, if available.\n */\nasync function submitServerSecondLeg(\n quote: TransactionPayQuote<ServerQuote>,\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n targetHash: Hex | undefined,\n): Promise<Hex | undefined> {\n const { from, recipient, targetChainId, targetTokenAddress } = quote.request;\n\n const { transactionHash } = await submitSecondLeg({\n chainId: targetChainId,\n from: recipient ?? from,\n messenger,\n settlementHash: targetHash === MISSING_TARGET_HASH ? undefined : targetHash,\n tokenAddress: targetTokenAddress,\n transaction,\n });\n\n return transactionHash;\n}\n\n/**\n * Submit the on-chain transaction steps for a server quote.\n *\n * Validates the source balance, builds the complete set of transactions (including\n * any post-quote or payment-override prepends), then dispatches to the\n * gasless execute path or TransactionController depending on the quote.\n *\n * No-ops when the quote has no transaction steps (signature-only flows).\n *\n * @param quote - Server quote.\n * @param messenger - Controller messenger.\n * @param transaction - Original transaction meta.\n */\nasync function submitTransactionSteps(\n quote: TransactionPayQuote<ServerQuote>,\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n): Promise<void> {\n const transactionSteps = quote.original.steps.filter(isTransactionStep);\n\n if (transactionSteps.length === 0) {\n // Signature-only quotes (all steps are signature steps, no transaction\n // steps) have nothing to submit on-chain even when gasless is false.\n const hasSignatureSteps = quote.original.steps.some(isSignatureStep);\n if (!quote.original.gasless && !hasSignatureSteps) {\n throw new Error('Server quote has no steps to submit');\n }\n return;\n }\n\n const { isHyperliquidSource, isPostQuote, paymentOverride } = quote.request;\n\n // Skip balance check for HyperLiquid source flows (no on-chain debit),\n // post-quote flows (funds come from the Safe after the original tx executes),\n // and payment-override flows (funds are supplied by the override account).\n if (!isHyperliquidSource && !isPostQuote && !paymentOverride) {\n await validateSourceBalance(quote, messenger);\n }\n\n const stepTransactions = await buildStepTransactions(\n quote,\n transactionSteps,\n transaction,\n messenger,\n );\n\n const gasPayment = resolveGasPayment({\n isDelegated: quote.original.gasless,\n isSourceGasFeeToken: quote.fees.isSourceGasFeeToken,\n sourceTokenAddress: quote.request.sourceTokenAddress,\n sponsorship: {\n accountSupports7702: accountSupports7702(messenger, quote.request.from),\n request: quote.request,\n transaction,\n },\n });\n\n if (gasPayment.mode === GasPaymentMode.Delegation) {\n await submitViaServerExecute(\n quote,\n stepTransactions,\n messenger,\n transaction,\n );\n } else {\n await submitViaTransactionController(\n quote,\n stepTransactions,\n messenger,\n transaction,\n gasPayment,\n );\n }\n}\n\n/**\n * Build the complete flat array of transactions for on-chain submission.\n *\n * Converts server transaction steps to transactions, then prepends any\n * additional calls required by the payment override or post-quote flow. The\n * returned array is ready to pass directly to submitViaServerExecute or\n * submitViaTransactionController.\n *\n * @param quote - Server quote.\n * @param transactionSteps - Transaction steps from the quote (pre-filtered).\n * @param transaction - Original transaction meta.\n * @param messenger - Controller messenger.\n * @returns Complete ordered array of transactions for submission.\n */\nasync function buildStepTransactions(\n quote: TransactionPayQuote<ServerQuote>,\n transactionSteps: ServerTransactionStep[],\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): Promise<StepTransaction[]> {\n const { from, isPostQuote, paymentOverride } = quote.request;\n const { gasLimits, maxFeePerGas, maxPriorityFeePerGas } =\n quote.original.client;\n const originalType = getEffectiveTransactionType(transaction);\n\n const quoteStepTransactions = transactionSteps.map((step, i) =>\n buildStepTransaction(\n step,\n i,\n transactionSteps.length,\n from,\n gasLimits,\n maxFeePerGas,\n maxPriorityFeePerGas,\n originalType,\n ),\n );\n\n if (paymentOverride) {\n return prependPaymentOverrideTransactions(\n quoteStepTransactions,\n quote,\n transaction,\n messenger,\n );\n }\n\n if (isPostQuote && transaction.txParams.to) {\n return prependPostQuoteTransactions(\n quoteStepTransactions,\n quote,\n transaction,\n messenger,\n );\n }\n\n return quoteStepTransactions;\n}\n\n/**\n * Converts a single server transaction step to a transaction.\n *\n * @param step - The transaction step.\n * @param index - Zero-based position within the transaction steps array.\n * @param totalSteps - Total number of transaction steps (for type mapping).\n * @param from - Sender address.\n * @param gasLimits - Per-step gas limits from client-side estimation.\n * @param clientMaxFeePerGas - Client-side max fee per gas fallback.\n * @param clientMaxPriorityFeePerGas - Client-side max priority fee per gas fallback.\n * @param originalType - Effective type of the parent transaction.\n * @returns Normalized transaction for this step.\n */\nfunction buildStepTransaction(\n step: ServerTransactionStep,\n index: number,\n totalSteps: number,\n from: Hex,\n gasLimits: number[],\n clientMaxFeePerGas: string | undefined,\n clientMaxPriorityFeePerGas: string | undefined,\n originalType: TransactionMeta['type'],\n): StepTransaction {\n let gas: Hex | undefined;\n const gasLimit = gasLimits[index];\n\n if (gasLimit) {\n gas = toHex(gasLimit);\n } else if (step.gasLimit) {\n gas = toHex(step.gasLimit);\n }\n\n const resolvedMaxFeePerGas = step.maxFeePerGas ?? clientMaxFeePerGas;\n const resolvedMaxPriorityFeePerGas =\n step.maxPriorityFeePerGas ?? clientMaxPriorityFeePerGas;\n\n const params: TransactionParams = {\n data: step.data,\n from,\n gas,\n maxFeePerGas: resolvedMaxFeePerGas\n ? toHex(resolvedMaxFeePerGas)\n : undefined,\n maxPriorityFeePerGas: resolvedMaxPriorityFeePerGas\n ? toHex(resolvedMaxPriorityFeePerGas)\n : undefined,\n to: step.to,\n value: toHex(step.value),\n };\n\n const type = getTransactionType(index, totalSteps, originalType);\n\n log('Built transaction for step', {\n index,\n step: {\n gasLimit: step.gasLimit,\n maxFeePerGas: step.maxFeePerGas,\n maxPriorityFeePerGas: step.maxPriorityFeePerGas,\n value: step.value,\n },\n params: {\n gas: params.gas,\n maxFeePerGas: params.maxFeePerGas,\n maxPriorityFeePerGas: params.maxPriorityFeePerGas,\n type,\n value: params.value,\n },\n });\n\n return { params, type };\n}\n\n/**\n * Determine the relay deposit transaction type for a step at the given index.\n *\n * Single-step quotes always use the deposit type. In multi-step quotes the\n * first step is an approval and subsequent steps are deposits — matching the\n * Relay strategy's convention.\n *\n * @param index - Zero-based index of the step within the transaction step array.\n * @param totalSteps - Total number of transaction steps.\n * @param originalType - Effective type of the parent transaction.\n * @returns The mapped TransactionType for this step.\n */\nfunction getTransactionType(\n index: number,\n totalSteps: number,\n originalType: TransactionMeta['type'],\n): TransactionType {\n const depositType = getRelayDepositType(originalType);\n\n if (totalSteps === 1) {\n return depositType;\n }\n\n return index === 0 ? ('tokenMethodApprove' as TransactionType) : depositType;\n}\n\n/**\n * Get the relay deposit transaction type based on the parent transaction type.\n *\n * @param originalType - Type of the parent transaction.\n * @returns The mapped relay deposit type, or `relayDeposit` as a fallback.\n */\nfunction getRelayDepositType(\n originalType: TransactionMeta['type'],\n): TransactionType {\n return (\n (originalType && RELAY_DEPOSIT_TYPES[originalType]) ??\n ('relayDeposit' as TransactionType)\n );\n}\n\n/**\n * Get the effective transaction type, resolving through batch-type parent\n * transactions to find the nested perps/predict type.\n *\n * @param transaction - The transaction metadata.\n * @returns The resolved type from nested transactions, or the top-level type.\n */\nfunction getEffectiveTransactionType(\n transaction: TransactionMeta,\n): TransactionMeta['type'] {\n if (transaction.type !== ('batch' as TransactionType)) {\n return transaction.type;\n }\n\n const nestedType = transaction.nestedTransactions?.find(\n (tx) => tx.type && RELAY_DEPOSIT_TYPES[tx.type] !== undefined,\n )?.type;\n\n return nestedType ?? transaction.type;\n}\n\n/**\n * Prepend payment override calls before the quote transaction steps.\n *\n * For money-account payment override flows the override account supplies\n * the source funds. The override transactions must be batched ahead of the\n * deposit steps.\n *\n * @param quoteStepTransactions - Transactions already built from the quote steps.\n * @param quote - Server quote.\n * @param transaction - Original transaction meta.\n * @param messenger - Controller messenger.\n * @returns Combined transactions with override calls prepended.\n */\nasync function prependPaymentOverrideTransactions(\n quoteStepTransactions: StepTransaction[],\n quote: TransactionPayQuote<ServerQuote>,\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): Promise<StepTransaction[]> {\n const { transactionData } = messenger.call(\n 'TransactionPayController:getState',\n );\n\n const { calls: overrideCalls } = await messenger.call(\n 'TransactionPayController:getPaymentOverrideData',\n {\n amount: quote.sourceAmount.human,\n transaction,\n transactionData: transactionData[transaction.id],\n },\n );\n\n if (!overrideCalls.length) {\n log('No payment override calls to prepend');\n return quoteStepTransactions;\n }\n\n log('Prepending payment override calls', { count: overrideCalls.length });\n\n const overrideTransactions = (overrideCalls as TransactionParams[]).map(\n (params) => ({\n params,\n }),\n );\n\n return [...overrideTransactions, ...quoteStepTransactions];\n}\n\n/**\n * Prepend the original transaction (or a delegation-wrapped version) before\n * the deposit steps for post-quote flows.\n *\n * In post-quote flows the source tokens are held in the Safe and only become\n * available after the original transaction executes as part of the batch.\n * When an accountOverride is active the override account cannot directly\n * execute the original call, so it is wrapped in a delegation transaction.\n *\n * @param quoteStepTransactions - Transactions already built from the quote steps.\n * @param quote - Server quote.\n * @param transaction - Original transaction meta.\n * @param messenger - Controller messenger.\n * @returns Combined transactions with the original tx prepended.\n */\nasync function prependPostQuoteTransactions(\n quoteStepTransactions: StepTransaction[],\n quote: TransactionPayQuote<ServerQuote>,\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): Promise<StepTransaction[]> {\n const hasAccountOverride =\n quote.request.from.toLowerCase() !==\n (transaction.txParams.from as Hex).toLowerCase();\n\n const { maxFeePerGas, maxPriorityFeePerGas } = quote.original.client;\n\n let prependedParams: TransactionParams;\n\n if (hasAccountOverride) {\n prependedParams = await buildDelegatedOriginalParams(\n transaction,\n messenger,\n );\n } else {\n prependedParams = {\n data: transaction.txParams.data,\n from: transaction.txParams.from,\n to: transaction.txParams.to,\n value: transaction.txParams.value,\n };\n }\n\n // Ensure the prepended tx carries the same fee caps as the quote steps so\n // it isn't submitted with undefined maxFeePerGas in a non-7702 batch.\n prependedParams.maxFeePerGas = maxFeePerGas ? toHex(maxFeePerGas) : undefined;\n prependedParams.maxPriorityFeePerGas = maxPriorityFeePerGas\n ? toHex(maxPriorityFeePerGas)\n : undefined;\n\n log('Prepending post-quote original tx', { hasAccountOverride });\n\n return [{ params: prependedParams }, ...quoteStepTransactions];\n}\n\n/**\n * Build TransactionParams for a delegation that redeems the original\n * post-quote transaction on behalf of the override account.\n *\n * @param transaction - Original transaction meta to be redeemed.\n * @param messenger - Controller messenger.\n * @returns Transaction params for the delegation tx.\n */\nasync function buildDelegatedOriginalParams(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): Promise<TransactionParams> {\n const delegation = await messenger.call(\n 'TransactionPayController:getDelegationTransaction',\n { transaction },\n );\n\n log('Delegation result for post-quote original tx', delegation);\n\n return {\n data: delegation.data,\n from: transaction.txParams.from,\n to: delegation.to,\n value: delegation.value,\n };\n}\n\n/**\n * Validate that the user's source token balance covers the quote's required\n * source amount before submitting on-chain.\n *\n * Reads the live balance via RPC rather than the cached state so it reflects\n * any concurrent spends. Throws fast with a clear error instead of letting\n * the on-chain transaction revert.\n *\n * @param quote - Server quote containing the required source amount.\n * @param messenger - Controller messenger.\n */\nasync function validateSourceBalance(\n quote: TransactionPayQuote<ServerQuote>,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n const { from, sourceChainId, sourceTokenAddress } = quote.request;\n\n const normalizedSourceTokenAddress = normalizeTokenAddress(\n sourceTokenAddress,\n sourceChainId,\n TokenAddressTarget.MetaMask,\n );\n\n let currentBalance: string;\n\n try {\n currentBalance = await getLiveTokenBalance(\n messenger,\n from,\n sourceChainId,\n normalizedSourceTokenAddress,\n );\n } catch (error) {\n throw new Error(\n `Cannot validate payment token balance - ${(error as Error).message}`,\n );\n }\n\n const requiredAmount = new BigNumber(quote.sourceAmount.raw);\n const balance = new BigNumber(currentBalance);\n\n log('Validating source balance', {\n from,\n sourceChainId,\n sourceTokenAddress,\n currentBalance,\n requiredAmount: requiredAmount.toString(10),\n });\n\n if (balance.isLessThan(requiredAmount)) {\n throw new Error(\n `Insufficient source token balance for server deposit. ` +\n `Required: ${requiredAmount.toString(10)}, ` +\n `Available: ${balance.toString(10)}`,\n );\n }\n}\n\nasync function submitViaServerExecute(\n quote: TransactionPayQuote<ServerQuote>,\n stepTransactions: StepTransaction[],\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n): Promise<void> {\n const { from, sourceChainId } = quote.request;\n const networkClientId = getNetworkClientId(messenger, sourceChainId);\n\n const nestedTransactions = stepTransactions.map(({ params }) => ({\n data: (params.data ?? '0x') as Hex,\n to: params.to as Hex,\n value: (params.value ?? '0x0') as Hex,\n }));\n\n const sourceCallTransaction = {\n ...transaction,\n chainId: sourceChainId,\n networkClientId,\n nestedTransactions,\n txParams: {\n ...transaction.txParams,\n from,\n },\n } as TransactionMeta;\n\n const delegation = await messenger.call(\n 'TransactionPayController:getDelegationTransaction',\n { transaction: sourceCallTransaction },\n );\n\n log('Delegation result for server source calls', delegation);\n\n const submitBody: ServerSubmitRequest = {\n provider: quote.original.provider,\n id: quote.original.id,\n chainId: Number(sourceChainId),\n to: delegation.to,\n data: delegation.data,\n value: new BigNumber(delegation.value).toFixed(),\n ...(delegation.authorizationList?.length\n ? {\n authorizationList: delegation.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 };\n\n const submitResponse = await submitServerIntent(messenger, submitBody);\n\n if (!submitResponse.success) {\n throw new Error(\n `Server submit failed: ${submitResponse.error ?? 'unknown'}`,\n );\n }\n}\n\nasync function submitViaTransactionController(\n quote: TransactionPayQuote<ServerQuote>,\n stepTransactions: StepTransaction[],\n messenger: TransactionPayControllerMessenger,\n transaction: TransactionMeta,\n gasPayment: GasPayment,\n): Promise<void> {\n const { from, sourceChainId } = quote.request;\n const { gasLimits, is7702 } = quote.original.client;\n const { excludeNativeTokenForFee, gasFeeToken } = gasPayment;\n\n const networkClientId = getNetworkClientId(messenger, sourceChainId);\n\n log('Submitting via TransactionController', {\n from,\n gasFeeToken,\n is7702,\n networkClientId,\n transactionCount: stepTransactions.length,\n sourceChainId,\n });\n\n const transactionIds: string[] = [];\n const { end } = collectTransactionIds(\n sourceChainId,\n from,\n messenger,\n (transactionId) => {\n transactionIds.push(transactionId);\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Add required transaction ID from server submission',\n },\n (tx) => {\n tx.requiredTransactionIds ??= [];\n tx.requiredTransactionIds.push(transactionId);\n },\n );\n },\n );\n\n try {\n if (stepTransactions.length === 1) {\n const { params, type } = stepTransactions[0];\n\n const addTransactionOptions = {\n excludeNativeTokenForFee,\n gasFeeToken,\n isGasFeeSponsored: gasPayment.isGasFeeSponsored,\n isInternal: true,\n networkClientId,\n origin: ORIGIN_METAMASK,\n requireApproval: false,\n type,\n };\n\n log('Calling addTransaction', {\n params,\n options: addTransactionOptions,\n });\n\n await messenger.call(\n 'TransactionController:addTransaction',\n params,\n addTransactionOptions,\n );\n } else {\n const gasLimit7702 = is7702 ? toHex(gasLimits[0]) : undefined;\n\n const batchTransactions = stepTransactions.map(({ params, type }) => {\n // params.gas was already resolved correctly by buildStepTransaction\n // (indexed by quote-step position), so use it directly. Indexing\n // the step position into gasLimits would be wrong when payment-\n // override or post-quote transactions are prepended.\n const gas = (gasLimit7702 ?? params.gas) as Hex | undefined;\n\n return {\n params: {\n data: params.data as Hex,\n gas,\n maxFeePerGas: params.maxFeePerGas as Hex,\n maxPriorityFeePerGas: params.maxPriorityFeePerGas as Hex,\n to: params.to as Hex,\n value: params.value as Hex,\n },\n type,\n };\n });\n\n const addTransactionBatchOptions = {\n from,\n ...(gasLimit7702 === undefined\n ? { disable7702: true }\n : {\n disable7702: false,\n disableHook: true,\n disableSequential: true,\n gasLimit7702,\n }),\n excludeNativeTokenForFee,\n gasFeeToken,\n isGasFeeSponsored: gasPayment.isGasFeeSponsored,\n isInternal: true,\n networkClientId,\n origin: ORIGIN_METAMASK,\n overwriteUpgrade: true,\n requireApproval: false,\n transactions: batchTransactions,\n };\n\n log('Calling addTransactionBatch', addTransactionBatchOptions);\n\n await messenger.call(\n 'TransactionController:addTransactionBatch',\n addTransactionBatchOptions,\n );\n }\n } finally {\n end();\n }\n\n log('Server transactions added', transactionIds);\n\n await Promise.all(\n transactionIds.map((txId) => waitForTransactionConfirmed(txId, messenger)),\n );\n\n log('Server transactions confirmed', transactionIds);\n\n logGasPaymentOutcome(\n gasPayment,\n transactionIds.map((txId) => getTransaction(txId, messenger)),\n );\n\n const lastId = transactionIds.at(-1);\n const sourceHash = lastId\n ? getTransaction(lastId, messenger)?.hash\n : undefined;\n\n if (sourceHash) {\n updateTransaction(\n {\n transactionId: transaction.id,\n messenger,\n note: 'Add source hash from server transaction submission',\n },\n (tx) => {\n tx.metamaskPay ??= {};\n tx.metamaskPay.sourceHash = sourceHash as Hex;\n },\n );\n }\n}\n\nasync function submitSignatureStep(\n step: ServerSignatureStep,\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n const { sign, post } = step;\n\n const typedData = {\n domain: sign.domain,\n types: {\n ...sign.types,\n EIP712Domain: deriveEIP712DomainType(sign.domain),\n },\n primaryType: sign.primaryType,\n message: sign.value,\n };\n\n log('Signing typed data for signature step', {\n primaryType: sign.primaryType,\n });\n\n const signature = await messenger.call(\n 'KeyringController:signTypedMessage',\n { from, data: JSON.stringify(typedData) },\n SignTypedDataVersion.V4,\n );\n\n await postSignatureStepResult(\n post.endpoint,\n post.method,\n post.body,\n signature,\n post.signatureFormat,\n );\n}\n\nasync function postSignatureStepResult(\n endpoint: string,\n method: string,\n body: Record<string, unknown>,\n signature: string,\n signatureFormat: 'queryParam' | 'rsv',\n): Promise<void> {\n let url = endpoint;\n let postBody: Record<string, unknown>;\n\n if (signatureFormat === 'queryParam') {\n url = `${endpoint}?signature=${signature}`;\n postBody = body;\n } else {\n // eslint-disable-next-line id-length\n const r = signature.slice(0, 66);\n // eslint-disable-next-line id-length\n const s = `0x${signature.slice(66, 130)}`;\n // eslint-disable-next-line id-length\n const v = parseInt(signature.slice(130, 132), 16);\n postBody = { ...body, signature: { r, s, v } };\n }\n\n log('Posting signature step result', { url, signatureFormat });\n\n let result: unknown;\n\n try {\n const response = await successfulFetch(url, {\n method,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(postBody),\n });\n\n result = await response.json();\n } catch (error) {\n throw new Error(`Signature step POST failed: ${(error as Error).message}`);\n }\n\n log('Signature step POST response', result);\n\n // For rsv-format steps (HyperLiquid exchange endpoint) the response body\n // carries an explicit status field. Validate it here so a failed deposit\n // throws immediately rather than silently proceeding to the polling phase.\n if (signatureFormat === 'rsv') {\n const status = (result as { status?: string })?.status;\n\n if (status !== 'ok') {\n throw new Error(\n `Signature step rejected by server: ${JSON.stringify(result)}`,\n );\n }\n }\n}\n\nfunction deriveEIP712DomainType(\n domain: Record<string, unknown>,\n): { name: string; type: string }[] {\n return Object.keys(DOMAIN_FIELD_MAP)\n .filter((key) => Object.prototype.hasOwnProperty.call(domain, key))\n .map((key) => DOMAIN_FIELD_MAP[key]);\n}\n\nasync function waitForServerCompletion(\n quote: ServerQuote,\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n): Promise<Hex | undefined> {\n const pollingInterval = getServerPollingInterval(messenger);\n const pollingTimeout = getServerPollingTimeout(messenger);\n const hasTimeout = pollingTimeout !== undefined && pollingTimeout > 0;\n\n log('Server polling config', { pollingInterval, pollingTimeout });\n\n const startTime = Date.now();\n\n let lastStatus: string | undefined;\n let sourceHashEmitted = false;\n\n while (true) {\n let statusResponse: ServerStatusResponse | undefined;\n\n try {\n const tx = getTransaction(transactionId, messenger);\n\n statusResponse = await getServerStatus(messenger, {\n provider: quote.provider,\n id: quote.id,\n hash: tx?.metamaskPay?.sourceHash ?? tx?.hash,\n });\n } catch (error) {\n log('Polling network error', error);\n }\n\n if (statusResponse) {\n lastStatus = statusResponse.status;\n log('Polled status', statusResponse.status, statusResponse);\n\n if (!sourceHashEmitted && statusResponse.sourceHash) {\n sourceHashEmitted = true;\n const { sourceHash } = statusResponse;\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Add source hash from server status',\n },\n (tx) => {\n tx.metamaskPay ??= {};\n tx.metamaskPay.sourceHash = sourceHash;\n },\n );\n }\n\n if (statusResponse.status === ServerStatus.Confirmed) {\n return statusResponse.targetHash ?? MISSING_TARGET_HASH;\n }\n\n if (\n statusResponse.status === ServerStatus.Failed ||\n statusResponse.status === ServerStatus.Refunded\n ) {\n throw new Error(`Server intent ${statusResponse.status.toLowerCase()}`);\n }\n }\n\n if (hasTimeout && Date.now() - startTime >= pollingTimeout) {\n const statusDetail = lastStatus ? ` (last status: ${lastStatus})` : '';\n throw new Error(`Server polling timed out${statusDetail}`);\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollingInterval));\n }\n}\n"]}
|
|
@@ -20,7 +20,9 @@ export declare enum ServerUnsupportedReason {
|
|
|
20
20
|
/** Reserving the HyperLiquid activation fee is not implemented. */
|
|
21
21
|
HyperliquidActivationFee = "hyperliquidActivationFee",
|
|
22
22
|
/** Two-phase max-amount gas station probing is not implemented. */
|
|
23
|
-
MaxAmount = "maxAmount"
|
|
23
|
+
MaxAmount = "maxAmount",
|
|
24
|
+
/** Polymarket deposit-wallet routing is not implemented. */
|
|
25
|
+
PolymarketDepositWallet = "polymarketDepositWallet"
|
|
24
26
|
}
|
|
25
27
|
/**
|
|
26
28
|
* Determine whether the server strategy can handle a set of quote requests.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-support.d.ts","sourceRoot":"","sources":["../../../src/strategy/server/server-support.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAEL,eAAe,EAChB,MAAM,kCAAkC,CAAC;AAE1C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD;;;;;;;;GAQG;AACH,eAAO,MAAM,wCAAwC,EAAE,eAAe,EAAO,CAAC;AAE9E,4DAA4D;AAC5D,oBAAY,uBAAuB;IACjC,kEAAkE;IAClE,sBAAsB,2BAA2B;IAEjD,uEAAuE;IACvE,uBAAuB,4BAA4B;IAEnD,mEAAmE;IACnE,wBAAwB,6BAA6B;IAErD,mEAAmE;IACnE,SAAS,cAAc;
|
|
1
|
+
{"version":3,"file":"server-support.d.ts","sourceRoot":"","sources":["../../../src/strategy/server/server-support.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAEL,eAAe,EAChB,MAAM,kCAAkC,CAAC;AAE1C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD;;;;;;;;GAQG;AACH,eAAO,MAAM,wCAAwC,EAAE,eAAe,EAAO,CAAC;AAE9E,4DAA4D;AAC5D,oBAAY,uBAAuB;IACjC,kEAAkE;IAClE,sBAAsB,2BAA2B;IAEjD,uEAAuE;IACvE,uBAAuB,4BAA4B;IAEnD,mEAAmE;IACnE,wBAAwB,6BAA6B;IAErD,mEAAmE;IACnE,SAAS,cAAc;IAEvB,4DAA4D;IAC5D,uBAAuB,4BAA4B;CACpD;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,0BAA0B,CAAC,EACzC,uBAAuB,EACvB,QAAQ,EACR,WAAW,GACZ,EAAE;IACD,uBAAuB,EAAE,eAAe,EAAE,CAAC;IAC3C,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,WAAW,CAAC,EAAE,eAAe,CAAC;CAC/B,GAAG,uBAAuB,GAAG,SAAS,CActC"}
|
|
@@ -20,6 +20,8 @@ export var ServerUnsupportedReason;
|
|
|
20
20
|
ServerUnsupportedReason["HyperliquidActivationFee"] = "hyperliquidActivationFee";
|
|
21
21
|
/** Two-phase max-amount gas station probing is not implemented. */
|
|
22
22
|
ServerUnsupportedReason["MaxAmount"] = "maxAmount";
|
|
23
|
+
/** Polymarket deposit-wallet routing is not implemented. */
|
|
24
|
+
ServerUnsupportedReason["PolymarketDepositWallet"] = "polymarketDepositWallet";
|
|
23
25
|
})(ServerUnsupportedReason || (ServerUnsupportedReason = {}));
|
|
24
26
|
/**
|
|
25
27
|
* Determine whether the server strategy can handle a set of quote requests.
|
|
@@ -72,6 +74,9 @@ function getRequestUnsupportedReason(request) {
|
|
|
72
74
|
if (request.isMaxAmount === true) {
|
|
73
75
|
return ServerUnsupportedReason.MaxAmount;
|
|
74
76
|
}
|
|
77
|
+
if (request.isPolymarketDepositWallet === true) {
|
|
78
|
+
return ServerUnsupportedReason.PolymarketDepositWallet;
|
|
79
|
+
}
|
|
75
80
|
return undefined;
|
|
76
81
|
}
|
|
77
82
|
//# sourceMappingURL=server-support.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-support.js","sourceRoot":"","sources":["../../../src/strategy/server/server-support.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kBAAkB,GAEnB,MAAM,kCAAkC,CAAC;AAI1C;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,wCAAwC,GAAsB,EAAE,CAAC;AAE9E,4DAA4D;AAC5D,MAAM,CAAN,IAAY,
|
|
1
|
+
{"version":3,"file":"server-support.js","sourceRoot":"","sources":["../../../src/strategy/server/server-support.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kBAAkB,GAEnB,MAAM,kCAAkC,CAAC;AAI1C;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,wCAAwC,GAAsB,EAAE,CAAC;AAE9E,4DAA4D;AAC5D,MAAM,CAAN,IAAY,uBAeX;AAfD,WAAY,uBAAuB;IACjC,kEAAkE;IAClE,4EAAiD,CAAA;IAEjD,uEAAuE;IACvE,8EAAmD,CAAA;IAEnD,mEAAmE;IACnE,gFAAqD,CAAA;IAErD,mEAAmE;IACnE,kDAAuB,CAAA;IAEvB,4DAA4D;IAC5D,8EAAmD,CAAA;AACrD,CAAC,EAfW,uBAAuB,KAAvB,uBAAuB,QAelC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,0BAA0B,CAAC,EACzC,uBAAuB,EACvB,QAAQ,EACR,WAAW,GAKZ;IACC,IAAI,CAAC,kBAAkB,CAAC,WAAW,EAAE,uBAAuB,CAAC,EAAE,CAAC;QAC9D,OAAO,uBAAuB,CAAC,uBAAuB,CAAC;IACzD,CAAC;IAED,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,MAAM,MAAM,GAAG,2BAA2B,CAAC,OAAO,CAAC,CAAC;QAEpD,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,MAAM,CAAC;QAChB,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,2BAA2B,CAClC,OAAqB;IAErB,IAAI,OAAO,CAAC,2BAA2B,KAAK,SAAS,EAAE,CAAC;QACtD,OAAO,uBAAuB,CAAC,wBAAwB,CAAC;IAC1D,CAAC;IAED,IAAI,OAAO,CAAC,wBAAwB,KAAK,IAAI,EAAE,CAAC;QAC9C,OAAO,uBAAuB,CAAC,sBAAsB,CAAC;IACxD,CAAC;IAED,IAAI,OAAO,CAAC,WAAW,KAAK,IAAI,EAAE,CAAC;QACjC,OAAO,uBAAuB,CAAC,SAAS,CAAC;IAC3C,CAAC;IAED,IAAI,OAAO,CAAC,yBAAyB,KAAK,IAAI,EAAE,CAAC;QAC/C,OAAO,uBAAuB,CAAC,uBAAuB,CAAC;IACzD,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport {\n hasTransactionType,\n TransactionType,\n} from '@metamask/transaction-controller';\n\nimport type { QuoteRequest } from '../../types.js';\n\n/**\n * Parent transaction types enabled for the server strategy by default.\n *\n * Intentionally empty so that turning on `payStrategies.server.enabled` alone\n * never diverts live traffic away from the relay strategy. Flows are opted in\n * one at a time via the `payStrategies.server.enabledTransactionTypes` remote\n * feature flag, which lets a single flow be validated in isolation before the\n * next one is added.\n */\nexport const DEFAULT_SERVER_ENABLED_TRANSACTION_TYPES: TransactionType[] = [];\n\n/** Why the server strategy declined to handle a request. */\nexport enum ServerUnsupportedReason {\n /** The direct mUSD Money Account fiat flow is not implemented. */\n DirectMusdMoneyAccount = 'directMusdMoneyAccount',\n\n /** The parent transaction type is not in the remote-flag allowlist. */\n DisabledTransactionType = 'disabledTransactionType',\n\n /** Reserving the HyperLiquid activation fee is not implemented. */\n HyperliquidActivationFee = 'hyperliquidActivationFee',\n\n /** Two-phase max-amount gas station probing is not implemented. */\n MaxAmount = 'maxAmount',\n\n /** Polymarket deposit-wallet routing is not implemented. */\n PolymarketDepositWallet = 'polymarketDepositWallet',\n}\n\n/**\n * Determine whether the server strategy can handle a set of quote requests.\n *\n * Gating has two independent layers:\n *\n * 1. A remote-flag allowlist of transaction types, so flows can be rolled out\n * and rolled back one at a time.\n * 2. Code-level capability guards for request shapes the server strategy does\n * not implement yet. These cannot be overridden by the flag; each one is\n * deleted as the corresponding capability lands.\n *\n * A transaction can carry several types across its nested transactions, so\n * both layers match against the transaction and its nested transactions.\n *\n * @param options - Options bag.\n * @param options.enabledTransactionTypes - Transaction types opted in via\n * remote feature flag.\n * @param options.requests - Quote requests for required tokens.\n * @param options.transaction - Metadata of the original target transaction.\n * @returns The first reason the requests are unsupported, or `undefined` if\n * every request is supported.\n */\nexport function getServerUnsupportedReason({\n enabledTransactionTypes,\n requests,\n transaction,\n}: {\n enabledTransactionTypes: TransactionType[];\n requests: QuoteRequest[];\n transaction?: TransactionMeta;\n}): ServerUnsupportedReason | undefined {\n if (!hasTransactionType(transaction, enabledTransactionTypes)) {\n return ServerUnsupportedReason.DisabledTransactionType;\n }\n\n for (const request of requests) {\n const reason = getRequestUnsupportedReason(request);\n\n if (reason) {\n return reason;\n }\n }\n\n return undefined;\n}\n\n/**\n * Determine whether a single quote request uses a capability the server\n * strategy has not implemented yet.\n *\n * @param request - Quote request for a required token.\n * @returns The reason the request is unsupported, or `undefined`.\n */\nfunction getRequestUnsupportedReason(\n request: QuoteRequest,\n): ServerUnsupportedReason | undefined {\n if (request.hyperliquidActivationFeeUsd !== undefined) {\n return ServerUnsupportedReason.HyperliquidActivationFee;\n }\n\n if (request.isDirectMusdMoneyAccount === true) {\n return ServerUnsupportedReason.DirectMusdMoneyAccount;\n }\n\n if (request.isMaxAmount === true) {\n return ServerUnsupportedReason.MaxAmount;\n }\n\n if (request.isPolymarketDepositWallet === true) {\n return ServerUnsupportedReason.PolymarketDepositWallet;\n }\n\n return undefined;\n}\n"]}
|
|
@@ -70,13 +70,6 @@ export type ServerQuoteRequest = {
|
|
|
70
70
|
authorizationList?: ServerAuthorization[];
|
|
71
71
|
supportsDeferredCalls?: boolean;
|
|
72
72
|
supportsGasless?: boolean;
|
|
73
|
-
/**
|
|
74
|
-
* Whether the quote is funded with a plain token transfer to a provider
|
|
75
|
-
* deposit address, rather than by calling the provider contracts. The
|
|
76
|
-
* transfer must not include any additional calldata, such as an appended
|
|
77
|
-
* request ID.
|
|
78
|
-
*/
|
|
79
|
-
useDepositAddress?: boolean;
|
|
80
73
|
};
|
|
81
74
|
/** Error detail from a rejected quote result. */
|
|
82
75
|
export type ServerQuoteError = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/strategy/server/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAE3D,iDAAiD;AACjD,MAAM,MAAM,iBAAiB,GAAG;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE,aAAa,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,EAAE,EAAE,GAAG,CAAC;IACR,IAAI,EAAE,GAAG,CAAC;IACV,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,WAAW,CAAC;IAClB,IAAI,EAAE;QACJ,MAAM,EAAE,MAAM,CAAC,MAAM,EAA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/strategy/server/types.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/strategy/server/types.ts"],"names":[],"mappings":"AAqIA,6CAA6C;AAC7C,MAAM,CAAN,IAAY,YAOX;AAPD,WAAY,YAAY;IACtB,mCAAmB,CAAA;IACnB,uCAAuB,CAAA;IACvB,uCAAuB,CAAA;IACvB,iCAAiB,CAAA;IACjB,qCAAqB,CAAA;IACrB,mCAAmB,CAAA;AACrB,CAAC,EAPW,YAAY,KAAZ,YAAY,QAOvB","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nimport type { TradeType } from '../../utils/trade-type.js';\n\n/** Token amount with chain and token context. */\nexport type ServerQuoteAmount = {\n chainId: number;\n token: string;\n decimals: number;\n raw: string;\n formatted: string;\n};\n\nexport type ServerTransactionStep = {\n type: 'transaction';\n chainId: number;\n to: Hex;\n data: Hex;\n value: string;\n gasLimit?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n};\n\nexport type ServerSignatureStep = {\n type: 'signature';\n sign: {\n domain: Record<string, unknown>;\n types: Record<string, unknown>;\n primaryType: string;\n value: Record<string, unknown>;\n };\n post: {\n endpoint: string;\n method: string;\n body: Record<string, unknown>;\n signatureFormat: 'queryParam' | 'rsv';\n };\n};\n\nexport type ServerStep = ServerTransactionStep | ServerSignatureStep;\n\n/** A call to include in the quote request (for delegation flows). */\nexport type ServerCall = {\n to: Hex;\n data: Hex;\n value: Hex;\n};\n\n/** EIP-7702 authorization entry for quote and submit requests. */\nexport type ServerAuthorization = {\n address: Hex;\n chainId: number;\n nonce: number;\n r: Hex;\n s: Hex;\n yParity: number;\n};\n\n/** Request body for POST /quote. */\nexport type ServerQuoteRequest = {\n source: { chainId: number; token: Hex };\n target: { chainId: number; token: Hex };\n amount: string;\n tradeType: TradeType;\n sender: Hex;\n recipient: Hex;\n refundTo?: Hex;\n slippage?: number;\n providers?: string[];\n calls?: ServerCall[];\n authorizationList?: ServerAuthorization[];\n supportsDeferredCalls?: boolean;\n supportsGasless?: boolean;\n};\n\n/** Error detail from a rejected quote result. */\nexport type ServerQuoteError = {\n code?: string;\n message: string;\n};\n\n/** A successful quote payload nested inside a ServerQuoteResult. */\nexport type ServerQuotePayload = {\n id: string;\n input: ServerQuoteAmount;\n output: ServerQuoteAmount;\n fees: ServerQuoteFees;\n duration: number;\n steps: ServerStep[];\n gasless: boolean;\n callsDeferred?: boolean;\n};\n\n/** Fee breakdown from a quote. */\nexport type ServerQuoteFees = {\n metamask: string;\n provider: string;\n subsidized: boolean;\n};\n\n/** A single provider result within the quote response. */\nexport type ServerQuoteResult = {\n provider: string;\n quote?: ServerQuotePayload;\n error?: ServerQuoteError;\n};\n\n/** Response body from POST /quote. */\nexport type ServerQuoteResponse = {\n results: ServerQuoteResult[];\n};\n\nexport type ServerQuoteClient = {\n gasLimits: number[];\n is7702: boolean;\n maxFeePerGas: string | undefined;\n maxPriorityFeePerGas: string | undefined;\n};\n\n/** Normalized server quote stored in TransactionPayQuote.original. */\nexport type ServerQuote = {\n id: string;\n provider: string;\n input: ServerQuoteAmount;\n output: ServerQuoteAmount;\n fees: ServerQuoteFees;\n duration: number;\n client: ServerQuoteClient;\n steps: ServerStep[];\n gasless: boolean;\n};\n\n/** Status values returned by GET /status. */\nexport enum ServerStatus {\n Pending = 'PENDING',\n Submitted = 'SUBMITTED',\n Confirmed = 'CONFIRMED',\n Failed = 'FAILED',\n Refunded = 'REFUNDED',\n Unknown = 'UNKNOWN',\n}\n\n/** Response body from GET /status. */\nexport type ServerStatusResponse = {\n status: ServerStatus;\n sourceHash?: Hex;\n targetHash?: Hex;\n error?: string;\n};\n\n/** Request body for POST /submit. */\nexport type ServerSubmitRequest = {\n provider: string;\n id: string;\n chainId: number;\n to: Hex;\n data: Hex;\n value: string;\n authorizationList?: {\n chainId: number;\n address: Hex;\n nonce: number;\n yParity: number;\n r: Hex;\n s: Hex;\n }[];\n};\n\n/** Response body from POST /submit. */\nexport type ServerSubmitResponse = {\n success: boolean;\n error?: string;\n};\n"]}
|