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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +18 -1
  2. package/dist/strategy/fiat/fiat-direct-musd.d.ts.map +1 -1
  3. package/dist/strategy/fiat/fiat-direct-musd.js +17 -12
  4. package/dist/strategy/fiat/fiat-direct-musd.js.map +1 -1
  5. package/dist/strategy/fiat/fiat-submit.js +1 -1
  6. package/dist/strategy/fiat/fiat-submit.js.map +1 -1
  7. package/dist/strategy/fiat/utils.d.ts +6 -24
  8. package/dist/strategy/fiat/utils.d.ts.map +1 -1
  9. package/dist/strategy/fiat/utils.js +21 -37
  10. package/dist/strategy/fiat/utils.js.map +1 -1
  11. package/dist/strategy/relay/relay-quotes.d.ts.map +1 -1
  12. package/dist/strategy/relay/relay-quotes.js +10 -40
  13. package/dist/strategy/relay/relay-quotes.js.map +1 -1
  14. package/dist/strategy/relay/relay-submit.d.ts.map +1 -1
  15. package/dist/strategy/relay/relay-submit.js +59 -110
  16. package/dist/strategy/relay/relay-submit.js.map +1 -1
  17. package/dist/strategy/server/server-api.d.ts +2 -2
  18. package/dist/strategy/server/server-api.d.ts.map +1 -1
  19. package/dist/strategy/server/server-api.js.map +1 -1
  20. package/dist/strategy/server/server-quotes.d.ts.map +1 -1
  21. package/dist/strategy/server/server-quotes.js +122 -21
  22. package/dist/strategy/server/server-quotes.js.map +1 -1
  23. package/dist/strategy/server/server-submit.d.ts.map +1 -1
  24. package/dist/strategy/server/server-submit.js +38 -2
  25. package/dist/strategy/server/server-submit.js.map +1 -1
  26. package/dist/strategy/server/server-support.d.ts +0 -2
  27. package/dist/strategy/server/server-support.d.ts.map +1 -1
  28. package/dist/strategy/server/server-support.js +0 -5
  29. package/dist/strategy/server/server-support.js.map +1 -1
  30. package/dist/strategy/server/types.d.ts +6 -9
  31. package/dist/strategy/server/types.d.ts.map +1 -1
  32. package/dist/strategy/server/types.js +0 -6
  33. package/dist/strategy/server/types.js.map +1 -1
  34. package/dist/types.d.ts +10 -0
  35. package/dist/types.d.ts.map +1 -1
  36. package/dist/types.js.map +1 -1
  37. package/dist/utils/chomp.d.ts +32 -0
  38. package/dist/utils/chomp.d.ts.map +1 -1
  39. package/dist/utils/chomp.js +73 -0
  40. package/dist/utils/chomp.js.map +1 -1
  41. package/dist/utils/second-leg.d.ts +71 -0
  42. package/dist/utils/second-leg.d.ts.map +1 -0
  43. package/dist/utils/second-leg.js +281 -0
  44. package/dist/utils/second-leg.js.map +1 -0
  45. package/package.json +2 -2
  46. package/dist/utils/ma-vault-deposit.d.ts +0 -40
  47. package/dist/utils/ma-vault-deposit.d.ts.map +0 -1
  48. package/dist/utils/ma-vault-deposit.js +0 -230
  49. package/dist/utils/ma-vault-deposit.js.map +0 -1
@@ -0,0 +1,281 @@
1
+ import { ORIGIN_METAMASK } from '@metamask/controller-utils';
2
+ import { TransactionType } from '@metamask/transaction-controller';
3
+ import { createModuleLogger } from '@metamask/utils';
4
+ import { projectLogger } from '../logger.js';
5
+ import { withChompRecovery } from './chomp.js';
6
+ import { prefixError } from './error-prefix.js';
7
+ import { getNetworkClientId } from './provider.js';
8
+ import { collectTransactionIds, getTransaction, getTransferredAmountFromTxHash, updateTransaction, waitForTransactionConfirmed, } from './transaction.js';
9
+ export const SECOND_LEG_ERROR_PREFIX = 'Second leg: ';
10
+ const log = createModuleLogger(projectLogger, 'second-leg');
11
+ /**
12
+ * Derives the quote recipient for non-atomic flows, where the second leg runs
13
+ * after settlement so funds must land directly on the account submitting that
14
+ * leg.
15
+ *
16
+ * Post-quote flows (e.g. Perps/Predict withdraw to Money Account) ask the
17
+ * client `getPaymentOverrideData` callback, which knows the Money Account
18
+ * address that cannot be derived from the request. Non-post-quote flows (e.g.
19
+ * max-amount Money Account deposit) use the parent transaction's own `from`,
20
+ * which is the Money Account rather than the funding EOA in `request.from`.
21
+ *
22
+ * Atomic flows return `undefined`: the provider executes the calls as part of
23
+ * the quote, so the funds must land on the account running them.
24
+ *
25
+ * @param transaction - Transaction metadata.
26
+ * @param request - Quote request.
27
+ * @param messenger - Controller messenger.
28
+ * @returns The recipient address, or `undefined` for atomic flows.
29
+ */
30
+ export async function resolveNonAtomicRecipient(transaction, request, messenger) {
31
+ if (request.atomic !== false) {
32
+ return undefined;
33
+ }
34
+ if (!request.isPostQuote) {
35
+ return transaction.txParams.from;
36
+ }
37
+ const { transactionData: transactionDataList } = messenger.call('TransactionPayController:getState');
38
+ const transactionData = transactionDataList[transaction.id];
39
+ const amountHuman = transactionData?.tokens?.[0]?.amountHuman ?? '0';
40
+ const { recipient } = await messenger.call('TransactionPayController:getPaymentOverrideData', {
41
+ amount: amountHuman,
42
+ transaction,
43
+ transactionData,
44
+ });
45
+ return recipient;
46
+ }
47
+ /**
48
+ * Submits the second leg of a non-atomic flow: the calls that the quote could
49
+ * not execute itself, run on the target chain once the first leg has settled.
50
+ *
51
+ * The single entrypoint for every strategy. The caller decides the chain, the
52
+ * submitting account, the calls, and whether gas is sponsored, while
53
+ * transaction-type-specific handling (e.g. {@link withChompRecovery}) is
54
+ * applied here so it holds whichever strategy settled the funds.
55
+ *
56
+ * The amount spent is read from the settlement transaction's transfer logs
57
+ * rather than trusted from a quote or provider, since slippage and fees mean
58
+ * the landed amount is only known after settlement. Throws when there is no
59
+ * settlement hash or no matching transfer, rather than guessing.
60
+ *
61
+ * @param options - Submit options.
62
+ * @param options.chainId - Chain the funds settled on and the batch is
63
+ * submitted on.
64
+ * @param options.from - Account that received the settled funds and submits
65
+ * the batch.
66
+ * @param options.getCalls - Builds the batch for the settled amount. Derived
67
+ * from the parent transaction's nested calls when omitted.
68
+ * @param options.messenger - Controller messenger.
69
+ * @param options.note - Note recorded against the parent transaction update.
70
+ * @param options.settlementHash - Hash of the transaction that delivered the
71
+ * funds to `from`.
72
+ * @param options.sponsored - Whether gas is sponsored. Defaults to `true`,
73
+ * since second legs run on chains where MetaMask sponsors gas; submission
74
+ * fails rather than silently charging the user when sponsorship is refused.
75
+ * @param options.tokenAddress - Token that settled.
76
+ * @param options.transaction - Parent transaction meta.
77
+ * @returns Hash of the final submitted child transaction, if available.
78
+ */
79
+ export async function submitSecondLeg({ chainId, from, getCalls, messenger, note, settlementHash, sponsored = true, tokenAddress, transaction, }) {
80
+ const { amountRaw: sourceAmountRaw, fromBlock } = await resolveSettledAmount({
81
+ chainId,
82
+ messenger,
83
+ recipient: from,
84
+ settlementHash,
85
+ tokenAddress,
86
+ });
87
+ // Resolved up front so the parent transaction reflects the settled amount
88
+ // even when type-specific handling short-circuits the submission.
89
+ const nestedTransactions = await resolveSecondLegCalls({
90
+ getCalls,
91
+ messenger,
92
+ note,
93
+ sourceAmountRaw,
94
+ transaction,
95
+ });
96
+ try {
97
+ return await withChompRecovery({ from, fromBlock, messenger, sourceAmountRaw, transaction }, async () => await submitBatch({
98
+ chainId,
99
+ from,
100
+ messenger,
101
+ nestedTransactions,
102
+ sourceAmountRaw,
103
+ sponsored,
104
+ transaction,
105
+ }));
106
+ }
107
+ catch (error) {
108
+ throw prefixError(error, SECOND_LEG_ERROR_PREFIX);
109
+ }
110
+ }
111
+ /**
112
+ * Resolves the calls to submit as the second leg.
113
+ *
114
+ * Callers with no calls on the parent transaction (e.g. withdraw flows) supply
115
+ * `getCalls` to build the batch for the settled amount. Otherwise the parent
116
+ * transaction's own nested calls are re-encoded for the settled amount via
117
+ * `getAmountData`, and the parent transaction is mutated so its stored calls
118
+ * and `requiredAssets` reflect that amount.
119
+ *
120
+ * @param options - Resolution options.
121
+ * @param options.getCalls - Builds the batch for the settled amount, used
122
+ * as-is when provided.
123
+ * @param options.messenger - Controller messenger.
124
+ * @param options.note - Note recorded against the parent transaction update.
125
+ * @param options.sourceAmountRaw - Settled amount in raw units.
126
+ * @param options.transaction - Parent transaction meta.
127
+ * @returns Nested transactions to submit as the second leg.
128
+ */
129
+ async function resolveSecondLegCalls({ getCalls, messenger, note = 'Second leg: update amount', sourceAmountRaw, transaction, }) {
130
+ if (getCalls) {
131
+ const calls = await getCalls(sourceAmountRaw);
132
+ if (!calls.length) {
133
+ throw new Error('Missing second leg calls');
134
+ }
135
+ return calls;
136
+ }
137
+ const transactionId = transaction.id;
138
+ const updatedTransaction = getTransaction(transactionId, messenger) ?? transaction;
139
+ const { updates } = await messenger.call('TransactionPayController:getAmountData', {
140
+ amount: sourceAmountRaw,
141
+ transaction: updatedTransaction,
142
+ });
143
+ if (!updates.length) {
144
+ throw new Error('No amount updates');
145
+ }
146
+ const nestedTransactions = updatedTransaction.nestedTransactions?.map((nestedTransaction) => ({ ...nestedTransaction }));
147
+ if (!nestedTransactions?.length) {
148
+ throw new Error('Missing nested transactions');
149
+ }
150
+ for (const { nestedTransactionIndex, data } of updates) {
151
+ if (nestedTransactions[nestedTransactionIndex]) {
152
+ nestedTransactions[nestedTransactionIndex].data = data;
153
+ }
154
+ }
155
+ updateTransaction({ transactionId, messenger, note }, (tx) => {
156
+ for (const { nestedTransactionIndex, data } of updates) {
157
+ if (tx.nestedTransactions?.[nestedTransactionIndex]) {
158
+ tx.nestedTransactions[nestedTransactionIndex].data = data;
159
+ }
160
+ }
161
+ if (tx.requiredAssets?.[0]) {
162
+ tx.requiredAssets[0].amount = `0x${BigInt(sourceAmountRaw).toString(16)}`;
163
+ }
164
+ });
165
+ return nestedTransactions;
166
+ }
167
+ /**
168
+ * Resolves the amount that settled on `recipient`, read from the settlement
169
+ * transaction's transfer logs, along with the block it settled in.
170
+ *
171
+ * @param options - Resolution options.
172
+ * @param options.chainId - Chain the funds settled on.
173
+ * @param options.messenger - Controller messenger.
174
+ * @param options.recipient - Account that received the settled funds.
175
+ * @param options.settlementHash - Hash of the transaction that delivered the
176
+ * funds.
177
+ * @param options.tokenAddress - Token that settled.
178
+ * @returns The settled amount in raw units, and the settlement block when
179
+ * available.
180
+ */
181
+ async function resolveSettledAmount({ chainId, messenger, recipient, settlementHash, tokenAddress, }) {
182
+ if (!settlementHash) {
183
+ throw new Error('Missing settlement hash');
184
+ }
185
+ const { amountRaw, blockNumber } = await getTransferredAmountFromTxHash({
186
+ chainId,
187
+ messenger,
188
+ tokenAddress,
189
+ txHash: settlementHash,
190
+ walletAddress: recipient,
191
+ });
192
+ if (!amountRaw) {
193
+ throw new Error(`Could not determine settled amount from transaction ${settlementHash}`);
194
+ }
195
+ log('Resolved settled amount', {
196
+ amountRaw,
197
+ blockNumber,
198
+ chainId,
199
+ recipient,
200
+ settlementHash,
201
+ });
202
+ return { amountRaw, fromBlock: blockNumber };
203
+ }
204
+ /**
205
+ * Submits the second-leg batch and waits for every child transaction to
206
+ * confirm.
207
+ *
208
+ * @param options - Submit options.
209
+ * @param options.chainId - Chain to submit the batch on.
210
+ * @param options.from - Account submitting the batch.
211
+ * @param options.messenger - Controller messenger.
212
+ * @param options.nestedTransactions - Calls to submit.
213
+ * @param options.sourceAmountRaw - Settled amount in raw units, for logging.
214
+ * @param options.sponsored - Whether gas is sponsored.
215
+ * @param options.transaction - Parent transaction meta.
216
+ * @returns Hash of the final submitted child transaction.
217
+ */
218
+ async function submitBatch({ chainId, from, messenger, nestedTransactions, sourceAmountRaw, sponsored, transaction, }) {
219
+ const transactionId = transaction.id;
220
+ const networkClientId = getNetworkClientId(messenger, chainId);
221
+ const transactionIds = [];
222
+ const { end } = collectTransactionIds(chainId, from, messenger, (id) => {
223
+ transactionIds.push(id);
224
+ updateTransaction({
225
+ transactionId,
226
+ messenger,
227
+ note: 'Add required transaction ID from second leg submission',
228
+ }, (tx) => {
229
+ tx.requiredTransactionIds ??= [];
230
+ tx.requiredTransactionIds.push(id);
231
+ });
232
+ });
233
+ const logContext = {
234
+ chainId,
235
+ from,
236
+ nestedTransactionCount: nestedTransactions.length,
237
+ networkClientId,
238
+ sourceAmountRaw,
239
+ transactionId,
240
+ };
241
+ log('Submitting second leg', logContext);
242
+ try {
243
+ await messenger.call('TransactionController:addTransactionBatch', {
244
+ disableHook: true,
245
+ disableSequential: true,
246
+ disableUpgrade: true,
247
+ from,
248
+ isGasFeeSponsored: sponsored,
249
+ isInternal: true,
250
+ networkClientId,
251
+ origin: ORIGIN_METAMASK,
252
+ requireApproval: false,
253
+ skipInitialGasEstimate: true,
254
+ transactions: nestedTransactions.map((nestedTransaction, index) => ({
255
+ params: {
256
+ data: nestedTransaction.data,
257
+ to: nestedTransaction.to,
258
+ value: nestedTransaction.value ?? '0x0',
259
+ },
260
+ type: index === 0
261
+ ? (nestedTransaction.type ?? TransactionType.tokenMethodApprove)
262
+ : TransactionType.contractInteraction,
263
+ })),
264
+ });
265
+ }
266
+ finally {
267
+ end();
268
+ }
269
+ log('Submitted second leg', { ...logContext, transactionIds });
270
+ if (!transactionIds.length) {
271
+ throw new Error('No transactions submitted');
272
+ }
273
+ await Promise.all(transactionIds.map((id) => waitForTransactionConfirmed(id, messenger)));
274
+ const hash = getTransaction(transactionIds.slice(-1)[0], messenger)?.hash;
275
+ if (!hash) {
276
+ throw new Error('Missing transaction hash');
277
+ }
278
+ log('Confirmed second leg', { ...logContext, hash, transactionIds });
279
+ return { transactionHash: hash };
280
+ }
281
+ //# sourceMappingURL=second-leg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"second-leg.js","sourceRoot":"","sources":["../../src/utils/second-leg.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAM7D,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAEnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAK7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,8BAA8B,EA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CAAC,cAAc,CAAC,MAAM,EAAE,CAAC;QAC3B,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;IAC/C,CAAC;IAED,MAAM,OAAO,CAAC,GAAG,CACf,cAAc,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,2BAA2B,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC,CACvE,CAAC;IAEF,MAAM,IAAI,GAAG,cAAc,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,EAAE,IAAI,CAAC;IAE1E,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAC9C,CAAC;IAED,GAAG,CAAC,sBAAsB,EAAE,EAAE,GAAG,UAAU,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC,CAAC;IAErE,OAAO,EAAE,eAAe,EAAE,IAAW,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["import { ORIGIN_METAMASK } from '@metamask/controller-utils';\nimport type {\n BatchTransactionParams,\n NestedTransactionMetadata,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger.js';\nimport type {\n QuoteRequest,\n TransactionPayControllerMessenger,\n} from '../types.js';\nimport { withChompRecovery } from './chomp.js';\nimport { prefixError } from './error-prefix.js';\nimport { getNetworkClientId } from './provider.js';\nimport {\n collectTransactionIds,\n getTransaction,\n getTransferredAmountFromTxHash,\n updateTransaction,\n waitForTransactionConfirmed,\n} from './transaction.js';\n\nexport const SECOND_LEG_ERROR_PREFIX = 'Second leg: ';\n\nconst log = createModuleLogger(projectLogger, 'second-leg');\n\nexport type SecondLegCallsBuilder = (\n sourceAmountRaw: string,\n) => Promise<BatchTransactionParams[]>;\n\n/**\n * Derives the quote recipient for non-atomic flows, where the second leg runs\n * after settlement so funds must land directly on the account submitting that\n * leg.\n *\n * Post-quote flows (e.g. Perps/Predict withdraw to Money Account) ask the\n * client `getPaymentOverrideData` callback, which knows the Money Account\n * address that cannot be derived from the request. Non-post-quote flows (e.g.\n * max-amount Money Account deposit) use the parent transaction's own `from`,\n * which is the Money Account rather than the funding EOA in `request.from`.\n *\n * Atomic flows return `undefined`: the provider executes the calls as part of\n * the quote, so the funds must land on the account running them.\n *\n * @param transaction - Transaction metadata.\n * @param request - Quote request.\n * @param messenger - Controller messenger.\n * @returns The recipient address, or `undefined` for atomic flows.\n */\nexport async function resolveNonAtomicRecipient(\n transaction: TransactionMeta,\n request: QuoteRequest,\n messenger: TransactionPayControllerMessenger,\n): Promise<Hex | undefined> {\n if (request.atomic !== false) {\n return undefined;\n }\n\n if (!request.isPostQuote) {\n return transaction.txParams.from as Hex;\n }\n\n const { transactionData: transactionDataList } = messenger.call(\n 'TransactionPayController:getState',\n );\n\n const transactionData = transactionDataList[transaction.id];\n const amountHuman = transactionData?.tokens?.[0]?.amountHuman ?? '0';\n\n const { recipient } = await messenger.call(\n 'TransactionPayController:getPaymentOverrideData',\n {\n amount: amountHuman,\n transaction,\n transactionData,\n },\n );\n\n return recipient;\n}\n\n/**\n * Submits the second leg of a non-atomic flow: the calls that the quote could\n * not execute itself, run on the target chain once the first leg has settled.\n *\n * The single entrypoint for every strategy. The caller decides the chain, the\n * submitting account, the calls, and whether gas is sponsored, while\n * transaction-type-specific handling (e.g. {@link withChompRecovery}) is\n * applied here so it holds whichever strategy settled the funds.\n *\n * The amount spent is read from the settlement transaction's transfer logs\n * rather than trusted from a quote or provider, since slippage and fees mean\n * the landed amount is only known after settlement. Throws when there is no\n * settlement hash or no matching transfer, rather than guessing.\n *\n * @param options - Submit options.\n * @param options.chainId - Chain the funds settled on and the batch is\n * submitted on.\n * @param options.from - Account that received the settled funds and submits\n * the batch.\n * @param options.getCalls - Builds the batch for the settled amount. Derived\n * from the parent transaction's nested calls when omitted.\n * @param options.messenger - Controller messenger.\n * @param options.note - Note recorded against the parent transaction update.\n * @param options.settlementHash - Hash of the transaction that delivered the\n * funds to `from`.\n * @param options.sponsored - Whether gas is sponsored. Defaults to `true`,\n * since second legs run on chains where MetaMask sponsors gas; submission\n * fails rather than silently charging the user when sponsorship is refused.\n * @param options.tokenAddress - Token that settled.\n * @param options.transaction - Parent transaction meta.\n * @returns Hash of the final submitted child transaction, if available.\n */\nexport async function submitSecondLeg({\n chainId,\n from,\n getCalls,\n messenger,\n note,\n settlementHash,\n sponsored = true,\n tokenAddress,\n transaction,\n}: {\n chainId: Hex;\n from: Hex;\n getCalls?: SecondLegCallsBuilder;\n messenger: TransactionPayControllerMessenger;\n note?: string;\n settlementHash: Hex | undefined;\n sponsored?: boolean;\n tokenAddress: Hex;\n transaction: TransactionMeta;\n}): Promise<{ transactionHash?: Hex }> {\n const { amountRaw: sourceAmountRaw, fromBlock } = await resolveSettledAmount({\n chainId,\n messenger,\n recipient: from,\n settlementHash,\n tokenAddress,\n });\n\n // Resolved up front so the parent transaction reflects the settled amount\n // even when type-specific handling short-circuits the submission.\n const nestedTransactions = await resolveSecondLegCalls({\n getCalls,\n messenger,\n note,\n sourceAmountRaw,\n transaction,\n });\n\n try {\n return await withChompRecovery(\n { from, fromBlock, messenger, sourceAmountRaw, transaction },\n async () =>\n await submitBatch({\n chainId,\n from,\n messenger,\n nestedTransactions,\n sourceAmountRaw,\n sponsored,\n transaction,\n }),\n );\n } catch (error) {\n throw prefixError(error, SECOND_LEG_ERROR_PREFIX);\n }\n}\n\n/**\n * Resolves the calls to submit as the second leg.\n *\n * Callers with no calls on the parent transaction (e.g. withdraw flows) supply\n * `getCalls` to build the batch for the settled amount. Otherwise the parent\n * transaction's own nested calls are re-encoded for the settled amount via\n * `getAmountData`, and the parent transaction is mutated so its stored calls\n * and `requiredAssets` reflect that amount.\n *\n * @param options - Resolution options.\n * @param options.getCalls - Builds the batch for the settled amount, used\n * as-is when provided.\n * @param options.messenger - Controller messenger.\n * @param options.note - Note recorded against the parent transaction update.\n * @param options.sourceAmountRaw - Settled amount in raw units.\n * @param options.transaction - Parent transaction meta.\n * @returns Nested transactions to submit as the second leg.\n */\nasync function resolveSecondLegCalls({\n getCalls,\n messenger,\n note = 'Second leg: update amount',\n sourceAmountRaw,\n transaction,\n}: {\n getCalls?: SecondLegCallsBuilder;\n messenger: TransactionPayControllerMessenger;\n note?: string;\n sourceAmountRaw: string;\n transaction: TransactionMeta;\n}): Promise<NestedTransactionMetadata[]> {\n if (getCalls) {\n const calls = await getCalls(sourceAmountRaw);\n\n if (!calls.length) {\n throw new Error('Missing second leg calls');\n }\n\n return calls;\n }\n\n const transactionId = transaction.id;\n\n const updatedTransaction =\n getTransaction(transactionId, messenger) ?? transaction;\n\n const { updates } = await messenger.call(\n 'TransactionPayController:getAmountData',\n {\n amount: sourceAmountRaw,\n transaction: updatedTransaction,\n },\n );\n\n if (!updates.length) {\n throw new Error('No amount updates');\n }\n\n const nestedTransactions = updatedTransaction.nestedTransactions?.map(\n (nestedTransaction) => ({ ...nestedTransaction }),\n );\n\n if (!nestedTransactions?.length) {\n throw new Error('Missing nested transactions');\n }\n\n for (const { nestedTransactionIndex, data } of updates) {\n if (nestedTransactions[nestedTransactionIndex]) {\n nestedTransactions[nestedTransactionIndex].data = data;\n }\n }\n\n updateTransaction({ transactionId, messenger, note }, (tx) => {\n for (const { nestedTransactionIndex, data } of updates) {\n if (tx.nestedTransactions?.[nestedTransactionIndex]) {\n tx.nestedTransactions[nestedTransactionIndex].data = data;\n }\n }\n\n if (tx.requiredAssets?.[0]) {\n tx.requiredAssets[0].amount = `0x${BigInt(sourceAmountRaw).toString(16)}`;\n }\n });\n\n return nestedTransactions;\n}\n\n/**\n * Resolves the amount that settled on `recipient`, read from the settlement\n * transaction's transfer logs, along with the block it settled in.\n *\n * @param options - Resolution options.\n * @param options.chainId - Chain the funds settled on.\n * @param options.messenger - Controller messenger.\n * @param options.recipient - Account that received the settled funds.\n * @param options.settlementHash - Hash of the transaction that delivered the\n * funds.\n * @param options.tokenAddress - Token that settled.\n * @returns The settled amount in raw units, and the settlement block when\n * available.\n */\nasync function resolveSettledAmount({\n chainId,\n messenger,\n recipient,\n settlementHash,\n tokenAddress,\n}: {\n chainId: Hex;\n messenger: TransactionPayControllerMessenger;\n recipient: Hex;\n settlementHash: Hex | undefined;\n tokenAddress: Hex;\n}): Promise<{ amountRaw: string; fromBlock: Hex | undefined }> {\n if (!settlementHash) {\n throw new Error('Missing settlement hash');\n }\n\n const { amountRaw, blockNumber } = await getTransferredAmountFromTxHash({\n chainId,\n messenger,\n tokenAddress,\n txHash: settlementHash,\n walletAddress: recipient,\n });\n\n if (!amountRaw) {\n throw new Error(\n `Could not determine settled amount from transaction ${settlementHash}`,\n );\n }\n\n log('Resolved settled amount', {\n amountRaw,\n blockNumber,\n chainId,\n recipient,\n settlementHash,\n });\n\n return { amountRaw, fromBlock: blockNumber };\n}\n\n/**\n * Submits the second-leg batch and waits for every child transaction to\n * confirm.\n *\n * @param options - Submit options.\n * @param options.chainId - Chain to submit the batch on.\n * @param options.from - Account submitting the batch.\n * @param options.messenger - Controller messenger.\n * @param options.nestedTransactions - Calls to submit.\n * @param options.sourceAmountRaw - Settled amount in raw units, for logging.\n * @param options.sponsored - Whether gas is sponsored.\n * @param options.transaction - Parent transaction meta.\n * @returns Hash of the final submitted child transaction.\n */\nasync function submitBatch({\n chainId,\n from,\n messenger,\n nestedTransactions,\n sourceAmountRaw,\n sponsored,\n transaction,\n}: {\n chainId: Hex;\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n nestedTransactions: NestedTransactionMetadata[];\n sourceAmountRaw: string;\n sponsored: boolean;\n transaction: TransactionMeta;\n}): Promise<{ transactionHash: Hex }> {\n const transactionId = transaction.id;\n const networkClientId = getNetworkClientId(messenger, chainId);\n const transactionIds: string[] = [];\n\n const { end } = collectTransactionIds(chainId, from, messenger, (id) => {\n transactionIds.push(id);\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Add required transaction ID from second leg submission',\n },\n (tx) => {\n tx.requiredTransactionIds ??= [];\n tx.requiredTransactionIds.push(id);\n },\n );\n });\n\n const logContext = {\n chainId,\n from,\n nestedTransactionCount: nestedTransactions.length,\n networkClientId,\n sourceAmountRaw,\n transactionId,\n };\n\n log('Submitting second leg', logContext);\n\n try {\n await messenger.call('TransactionController:addTransactionBatch', {\n disableHook: true,\n disableSequential: true,\n disableUpgrade: true,\n from,\n isGasFeeSponsored: sponsored,\n isInternal: true,\n networkClientId,\n origin: ORIGIN_METAMASK,\n requireApproval: false,\n skipInitialGasEstimate: true,\n transactions: nestedTransactions.map((nestedTransaction, index) => ({\n params: {\n data: nestedTransaction.data,\n to: nestedTransaction.to,\n value: nestedTransaction.value ?? '0x0',\n },\n type:\n index === 0\n ? (nestedTransaction.type ?? TransactionType.tokenMethodApprove)\n : TransactionType.contractInteraction,\n })),\n });\n } finally {\n end();\n }\n\n log('Submitted second leg', { ...logContext, transactionIds });\n\n if (!transactionIds.length) {\n throw new Error('No transactions submitted');\n }\n\n await Promise.all(\n transactionIds.map((id) => waitForTransactionConfirmed(id, messenger)),\n );\n\n const hash = getTransaction(transactionIds.slice(-1)[0], messenger)?.hash;\n\n if (!hash) {\n throw new Error('Missing transaction hash');\n }\n\n log('Confirmed second leg', { ...logContext, hash, transactionIds });\n\n return { transactionHash: hash as Hex };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/transaction-pay-controller",
3
- "version": "30.0.3-preview-44b7ded21",
3
+ "version": "30.1.0-preview-2750df1dc",
4
4
  "description": "Manages alternate payment strategies to provide required funds for transactions in MetaMask",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -55,7 +55,7 @@
55
55
  "@ethersproject/contracts": "^5.7.0",
56
56
  "@ethersproject/providers": "^5.8.0",
57
57
  "@metamask/accounts-controller": "^40.0.0",
58
- "@metamask/assets-controller": "^18.0.1",
58
+ "@metamask/assets-controller": "^19.0.0",
59
59
  "@metamask/base-controller": "^10.0.0",
60
60
  "@metamask/controller-utils": "^13.0.0",
61
61
  "@metamask/gas-fee-controller": "^27.0.0",
@@ -1,40 +0,0 @@
1
- import type { BatchTransactionParams, TransactionMeta } from '@metamask/transaction-controller';
2
- import type { Hex } from '@metamask/utils';
3
- import type { TransactionPayControllerMessenger } from '../types.js';
4
- export declare const VAULT_ERROR_PREFIX = "Vault: ";
5
- /**
6
- * Submits a Money Account mUSD vault deposit batch on Monad once the source
7
- * mUSD has settled in the Money Account (fiat on-ramp, Relay bridge, or any
8
- * other path). Re-encodes the original nested vault calldata with the
9
- * settled `sourceAmountRaw` via `getAmountData` and submits as a sponsored,
10
- * internal EIP-7702 batch. Callers decide whether to honour any vault
11
- * kill-switch by passing `vaultDisabled`.
12
- *
13
- * @param options - Submit options.
14
- * @param options.fromBlock - Block number to start searching for CHOMP deposits.
15
- * @param options.messenger - Controller messenger.
16
- * @param options.moneyAccountAddress - Money Account address sending the vault
17
- * deposit. Defaults to `transaction.txParams.from` (the deposit-flow sender);
18
- * withdraw flows pass it explicitly since their `from` is the funding EOA.
19
- * @param options.depositCalls - Pre-built vault-deposit batch for withdraw
20
- * flows, whose parent transaction carries no vault calls. When omitted the
21
- * batch is derived from the transaction's own nested calls re-encoded via
22
- * `getAmountData`.
23
- * @param options.sourceAmountRaw - Settled mUSD amount in raw units.
24
- * @param options.transaction - Original Money Account transaction meta.
25
- * @param options.vaultDisabled - When `true`, skip the vault batch and leave
26
- * the settled mUSD in the Money Account. Caller-evaluated kill-switch.
27
- * @returns Hash of the final submitted child transaction, if available.
28
- */
29
- export declare function submitMoneyAccountVaultDeposit({ fromBlock, messenger, moneyAccountAddress: moneyAccountAddressOverride, depositCalls, sourceAmountRaw, transaction, vaultDisabled, }: {
30
- fromBlock?: Hex;
31
- messenger: TransactionPayControllerMessenger;
32
- moneyAccountAddress?: Hex;
33
- depositCalls?: BatchTransactionParams[];
34
- sourceAmountRaw: string;
35
- transaction: TransactionMeta;
36
- vaultDisabled: boolean;
37
- }): Promise<{
38
- transactionHash?: Hex;
39
- }>;
40
- //# sourceMappingURL=ma-vault-deposit.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ma-vault-deposit.d.ts","sourceRoot":"","sources":["../../src/utils/ma-vault-deposit.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,sBAAsB,EAEtB,eAAe,EAChB,MAAM,kCAAkC,CAAC;AAE1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAK3C,OAAO,KAAK,EAAE,iCAAiC,EAAE,MAAM,aAAa,CAAC;AAarE,eAAO,MAAM,kBAAkB,YAAY,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,8BAA8B,CAAC,EACnD,SAAS,EACT,SAAS,EACT,mBAAmB,EAAE,2BAA2B,EAChD,YAAY,EACZ,eAAe,EACf,WAAW,EACX,aAAa,GACd,EAAE;IACD,SAAS,CAAC,EAAE,GAAG,CAAC;IAChB,SAAS,EAAE,iCAAiC,CAAC;IAC7C,mBAAmB,CAAC,EAAE,GAAG,CAAC;IAC1B,YAAY,CAAC,EAAE,sBAAsB,EAAE,CAAC;IACxC,eAAe,EAAE,MAAM,CAAC;IACxB,WAAW,EAAE,eAAe,CAAC;IAC7B,aAAa,EAAE,OAAO,CAAC;CACxB,GAAG,OAAO,CAAC;IAAE,eAAe,CAAC,EAAE,GAAG,CAAA;CAAE,CAAC,CAwJrC"}
@@ -1,230 +0,0 @@
1
- import { ORIGIN_METAMASK } from '@metamask/controller-utils';
2
- import { TransactionType } from '@metamask/transaction-controller';
3
- import { createModuleLogger } from '@metamask/utils';
4
- import { projectLogger } from '../logger.js';
5
- import { MUSD_MONAD_FIAT_ASSET } from '../strategy/fiat/constants.js';
6
- import { findRecentChompVaultDeposit } from './chomp.js';
7
- import { prefixError } from './error-prefix.js';
8
- import { getNetworkClientId } from './provider.js';
9
- import { collectTransactionIds, getTransaction, updateTransaction, waitForTransactionConfirmed, } from './transaction.js';
10
- const log = createModuleLogger(projectLogger, 'ma-vault-deposit');
11
- export const VAULT_ERROR_PREFIX = 'Vault: ';
12
- /**
13
- * Submits a Money Account mUSD vault deposit batch on Monad once the source
14
- * mUSD has settled in the Money Account (fiat on-ramp, Relay bridge, or any
15
- * other path). Re-encodes the original nested vault calldata with the
16
- * settled `sourceAmountRaw` via `getAmountData` and submits as a sponsored,
17
- * internal EIP-7702 batch. Callers decide whether to honour any vault
18
- * kill-switch by passing `vaultDisabled`.
19
- *
20
- * @param options - Submit options.
21
- * @param options.fromBlock - Block number to start searching for CHOMP deposits.
22
- * @param options.messenger - Controller messenger.
23
- * @param options.moneyAccountAddress - Money Account address sending the vault
24
- * deposit. Defaults to `transaction.txParams.from` (the deposit-flow sender);
25
- * withdraw flows pass it explicitly since their `from` is the funding EOA.
26
- * @param options.depositCalls - Pre-built vault-deposit batch for withdraw
27
- * flows, whose parent transaction carries no vault calls. When omitted the
28
- * batch is derived from the transaction's own nested calls re-encoded via
29
- * `getAmountData`.
30
- * @param options.sourceAmountRaw - Settled mUSD amount in raw units.
31
- * @param options.transaction - Original Money Account transaction meta.
32
- * @param options.vaultDisabled - When `true`, skip the vault batch and leave
33
- * the settled mUSD in the Money Account. Caller-evaluated kill-switch.
34
- * @returns Hash of the final submitted child transaction, if available.
35
- */
36
- export async function submitMoneyAccountVaultDeposit({ fromBlock, messenger, moneyAccountAddress: moneyAccountAddressOverride, depositCalls, sourceAmountRaw, transaction, vaultDisabled, }) {
37
- const transactionId = transaction.id;
38
- const moneyAccountAddress = (moneyAccountAddressOverride ??
39
- transaction.txParams.from);
40
- if (!moneyAccountAddress) {
41
- throw new Error('Missing Money Account address');
42
- }
43
- if (vaultDisabled) {
44
- log('Skipping vault deposit because vaultDisabled is true', {
45
- moneyAccountAddress,
46
- sourceAmountRaw,
47
- transactionId,
48
- });
49
- return { transactionHash: '0x' };
50
- }
51
- const nestedTransactions = await resolveVaultDepositBatch({
52
- depositCalls,
53
- messenger,
54
- sourceAmountRaw,
55
- transaction,
56
- transactionId,
57
- });
58
- // CHOMP pre-check: skip addTransactionBatch entirely if CHOMP has already
59
- // auto-vaulted the funds during or before the checkout window.
60
- const preChompHash = await tryFindChompDeposit({
61
- fromBlock,
62
- messenger,
63
- moneyAccountAddress,
64
- sourceAmountRaw,
65
- transactionId,
66
- });
67
- if (preChompHash) {
68
- return { transactionHash: preChompHash };
69
- }
70
- const networkClientId = getNetworkClientId(messenger, MUSD_MONAD_FIAT_ASSET.chainId);
71
- const transactionIds = [];
72
- const { end } = collectTransactionIds(MUSD_MONAD_FIAT_ASSET.chainId, moneyAccountAddress, messenger, (id) => {
73
- transactionIds.push(id);
74
- updateTransaction({
75
- transactionId,
76
- messenger,
77
- note: 'Add required transaction ID from Money Account vault submission',
78
- }, (tx) => {
79
- tx.requiredTransactionIds ??= [];
80
- tx.requiredTransactionIds.push(id);
81
- });
82
- });
83
- log('Submitting Money Account vault deposit', {
84
- moneyAccountAddress,
85
- nestedTransactionCount: nestedTransactions.length,
86
- networkClientId,
87
- sourceAmountRaw,
88
- transactionId,
89
- });
90
- try {
91
- await messenger.call('TransactionController:addTransactionBatch', {
92
- disableHook: true,
93
- disableSequential: true,
94
- disableUpgrade: true,
95
- from: moneyAccountAddress,
96
- isGasFeeSponsored: true,
97
- isInternal: true,
98
- networkClientId,
99
- origin: ORIGIN_METAMASK,
100
- requireApproval: false,
101
- skipInitialGasEstimate: true,
102
- transactions: nestedTransactions.map((nestedTransaction, index) => ({
103
- params: {
104
- data: nestedTransaction.data,
105
- to: nestedTransaction.to,
106
- value: nestedTransaction.value ?? '0x0',
107
- },
108
- type: index === 0
109
- ? (nestedTransaction.type ?? TransactionType.tokenMethodApprove)
110
- : TransactionType.contractInteraction,
111
- })),
112
- });
113
- }
114
- catch (error) {
115
- // CHOMP post-check: CHOMP may have won the race between pre-check and
116
- // submit. Return the CHOMP hash instead of surfacing a Vault-prefixed error.
117
- const postChompHash = await tryFindChompDeposit({
118
- fromBlock,
119
- messenger,
120
- moneyAccountAddress,
121
- sourceAmountRaw,
122
- transactionId,
123
- });
124
- if (postChompHash) {
125
- return { transactionHash: postChompHash };
126
- }
127
- throw prefixError(error, VAULT_ERROR_PREFIX);
128
- }
129
- finally {
130
- end();
131
- }
132
- log('Submitted Money Account vault deposit', {
133
- moneyAccountAddress,
134
- nestedTransactionCount: nestedTransactions.length,
135
- networkClientId,
136
- sourceAmountRaw,
137
- transactionId,
138
- transactionIds,
139
- });
140
- if (!transactionIds.length) {
141
- throw new Error('No transactions submitted');
142
- }
143
- await Promise.all(transactionIds.map((id) => waitForTransactionConfirmed(id, messenger)));
144
- const hash = getTransaction(transactionIds.slice(-1)[0], messenger)?.hash;
145
- if (!hash) {
146
- throw new Error('Missing transaction hash');
147
- }
148
- log('Confirmed Money Account vault deposit', {
149
- hash,
150
- moneyAccountAddress,
151
- nestedTransactionCount: nestedTransactions.length,
152
- networkClientId,
153
- sourceAmountRaw,
154
- transactionId,
155
- transactionIds,
156
- });
157
- return { transactionHash: hash };
158
- }
159
- /**
160
- * Resolves the vault-deposit batch (approve + teller deposit) to submit.
161
- *
162
- * Withdraw flows have no vault calls on their own nested transactions, so the
163
- * caller supplies a freshly built `depositCalls` batch. Deposit flows re-encode
164
- * their existing nested vault calldata with the settled amount via
165
- * `getAmountData` and also mutate the parent transaction so its stored calls
166
- * and `requiredAssets` reflect the settled amount.
167
- *
168
- * @param options - Resolution options.
169
- * @param options.depositCalls - Pre-built deposit batch for withdraw flows.
170
- * @param options.messenger - Controller messenger.
171
- * @param options.sourceAmountRaw - Settled mUSD amount in raw units.
172
- * @param options.transaction - Original Money Account transaction meta.
173
- * @param options.transactionId - ID of the original transaction.
174
- * @returns Nested transactions to submit as the vault deposit batch.
175
- */
176
- async function resolveVaultDepositBatch({ depositCalls, messenger, sourceAmountRaw, transaction, transactionId, }) {
177
- if (depositCalls?.length) {
178
- return depositCalls;
179
- }
180
- const updatedTransaction = getTransaction(transactionId, messenger) ?? transaction;
181
- const { updates } = await messenger.call('TransactionPayController:getAmountData', {
182
- amount: sourceAmountRaw,
183
- transaction: updatedTransaction,
184
- });
185
- if (!updates.length) {
186
- throw new Error('No amount updates');
187
- }
188
- const nestedTransactions = updatedTransaction.nestedTransactions?.map((nestedTransaction) => ({ ...nestedTransaction }));
189
- if (!nestedTransactions?.length) {
190
- throw new Error('Missing nested transactions');
191
- }
192
- for (const { nestedTransactionIndex, data } of updates) {
193
- if (nestedTransactions[nestedTransactionIndex]) {
194
- nestedTransactions[nestedTransactionIndex].data = data;
195
- }
196
- }
197
- updateTransaction({
198
- transactionId,
199
- messenger,
200
- note: 'Money Account vault deposit: update vault amount',
201
- }, (tx) => {
202
- for (const { nestedTransactionIndex, data } of updates) {
203
- if (tx.nestedTransactions?.[nestedTransactionIndex]) {
204
- tx.nestedTransactions[nestedTransactionIndex].data = data;
205
- }
206
- }
207
- if (tx.requiredAssets?.[0]) {
208
- tx.requiredAssets[0].amount = `0x${BigInt(sourceAmountRaw).toString(16)}`;
209
- }
210
- });
211
- return nestedTransactions;
212
- }
213
- async function tryFindChompDeposit({ fromBlock, messenger, moneyAccountAddress, sourceAmountRaw, transactionId, }) {
214
- if (!fromBlock) {
215
- return undefined;
216
- }
217
- try {
218
- return await findRecentChompVaultDeposit({
219
- fromBlock,
220
- messenger,
221
- moneyAccountAddress,
222
- sourceAmountRaw,
223
- });
224
- }
225
- catch (chompError) {
226
- log('CHOMP check failed', { chompError, transactionId });
227
- return undefined;
228
- }
229
- }
230
- //# sourceMappingURL=ma-vault-deposit.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ma-vault-deposit.js","sourceRoot":"","sources":["../../src/utils/ma-vault-deposit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAM7D,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAEnE,OAAO,E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AAU,EAAE,aAAa,EAAE,CAAC,CAAC;QACzD,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["import { ORIGIN_METAMASK } from '@metamask/controller-utils';\nimport type {\n BatchTransactionParams,\n NestedTransactionMetadata,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger.js';\nimport { MUSD_MONAD_FIAT_ASSET } from '../strategy/fiat/constants.js';\nimport type { TransactionPayControllerMessenger } from '../types.js';\nimport { findRecentChompVaultDeposit } from './chomp.js';\nimport { prefixError } from './error-prefix.js';\nimport { getNetworkClientId } from './provider.js';\nimport {\n collectTransactionIds,\n getTransaction,\n updateTransaction,\n waitForTransactionConfirmed,\n} from './transaction.js';\n\nconst log = createModuleLogger(projectLogger, 'ma-vault-deposit');\n\nexport const VAULT_ERROR_PREFIX = 'Vault: ';\n\n/**\n * Submits a Money Account mUSD vault deposit batch on Monad once the source\n * mUSD has settled in the Money Account (fiat on-ramp, Relay bridge, or any\n * other path). Re-encodes the original nested vault calldata with the\n * settled `sourceAmountRaw` via `getAmountData` and submits as a sponsored,\n * internal EIP-7702 batch. Callers decide whether to honour any vault\n * kill-switch by passing `vaultDisabled`.\n *\n * @param options - Submit options.\n * @param options.fromBlock - Block number to start searching for CHOMP deposits.\n * @param options.messenger - Controller messenger.\n * @param options.moneyAccountAddress - Money Account address sending the vault\n * deposit. Defaults to `transaction.txParams.from` (the deposit-flow sender);\n * withdraw flows pass it explicitly since their `from` is the funding EOA.\n * @param options.depositCalls - Pre-built vault-deposit batch for withdraw\n * flows, whose parent transaction carries no vault calls. When omitted the\n * batch is derived from the transaction's own nested calls re-encoded via\n * `getAmountData`.\n * @param options.sourceAmountRaw - Settled mUSD amount in raw units.\n * @param options.transaction - Original Money Account transaction meta.\n * @param options.vaultDisabled - When `true`, skip the vault batch and leave\n * the settled mUSD in the Money Account. Caller-evaluated kill-switch.\n * @returns Hash of the final submitted child transaction, if available.\n */\nexport async function submitMoneyAccountVaultDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress: moneyAccountAddressOverride,\n depositCalls,\n sourceAmountRaw,\n transaction,\n vaultDisabled,\n}: {\n fromBlock?: Hex;\n messenger: TransactionPayControllerMessenger;\n moneyAccountAddress?: Hex;\n depositCalls?: BatchTransactionParams[];\n sourceAmountRaw: string;\n transaction: TransactionMeta;\n vaultDisabled: boolean;\n}): Promise<{ transactionHash?: Hex }> {\n const transactionId = transaction.id;\n const moneyAccountAddress = (moneyAccountAddressOverride ??\n transaction.txParams.from) as Hex | undefined;\n\n if (!moneyAccountAddress) {\n throw new Error('Missing Money Account address');\n }\n\n if (vaultDisabled) {\n log('Skipping vault deposit because vaultDisabled is true', {\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n });\n\n return { transactionHash: '0x' };\n }\n\n const nestedTransactions = await resolveVaultDepositBatch({\n depositCalls,\n messenger,\n sourceAmountRaw,\n transaction,\n transactionId,\n });\n\n // CHOMP pre-check: skip addTransactionBatch entirely if CHOMP has already\n // auto-vaulted the funds during or before the checkout window.\n const preChompHash = await tryFindChompDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n });\n\n if (preChompHash) {\n return { transactionHash: preChompHash };\n }\n\n const networkClientId = getNetworkClientId(\n messenger,\n MUSD_MONAD_FIAT_ASSET.chainId,\n );\n const transactionIds: string[] = [];\n const { end } = collectTransactionIds(\n MUSD_MONAD_FIAT_ASSET.chainId,\n moneyAccountAddress,\n messenger,\n (id) => {\n transactionIds.push(id);\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Add required transaction ID from Money Account vault submission',\n },\n (tx) => {\n tx.requiredTransactionIds ??= [];\n tx.requiredTransactionIds.push(id);\n },\n );\n },\n );\n\n log('Submitting Money Account vault deposit', {\n moneyAccountAddress,\n nestedTransactionCount: nestedTransactions.length,\n networkClientId,\n sourceAmountRaw,\n transactionId,\n });\n\n try {\n await messenger.call('TransactionController:addTransactionBatch', {\n disableHook: true,\n disableSequential: true,\n disableUpgrade: true,\n from: moneyAccountAddress,\n isGasFeeSponsored: true,\n isInternal: true,\n networkClientId,\n origin: ORIGIN_METAMASK,\n requireApproval: false,\n skipInitialGasEstimate: true,\n transactions: nestedTransactions.map((nestedTransaction, index) => ({\n params: {\n data: nestedTransaction.data,\n to: nestedTransaction.to,\n value: nestedTransaction.value ?? '0x0',\n },\n type:\n index === 0\n ? (nestedTransaction.type ?? TransactionType.tokenMethodApprove)\n : TransactionType.contractInteraction,\n })),\n });\n } catch (error) {\n // CHOMP post-check: CHOMP may have won the race between pre-check and\n // submit. Return the CHOMP hash instead of surfacing a Vault-prefixed error.\n const postChompHash = await tryFindChompDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n });\n\n if (postChompHash) {\n return { transactionHash: postChompHash };\n }\n\n throw prefixError(error, VAULT_ERROR_PREFIX);\n } finally {\n end();\n }\n\n log('Submitted Money Account vault deposit', {\n moneyAccountAddress,\n nestedTransactionCount: nestedTransactions.length,\n networkClientId,\n sourceAmountRaw,\n transactionId,\n transactionIds,\n });\n\n if (!transactionIds.length) {\n throw new Error('No transactions submitted');\n }\n\n await Promise.all(\n transactionIds.map((id) => waitForTransactionConfirmed(id, messenger)),\n );\n\n const hash = getTransaction(transactionIds.slice(-1)[0], messenger)?.hash;\n\n if (!hash) {\n throw new Error('Missing transaction hash');\n }\n\n log('Confirmed Money Account vault deposit', {\n hash,\n moneyAccountAddress,\n nestedTransactionCount: nestedTransactions.length,\n networkClientId,\n sourceAmountRaw,\n transactionId,\n transactionIds,\n });\n\n return { transactionHash: hash as Hex };\n}\n\n/**\n * Resolves the vault-deposit batch (approve + teller deposit) to submit.\n *\n * Withdraw flows have no vault calls on their own nested transactions, so the\n * caller supplies a freshly built `depositCalls` batch. Deposit flows re-encode\n * their existing nested vault calldata with the settled amount via\n * `getAmountData` and also mutate the parent transaction so its stored calls\n * and `requiredAssets` reflect the settled amount.\n *\n * @param options - Resolution options.\n * @param options.depositCalls - Pre-built deposit batch for withdraw flows.\n * @param options.messenger - Controller messenger.\n * @param options.sourceAmountRaw - Settled mUSD amount in raw units.\n * @param options.transaction - Original Money Account transaction meta.\n * @param options.transactionId - ID of the original transaction.\n * @returns Nested transactions to submit as the vault deposit batch.\n */\nasync function resolveVaultDepositBatch({\n depositCalls,\n messenger,\n sourceAmountRaw,\n transaction,\n transactionId,\n}: {\n depositCalls?: BatchTransactionParams[];\n messenger: TransactionPayControllerMessenger;\n sourceAmountRaw: string;\n transaction: TransactionMeta;\n transactionId: string;\n}): Promise<NestedTransactionMetadata[]> {\n if (depositCalls?.length) {\n return depositCalls;\n }\n\n const updatedTransaction =\n getTransaction(transactionId, messenger) ?? transaction;\n const { updates } = await messenger.call(\n 'TransactionPayController:getAmountData',\n {\n amount: sourceAmountRaw,\n transaction: updatedTransaction,\n },\n );\n\n if (!updates.length) {\n throw new Error('No amount updates');\n }\n\n const nestedTransactions = updatedTransaction.nestedTransactions?.map(\n (nestedTransaction) => ({ ...nestedTransaction }),\n );\n\n if (!nestedTransactions?.length) {\n throw new Error('Missing nested transactions');\n }\n\n for (const { nestedTransactionIndex, data } of updates) {\n if (nestedTransactions[nestedTransactionIndex]) {\n nestedTransactions[nestedTransactionIndex].data = data;\n }\n }\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Money Account vault deposit: update vault amount',\n },\n (tx) => {\n for (const { nestedTransactionIndex, data } of updates) {\n if (tx.nestedTransactions?.[nestedTransactionIndex]) {\n tx.nestedTransactions[nestedTransactionIndex].data = data;\n }\n }\n\n if (tx.requiredAssets?.[0]) {\n tx.requiredAssets[0].amount = `0x${BigInt(sourceAmountRaw).toString(\n 16,\n )}`;\n }\n },\n );\n\n return nestedTransactions;\n}\n\nasync function tryFindChompDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n}: {\n fromBlock: Hex | undefined;\n messenger: TransactionPayControllerMessenger;\n moneyAccountAddress: Hex;\n sourceAmountRaw: string;\n transactionId: string;\n}): Promise<Hex | undefined> {\n if (!fromBlock) {\n return undefined;\n }\n\n try {\n return await findRecentChompVaultDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n });\n } catch (chompError) {\n log('CHOMP check failed', { chompError, transactionId });\n return undefined;\n }\n}\n"]}