Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/transaction-pay-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Add CHOMP idempotency for direct mUSD vault deposits ([#9267](https://github.com/MetaMask/core/pull/9267))

### Fixed

- Wait for keyring unlock before executing fiat post-ramp second leg ([#9267](https://github.com/MetaMask/core/pull/9267))

## [23.16.1]

### Changed
Expand Down
194 changes: 194 additions & 0 deletions packages/transaction-pay-controller/src/strategy/fiat/chomp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
import type { Hex } from '@metamask/utils';

import { CHAIN_ID_MONAD, MUSD_MONAD_ADDRESS } from '../../constants';
import type { TransactionPayControllerMessenger } from '../../types';
import { rpcRequest } from '../../utils/provider';
import { findRecentChompVaultDeposit } from './chomp';

jest.mock('../../utils/provider');

const MONEY_ACCOUNT_ADDRESS =
'0x1111111111111111111111111111111111111111' as Hex;
const CHOMP_TX_HASH =
'0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef' as Hex;
const FROM_BLOCK = '0x100' as Hex;
const SOURCE_AMOUNT_RAW = '5000000'; // 5 mUSD (6 decimals)
// uint256 hex for 5000000 (>= source amount)
const TRANSFER_DATA_SUFFICIENT =
'0x00000000000000000000000000000000000000000000000000000000004c4b40';
// uint256 hex for 4999999 (< source amount)
const TRANSFER_DATA_INSUFFICIENT =
'0x00000000000000000000000000000000000000000000000000000000004c4b3f';

const ERC20_TRANSFER_TOPIC =
'0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';

function padAddress(address: string): string {
return `0x${address.replace(/^0x/u, '').toLowerCase().padStart(64, '0')}`;
}

const MONEY_ACCOUNT_PADDED = padAddress(MONEY_ACCOUNT_ADDRESS);

function buildMusdTransferLog(
txHash: Hex = CHOMP_TX_HASH,
data: string = TRANSFER_DATA_SUFFICIENT,
): {
address: string;
topics: string[];
data: string;
transactionHash: Hex;
} {
return {
address: MUSD_MONAD_ADDRESS,
data,
topics: [
ERC20_TRANSFER_TOPIC,
MONEY_ACCOUNT_PADDED,
padAddress('0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'),
],
transactionHash: txHash,
};
}

function buildMessenger(): TransactionPayControllerMessenger {
return {} as TransactionPayControllerMessenger;
}

describe('chomp', () => {
const rpcRequestMock = jest.mocked(rpcRequest);

beforeEach(() => {
jest.resetAllMocks();
});

describe('findRecentChompVaultDeposit', () => {
it('returns the CHOMP tx hash when a Transfer log with sufficient amount is found', async () => {
rpcRequestMock.mockResolvedValueOnce([buildMusdTransferLog()]);

const result = await findRecentChompVaultDeposit({
fromBlock: FROM_BLOCK,
messenger: buildMessenger(),
moneyAccountAddress: MONEY_ACCOUNT_ADDRESS,
sourceAmountRaw: SOURCE_AMOUNT_RAW,
});

expect(result).toBe(CHOMP_TX_HASH);
// Only eth_getLogs should have been called.
expect(rpcRequestMock).toHaveBeenCalledTimes(1);
});

it('returns undefined when the mUSD transfer amount is below the required amount', async () => {
rpcRequestMock.mockResolvedValueOnce([
buildMusdTransferLog(CHOMP_TX_HASH, TRANSFER_DATA_INSUFFICIENT),
]);

const result = await findRecentChompVaultDeposit({
fromBlock: FROM_BLOCK,
messenger: buildMessenger(),
moneyAccountAddress: MONEY_ACCOUNT_ADDRESS,
sourceAmountRaw: SOURCE_AMOUNT_RAW,
});

expect(result).toBeUndefined();
expect(rpcRequestMock).toHaveBeenCalledTimes(1);
});

it('returns undefined when no mUSD Transfer logs are found', async () => {
rpcRequestMock.mockResolvedValueOnce([]);

const result = await findRecentChompVaultDeposit({
fromBlock: FROM_BLOCK,
messenger: buildMessenger(),
moneyAccountAddress: MONEY_ACCOUNT_ADDRESS,
sourceAmountRaw: SOURCE_AMOUNT_RAW,
});

expect(result).toBeUndefined();
expect(rpcRequestMock).toHaveBeenCalledTimes(1);
});

it('queries eth_getLogs with the correct filter', async () => {
rpcRequestMock.mockResolvedValueOnce([]);

await findRecentChompVaultDeposit({
fromBlock: FROM_BLOCK,
messenger: buildMessenger(),
moneyAccountAddress: MONEY_ACCOUNT_ADDRESS,
sourceAmountRaw: SOURCE_AMOUNT_RAW,
});

expect(rpcRequestMock).toHaveBeenCalledWith(
expect.objectContaining({
chainId: CHAIN_ID_MONAD,
method: 'eth_getLogs',
params: [
expect.objectContaining({
address: MUSD_MONAD_ADDRESS,
fromBlock: FROM_BLOCK,
toBlock: 'latest',
topics: [ERC20_TRANSFER_TOPIC, MONEY_ACCOUNT_PADDED, null],
}),
],
}),
);
});

it('processes logs newest-first and returns the most recent match', async () => {
const olderHash =
'0x0000000000000000000000000000000000000000000000000000000000000001' as Hex;
const newerHash =
'0x0000000000000000000000000000000000000000000000000000000000000002' as Hex;

rpcRequestMock.mockResolvedValueOnce([
buildMusdTransferLog(olderHash),
buildMusdTransferLog(newerHash),
]);

const result = await findRecentChompVaultDeposit({
fromBlock: FROM_BLOCK,
messenger: buildMessenger(),
moneyAccountAddress: MONEY_ACCOUNT_ADDRESS,
sourceAmountRaw: SOURCE_AMOUNT_RAW,
});

expect(result).toBe(newerHash);
expect(rpcRequestMock).toHaveBeenCalledTimes(1);
});

it('skips logs with insufficient amount and returns the first sufficient one', async () => {
const insufficientHash =
'0x0000000000000000000000000000000000000000000000000000000000000001' as Hex;

rpcRequestMock.mockResolvedValueOnce([
buildMusdTransferLog(insufficientHash, TRANSFER_DATA_INSUFFICIENT),
buildMusdTransferLog(CHOMP_TX_HASH),
]);

const result = await findRecentChompVaultDeposit({
fromBlock: FROM_BLOCK,
messenger: buildMessenger(),
moneyAccountAddress: MONEY_ACCOUNT_ADDRESS,
sourceAmountRaw: SOURCE_AMOUNT_RAW,
});

// Logs reversed: CHOMP_TX_HASH checked first (newer), passes amount check.
expect(result).toBe(CHOMP_TX_HASH);
expect(rpcRequestMock).toHaveBeenCalledTimes(1);
});

it('treats a log with data "0x" as zero amount and skips it', async () => {
rpcRequestMock.mockResolvedValueOnce([
buildMusdTransferLog(CHOMP_TX_HASH, '0x'),
]);

const result = await findRecentChompVaultDeposit({
fromBlock: FROM_BLOCK,
messenger: buildMessenger(),
moneyAccountAddress: MONEY_ACCOUNT_ADDRESS,
sourceAmountRaw: SOURCE_AMOUNT_RAW,
});

expect(result).toBeUndefined();
});
});
});
86 changes: 86 additions & 0 deletions packages/transaction-pay-controller/src/strategy/fiat/chomp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import type { Hex } from '@metamask/utils';
import { createModuleLogger } from '@metamask/utils';

import { CHAIN_ID_MONAD, MUSD_MONAD_ADDRESS } from '../../constants';
import { projectLogger } from '../../logger';
import type { TransactionPayControllerMessenger } from '../../types';
import { rpcRequest } from '../../utils/provider';

const log = createModuleLogger(projectLogger, 'chomp');

/** keccak256('Transfer(address,address,uint256)') */
const ERC20_TRANSFER_TOPIC =
'0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';

type RpcLog = {
address: string;
topics: string[];
data: string;
transactionHash: Hex;
};

export async function findRecentChompVaultDeposit({
messenger,
moneyAccountAddress,
sourceAmountRaw,
fromBlock,
}: {
messenger: TransactionPayControllerMessenger;
moneyAccountAddress: Hex;
sourceAmountRaw: string;
fromBlock: Hex;
}): Promise<Hex | undefined> {
const fromPadded = padAddress(moneyAccountAddress);

const logs = await rpcRequest<RpcLog[]>({
messenger,
chainId: CHAIN_ID_MONAD,
method: 'eth_getLogs',
params: [
{
address: MUSD_MONAD_ADDRESS,
fromBlock,
toBlock: 'latest',
topics: [ERC20_TRANSFER_TOPIC, fromPadded, null],
},
],
});

log('CHOMP scan: mUSD Transfer logs found', {
count: logs.length,
fromBlock,
moneyAccountAddress,
});

const requiredAmount = BigInt(sourceAmountRaw);

// Examine newest logs first so we return the most recent CHOMP match.
for (const txLog of [...logs].reverse()) {
const transferAmount = BigInt(txLog.data === '0x' ? '0x0' : txLog.data);

if (transferAmount < requiredAmount) {
log('CHOMP scan: skipping log — transfer amount below required', {
requiredAmount: requiredAmount.toString(),
transferAmount: transferAmount.toString(),
txHash: txLog.transactionHash,
});
continue;
}

log('CHOMP scan: match found', {
moneyAccountAddress,
sourceAmountRaw,
transferAmount: transferAmount.toString(),
txHash: txLog.transactionHash,
});

return txLog.transactionHash;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

CHOMP scan matches unrelated transfers

High Severity

CHOMP idempotency treats any recent mUSD Transfer from the Money Account with amount at least the settled raw total as success. That can match unrelated outbound sends or another deposit’s vault tx, so the direct vault batch is skipped while this order’s ramp credit may stay unvaulted.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit f307c21. Configure here.

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.

It should be ultra edge case, nobody will withdraw larger amount while being in deposit intent or deposit larger mUSD from another source I believe.

}

log('CHOMP scan: no match found', { fromBlock, moneyAccountAddress });
return undefined;
}

function padAddress(address: Hex): string {
return `0x${address.replace(/^0x/u, '').toLowerCase().padStart(64, '0')}`;
}
Loading
Loading