Skip to content

fix: MMPay fiat payment fixes #8987

Open
OGPoyraz wants to merge 18 commits into
mainfrom
ogp/fiat-money-account-deposit-fix
Open

fix: MMPay fiat payment fixes #8987
OGPoyraz wants to merge 18 commits into
mainfrom
ogp/fiat-money-account-deposit-fix

Conversation

@OGPoyraz
Copy link
Copy Markdown
Member

@OGPoyraz OGPoyraz commented Jun 3, 2026

Explanation

Fiat payments for moneyAccountDeposit transactions fail with multiple sequential errors after the on-ramp order settles:

  1. isMaxAmount: true in the fiat re-quote — after Transak settles, submitRelayAfterFiatCompletion re-quotes with isMaxAmount: true, isPostQuote: false. This calls processTransactions, which throws "Max amount quotes do not support included transactions" because moneyAccountDeposit has nested txs (approve + deposit) that require delegation.

  2. validateRelaySlippage compares wrong amounts — it compares currencyOut.amount from two relay quotes made with different source amounts (theoretical $5 quoting phase vs actual ~$4.95 post-Transak settlement). This produces ~25% apparent "slippage" that is not real slippage — it is just a smaller input producing a smaller output.

  3. Nested calldata has zero amounts — the fiat path in handleDone only sets amountFiat and never calls updateTokenAmount(), so requiredAssets.amount stays 0x0 and the nested approve + deposit calldata encodes zero amounts.

  4. Wrong wallet address in fiat flowfiat-quotes.ts and fiat-submit.ts used transaction.txParams.from as the wallet address. For moneyAccountDeposit, txParams.from is the money account address on the target chain (Monad), not the user's EOA. This caused Ramps/Transak to receive the wrong deposit address, resolveSourceAmountRaw to look for on-chain ETH at the wrong address, and all relay quotes to use the wrong from/user address — resulting in TRANSFER_FROM_FAILED reverts.

  5. Fiat total calculation using wrong amountcalculateTotals derived the payment amount from token amounts or targetAmount, which is incorrect for fiat flows where the user enters a specific fiat amount.

Changes

fiat-quotes.ts — uses accountOverride when available for walletAddress, matching the existing pattern in quotes.ts. This ensures Ramps/Transak receives the user's actual EOA address, not the money account address.

fiat-submit.ts — two wallet address fixes plus three-phase relay flow:

  • submitFiatQuotes: uses accountOverride ?? txParams.from for order polling wallet address
  • submitRelayAfterFiatCompletion: uses baseRequest.from (already accountOverride-aware from the quote) for on-chain amount lookup
  • Phase 1: Discovery relay quote (isPostQuote: true, EXACT_INPUT) with the settled source amount to learn currencyOut.minimumAmount
  • Phase 2: Calls getAmountData via messenger to delegate calldata re-encoding to the client, then patches nested tx data + requiredAssets[0].amount
  • Phase 3: Real relay quote (isPostQuote: false, EXACT_OUTPUT) with delegation

relay-submit.ts — reverts the isExecute balance skip (no longer needed with correct wallet address). The balance check now correctly validates the user's EOA balance.

validateRelaySlippagevalidateRelayRateDrift — compares USD exchange rate ratios (output_usd / input_usd) between original and discovery quotes instead of absolute amounts, normalising for different source amounts.

TransactionPayController — adds optional getAmountData callback on the constructor, exposed via messenger as TransactionPayController:getAmountData. Keeps ABI knowledge on the client side.

totals.ts — adds fiatPaymentAmount parameter to calculateTotals. When a fiat strategy quote is present, uses the user-entered fiat payment amount directly instead of deriving it from token amounts or relay targetAmount. Falls back to '0' if fiat amount is unavailable.

quotes.ts — passes fiatPayment.amountFiat from the transaction pay state into calculateTotals as fiatPaymentAmount.

References

Checklist

  • I've updated the test suite for new or updated code as appropriate
  • I've updated documentation (JSDoc, Markdown, etc.) for new or updated code as appropriate
  • I've communicated my changes to consumers by updating changelogs for packages I've changed
  • I've introduced breaking changes in this PR and have prepared draft pull requests for clients and consumer packages to resolve them

Note

High Risk
Changes post-settlement fiat relay submission, on-ramp wallet resolution, and calldata patching for money-account deposits—errors could block payments or submit wrong amounts without a matching client getAmountData implementation.

Overview
Fixes MetaMask Pay fiat flows after on-ramp settlement, especially moneyAccountDeposit with nested approve/deposit calldata.

TransactionPayController gains an optional getAmountData callback and TransactionPayController:getAmountData messenger action so the client can re-encode nested transaction data for a settled token amount (defaults to empty updates).

fiat-submit.ts is reworked post-order completion:

  • Wallet for ramps polling uses accountOverride ?? txParams.from; on-chain source resolution uses baseRequest.from.
  • Simple deposits (fewer than two nested txs): one post-settlement relay quote with isMaxAmount: false, isPostQuote: true (avoids max-amount + included-tx errors).
  • Nested calldata (≥2 nested txs): discovery quote → getAmountData → patch nested data and requiredAssets[0].amountdelegation quote with targetAmountMinimum.
  • validateRelaySlippage is replaced by validateRelayRateDrift, comparing USD in/out ratios (10% max) instead of raw output amounts.

Totals: calculateTotals takes fiatPaymentAmount; when a fiat strategy quote is present, totals use the user-entered fiat amount (via quotes.ts passing fiatPayment.amountFiat), not relay targetAmount.

Exports and tests cover the new API and both relay paths.

Reviewed by Cursor Bugbot for commit d9d35fd. Bugbot is set up for automated code reviews on this repo. Configure here.

@OGPoyraz OGPoyraz requested a review from a team as a code owner June 3, 2026 12:24
@OGPoyraz OGPoyraz marked this pull request as draft June 3, 2026 12:24
@OGPoyraz OGPoyraz temporarily deployed to default-branch June 3, 2026 12:24 — with GitHub Actions Inactive
@OGPoyraz OGPoyraz changed the title Ogp/fiat money account deposit fix fix: Fiat flow on MoneyAccountDeposit Jun 3, 2026
@OGPoyraz OGPoyraz force-pushed the ogp/fiat-money-account-deposit-fix branch from 3f77b67 to 0560a35 Compare June 3, 2026 12:31
@OGPoyraz OGPoyraz marked this pull request as ready for review June 3, 2026 13:04
@OGPoyraz OGPoyraz requested a review from a team as a code owner June 3, 2026 13:04
@OGPoyraz OGPoyraz temporarily deployed to default-branch June 3, 2026 13:04 — with GitHub Actions Inactive
@OGPoyraz OGPoyraz force-pushed the ogp/fiat-money-account-deposit-fix branch from b3b05dd to 8ca96e8 Compare June 3, 2026 13:25
Comment thread packages/transaction-pay-controller/src/strategy/fiat/fiat-submit.ts Outdated
Comment thread packages/transaction-pay-controller/src/strategy/relay/relay-submit.test.ts Outdated
Comment thread packages/transaction-pay-controller/src/utils/totals.ts
Comment thread packages/transaction-pay-controller/src/utils/totals.ts
@OGPoyraz OGPoyraz changed the title fix: Fiat flow on MoneyAccountDeposit fix: MMPay fiat payment fixes Jun 3, 2026
### Added

- Add optional `getAmountData` callback to `TransactionPayControllerOptions` for client-side nested calldata re-encoding ([#8987](https://github.com/MetaMask/core/pull/8987))
- Add `TransactionPayController:getAmountData` messenger action ([#8987](https://github.com/MetaMask/core/pull/8987))
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we combine / nest some or all of these?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done


export type GetAmountDataRequest = {
/** Raw token amount (atomic units) to encode into calldata. */
amount: string;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor, I think getPaymentOverrideData provides the human / formatted amount. Not sure which is easier for the client to handle.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

buildMoneyAccountDepositBatch in client was expecting raw amount hence I passed as is.
For reference: https://github.com/MetaMask/metamask-mobile/pull/31009/files#diff-c2390f54bc74c73163ad5949d6accb3524100bf2dd425db4dd82c1ed73d7076f

refundTo,
sourceAmounts,
tokens,
fiatPayment,
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor, alphabetical.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

? targetAmount.fiat
: amountFiat,
)
.plus(paymentAmountFiat)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For clarity and consistency, could we call this sourceAmountX and rename the function to getSourceAmount?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

const amountFiat = transactionData?.fiatPayment?.amountFiat;
const walletAddress = transaction.txParams.from as Hex;
const walletAddress =
transactionData?.accountOverride ?? (transaction.txParams.from as Hex);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed, this can always use request.from as it's the same calculation?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

const amountFiat = transactionData?.fiatPayment?.amountFiat;
const walletAddress = transaction.txParams.from as Hex;
const walletAddress =
transactionData?.accountOverride ?? (transaction.txParams.from as Hex);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On line 95, below, it looks like we were already added the relay fee to the fiat amount?

So was it just the UI that wasn't reflecting that?

Copy link
Copy Markdown
Member Author

@OGPoyraz OGPoyraz Jun 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes but this is just a quote, real order flow (headless buy) starts when we click "Add funds" in UI where we need the amount again (in useFiatConfirm).

You may ask "why we are not passing the fiat quote amount while starting headless buy", but somehow I never see what amount we requested originally in the quote, either less or more amount saved in fiat quote entity, not sure why. Hence I subtract the fiat provider fee from totals.total in client
https://github.com/MetaMask/metamask-mobile/pull/31009/files#diff-aafbaf61a37d99028f87dea7fbe81be4508bc20412d534db932c1a1cd83e59b6

(tx) => {
for (const { nestedTransactionIndex, data } of updates) {
if (tx.nestedTransactions?.[nestedTransactionIndex]) {
tx.nestedTransactions[nestedTransactionIndex].data = data;
Copy link
Copy Markdown
Member

@matthewwalsh0 matthewwalsh0 Jun 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we not to update data also? In which case should we look at updateAtomicData in the transaction controller? Or have the new callback return the full data also?

Or are we just updating enough so the Relay quote can generate the delegation and include in the quote?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just updating enough parts so only nestedTransactions as other parts will be unnecessary for final quote happening in the Phase3 below.

const relayRequest: QuoteRequest = {
...baseRequest,
isMaxAmount: false,
isPostQuote: false,
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this not need to be conditional?

If we're doing a Perps or Predict deposit for example, we won't need transaction data, so we will want to use EXACT_INPUT instead of EXACT_OUTPUT so we can ensure nothing left over and cheaper Relay fees.

We won't even need the first discovery quote in that case so can avoid an entire additional request?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very valid point, I will make sure perps predict cases to use EXACT_OUTPUT, thanks.


// Phase 3: Real relay quote with delegation (standard crypto-like flow).
const relayRequest: QuoteRequest = {
...baseRequest,
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're doing an EXACT_OUTPUT for money account deposit, what do we do with any remaining funds on the selected account after the fiat quote?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no clean way to avoid it, unfortunately it will leave some dust.

If we do the EXACT_INPUT for everything then the vault deposit calldata amount won't match what Relay delivers, causing reverts

targetAmountMinimum: settledTargetRaw,
};

const relayQuotes = await getRelayQuotes({
Copy link
Copy Markdown
Member

@matthewwalsh0 matthewwalsh0 Jun 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suppose we do a Ramps quote that gets $100 into the EOA.

And we get an EXACT_INPUT quote that tell us we can get $95.

And then we get our final EXACT_OUPUT quote targeting $95... Except the fees are higher in general on EXACT_OUTPUT, plus we now have our additional transaction data included. So what if it says the required source amount is $101?

Do we need to leave a buffer for additional cost so intentionally ask for less in the second quote? But that means we always have funds left over.

Or do we retry with repeating lower amounts until it's less than our balance? Meaning we have to repeatedly re-encode the amount.

Or do we just throw if we can't afford it? But that's not the user's fault so no way for them to remedy.

Essentially we have to consider the slippage twice, from original to discovery, and discovery to final.

Copy link
Copy Markdown
Member Author

@OGPoyraz OGPoyraz Jun 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Understood, so depends on the spread between EXACT_INPUT and EXACT_OUTPUT fees + the delegation gas overhead. I didn't foresee this point as I always did my tests on already delegated account.

There is no easy solution for that. But we can try adding potential buffer here for the non-delegated cases, which we can assume discovery phase determine partially (for fees) that. But not sure how can we determine the cost of delegation, maybe we can apply some dedicated amount for that. Would it make sense?

OGPoyraz added a commit that referenced this pull request Jun 4, 2026
- Consolidate duplicate changelog entries for #8987
- Alphabetize destructured properties in updateQuotes
- Rename getPaymentAmount to getSourceAmount for clarity
- Simplify walletAddress in fiat-quotes to use transaction.txParams.from
Copy link
Copy Markdown

@cursor cursor Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 5ce7386. Configure here.

OGPoyraz added 9 commits June 4, 2026 17:27
Add optional getAmountData callback that re-encodes nested transaction
calldata for a given token amount. Used by transaction types with
non-standard nested data (e.g. vault approve + deposit) that require
client-side context (vault config, RPC providers) to encode.
After fiat order settlement, use a three-phase relay flow:
1. Discovery quote (EXACT_INPUT) to find settled target token output
2. Re-encode nested calldata via getAmountData callback
3. Real relay quote with delegation (EXACT_OUTPUT) for execution

Also removes validateRelaySlippage which incorrectly compared outputs
from relay quotes made with different source amounts, and removes
isMaxAmount:true which caused delegation errors with nested transactions.
- Fix unnecessary type assertion on requiredAssets hex amount
- Add JSDoc @param tags to validateRelayRateDrift
- Update fiat-submit tests for three-phase relay flow
- Add getAmountData controller tests
- Add rate drift, stale calldata, and discovery quote error tests
- 100% test coverage maintained
A better post-settlement rate benefits the user and should not block
fiat completion. Remove .abs() so only positive drift (rate worsened)
is rejected.
- Remove unused args parameter
- Replace non-null assertions with optional chaining
OGPoyraz added 9 commits June 4, 2026 17:30
The execute flow uses Relay's relayer to handle the source-side
transaction, so the user's EOA does not need to hold the source
tokens at submit time. This was causing fiat moneyAccountDeposit
to fail with 'Insufficient source token balance' after Transak
settlement.
The fiat quoting and submission flows used transaction.txParams.from as
the wallet address. For moneyAccountDeposit, txParams.from is the money
account address on the target chain, not the user's EOA. This caused:

- Ramps/Transak to receive the wrong deposit address
- resolveSourceAmountRaw to look for on-chain ETH at the wrong address
- Relay quotes to use the wrong from/user address
- Balance validation to check the wrong account

Use accountOverride (the user's selected EVM account) when available,
matching the pattern already used in quotes.ts.

Also revert the isExecute balance skip (no longer needed with correct
address) and remove hasFiatStrategy from totals calculation.
Reverts the test changes from the isExecute balance skip commit since
the source code was also reverted. Restores the original test that
validates source balance for execute flows.
The test validated the removed hasFiatStrategy path in calculateTotals.
With fiat strategy now using amountFiat consistently, this test case
is no longer applicable.
Pass fiatPayment.amountFiat from quote context into calculateTotals so
the fiat flow uses the user-entered fiat amount for the total instead
of deriving it from token amounts or targetAmount.
- Consolidate duplicate changelog entries for #8987
- Alphabetize destructured properties in updateQuotes
- Rename getPaymentAmount to getSourceAmount for clarity
- Simplify walletAddress in fiat-quotes to use transaction.txParams.from
Transactions without nested calldata (e.g. Perps, Predict deposits) now
use a single EXACT_INPUT relay quote after fiat settlement instead of the
three-phase discovery + re-encoding + delegation flow.

This reduces relay calls from 3 to 1, uses cheaper EXACT_INPUT fees,
and avoids leftover dust on the source chain.

The three-phase flow is preserved for moneyAccountDeposit and other
transactions with nested calldata that requires re-encoding.
@OGPoyraz OGPoyraz force-pushed the ogp/fiat-money-account-deposit-fix branch from 5ce7386 to d9d35fd Compare June 4, 2026 15:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants