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
173 changes: 155 additions & 18 deletions modules/abstract-eth/src/abstractEthLikeNewCoins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ import { EthLikeToken } from './ethLikeToken';
import {
calculateForwarderV1Address,
coinFamiliesWithL1Fees,
confidentialTransferWithProofMethodId,
confidentialTransferWithProofTypes,
approveMethodId,
decodeApproveCalldata,
decodeFinalizeUnwrapCalldata,
Expand All @@ -94,6 +96,7 @@ import {
decodeUnwrapCalldata,
decodeWrapCalldata,
ERC1155TransferBuilder,
EthTransactionData,
ERC721TransferBuilder,
getBufferedByteCode,
getCommon,
Expand Down Expand Up @@ -590,11 +593,18 @@ export const optionalDeps = {
};

/** Intent types other than payments that verifyTssTransaction already verifies. */
const TSS_DEDICATED_INTENT_TYPES = new Set(['defiApprove', 'defiDeposit', 'defiWithdraw', 'wrapApprove']);
const TSS_DEDICATED_INTENT_TYPES = new Set([
'defiApprove',
'defiDeposit',
'defiWithdraw',
'wrapApprove',
'tokenApproval',
]);

type TssDecodedArg = ReturnType<typeof getRawDecoded>[number];

const TSS_ERC20_TRANSFER_TYPES = ['address', 'uint256'];
const TSS_ERC20_APPROVE_TYPES = ['address', 'uint256'];
const TSS_NATIVE_BATCH_TYPES = ['address[]', 'uint256[]'];
const TSS_TOKEN_BATCH_TYPES = ['address', 'address[]', 'uint256[]'];

Expand Down Expand Up @@ -3636,11 +3646,37 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem
return { isToken: true, reason: `token '${declared}' cannot be resolved to a contract on this network` };
}
if (token instanceof Erc7984Coin) {
return { isToken: true, confidential: true, reason: `token '${declared}' is an ERC-7984 token` };
return {
isToken: true,
contract: contract.toLowerCase(),
confidential: true,
reason: `token '${declared}' is an ERC-7984 token`,
};
}
return { isToken: true, contract: contract.toLowerCase() };
}

/**
* Decode raw serialized EVM transaction bytes directly via `EthTransactionData.fromSerialized`,
* bypassing `TransactionBuilder.from()` / `.build()` reserialization so calldata bytes cannot be
* altered or normalized before verification.
*/
protected decodeRawTssTxFields(txHex: string | undefined): { to: string; value: string; data: string } {
if (!txHex) {
throw new Error('missing txHex in txPrebuild');
}
const common = AbstractEthLikeNewCoins.getCustomChainCommon(this.getChainId());
if (!this.staticsCoin?.features.includes(CoinFeature.EIP1559)) {
common.setHardfork(optionalDeps.EthCommon.Hardfork.Petersburg);
}
const txJson = EthTransactionData.fromSerialized(txHex, common).toJson();
return {
to: (txJson.to ?? '').toLowerCase(),
value: txJson.value ?? '0',
data: (txJson.data || '0x').toLowerCase(),
};
}

/**
* Verify a single-recipient payment: explicit calldata must match exactly; otherwise the bytes
* must be a plain native send or a canonical ERC-20 transfer of the declared token.
Expand All @@ -3651,12 +3687,7 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem
txHex: string | undefined,
throwRecipientMismatch: (message: string, mismatchedRecipients: Recipient[]) => Promise<never>
): Promise<void> {
const txBuilder = this.getTransactionBuilder();
txBuilder.from(txHex);
const txJson = (await txBuilder.build()).toJson();
const to = (txJson.to ?? '').toLowerCase();
const value = txJson.value ?? '0';
const data = (txJson.data || '0x').toLowerCase();
const { to, value, data } = this.decodeRawTssTxFields(txHex);
const mismatch = (message: string, address = to, amount = value): Promise<never> =>
throwRecipientMismatch(message, [{ address, amount }]);

Expand All @@ -3677,6 +3708,46 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem

const token = this.resolveTssToken(recipient.tokenName ?? txParams.tokenName);

if (token.confidential) {
// ERC-7984 confidential token payment: MUST call confidentialTransfer(address,bytes32,bytes)
// on the declared token contract with zero native value and matching recipient.
// Encrypted amount (handle + inputProof) cannot be decrypted client-side and stays a warning.
const expectedSelector = confidentialTransferWithProofMethodId.toLowerCase();
if (!data.startsWith(expectedSelector)) {
await mismatch('ERC-7984 payment calldata must use confidentialTransfer(address,bytes32,bytes)');
}
if (!isCanonicalTssCalldata(data, confidentialTransferWithProofTypes)) {
await mismatch('ERC-7984 confidentialTransfer calldata is not canonical');
}
const [innerRecipient, encryptedHandle, inputProof] = decodeTssCalldataArgs(
data,
confidentialTransferWithProofTypes
);
const decodedRecipient = addHexPrefix(innerRecipient as string).toLowerCase();
if (!recipient.address || decodedRecipient !== recipient.address.toLowerCase()) {
await mismatch('destination address does not match with the recipient address', decodedRecipient, value);
}
if (!tssValuesEqual(value, '0')) {
await mismatch('ERC-7984 confidential transfer must not carry native value');
}
if (!token.contract || to !== token.contract) {
await mismatch('transaction is not sent to the declared token contract');
}
const handleBuf = encryptedHandle as Buffer;
const proofBuf = inputProof as Buffer;
if (!handleBuf || handleBuf.length !== 32 || handleBuf.every((b) => b === 0)) {
await mismatch('ERC-7984 confidentialTransfer encryptedHandle is missing or empty');
}
if (!proofBuf || proofBuf.length === 0) {
await mismatch('ERC-7984 confidentialTransfer inputProof is missing or empty');
}
this.warnTssVerificationIncomplete(
'transfer',
`${token.reason}: encrypted amount cannot be verified against declared plaintext amount`
);
return;
}

if (isEmptyTssCalldata(data)) {
if (token.isToken) {
await mismatch('token payment carries no ERC-20 transfer calldata');
Expand All @@ -3692,10 +3763,6 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem

const transferMethodId = tssMethodId('transfer', TSS_ERC20_TRANSFER_TYPES);
if (!data.startsWith(transferMethodId)) {
if (token.confidential) {
this.warnTssVerificationIncomplete('transfer', `${token.reason}: the payment calldata was not verified`);
return;
}
await mismatch('payment calldata is not a native send or an ERC-20 transfer(address,uint256)');
}
if (!isCanonicalTssCalldata(data, TSS_ERC20_TRANSFER_TYPES)) {
Expand Down Expand Up @@ -3741,12 +3808,7 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem
txHex: string | undefined,
throwRecipientMismatch: (message: string, mismatchedRecipients: Recipient[]) => Promise<never>
): Promise<void> {
const txBuilder = this.getTransactionBuilder();
txBuilder.from(txHex);
const txJson = (await txBuilder.build()).toJson();
const to = (txJson.to ?? '').toLowerCase();
const value = txJson.value ?? '0';
const data = (txJson.data || '0x').toLowerCase();
const { to, value, data } = this.decodeRawTssTxFields(txHex);
const mismatch = (message: string, address = to, amount = value): Promise<never> =>
throwRecipientMismatch(message, [{ address, amount }]);

Expand Down Expand Up @@ -3804,6 +3866,10 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem
}
const tokenContract = addHexPrefix(decoded[0] as string).toLowerCase();
for (const token of tokens) {
if (token.confidential) {
// ERC-7984 confidential tokens have no batchTransferFrom surface; a batch intent naming one is a mismatch.
await mismatch('ERC-7984 confidential tokens cannot be paid through a batch', tokenContract);
}
if (!token.contract) {
this.warnTssVerificationIncomplete(
'transfer',
Expand All @@ -3815,6 +3881,72 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem
}
}

/**
* Verify a `tokenApproval` TSS intent against raw transaction bytes (CECHO-2689).
*
* Expected shape (fail closed on any deviation):
* - `to` = contract address of the declared token on this network
* - `value` = 0
* - `data` = canonical `approve(address,uint256)` (`0x095ea7b3`)
* - `spender` = this network's configured `batcherContractAddress`
* - `amount` = `MAX_UINT256` (`2^256 - 1`)
*/
private async verifyTssTokenApproval(
txParams: EthTransactionParams,
txHex: string | undefined,
throwRecipientMismatch: (message: string, mismatchedRecipients: Recipient[]) => Promise<never>
): Promise<void> {
const { to, value, data } = this.decodeRawTssTxFields(txHex);
const mismatch = (message: string, address = to, amount = value): Promise<never> =>
throwRecipientMismatch(message, [{ address, amount }]);

const token = this.resolveTssToken(txParams.tokenName);
if (!token.isToken || !token.contract) {
await mismatch(
token.reason
? `tokenApproval: ${token.reason}`
: 'tokenApproval transaction requires a declared tokenName resolvable to a contract on this network'
);
}

const configuredBatcher = this.getNetwork()?.batcherContractAddress;
if (!configuredBatcher) {
await mismatch('tokenApproval: no batcher contract is configured for this network');
}
// Unreachable when the mismatch above threw; an empty string can never equal a decoded address.
const batcherSpender = configuredBatcher ?? '';

if (to !== token.contract) {
await mismatch('tokenApproval transaction is not sent to the declared token contract');
}
if (!tssValuesEqual(value, '0')) {
await mismatch('tokenApproval transaction must not carry native value');
}

const expectedSelector = approveMethodId.toLowerCase();
if (!data.startsWith(expectedSelector)) {
await mismatch('tokenApproval transaction must use ERC-20 approve(address,uint256) calldata');
}
if (!isCanonicalTssCalldata(data, TSS_ERC20_APPROVE_TYPES)) {
await mismatch('tokenApproval approve calldata is not canonical');
}

const [rawSpender, rawAmount] = decodeTssCalldataArgs(data, TSS_ERC20_APPROVE_TYPES);
const decodedSpender = addHexPrefix(rawSpender as string).toLowerCase();
const decodedAmount = (rawAmount as BN).toString(10);

if (decodedSpender !== batcherSpender.toLowerCase()) {
await mismatch(
'tokenApproval transaction spender does not match the network batcher contract',
decodedSpender,
decodedAmount
);
}
if (!tssValuesEqual(decodedAmount, MAX_UINT256.toString())) {
await mismatch('tokenApproval transaction amount must be MAX_UINT256', decodedSpender, decodedAmount);
}
}

/**
* @param {VerifyEthTransactionOptions} params
* @param {TransactionParams} params.txParams - params object passed to send
Expand Down Expand Up @@ -3971,9 +4103,14 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem
} else {
// Declared as anything else: only an approve of a registered wrapper is rejected (see the method doc);
// for every other tx this returns without parsing or after one best-effort parse.
// Runs BEFORE tokenApproval so a relabeled approve(wrapper, ...) fails with the wrapper-approve error.
await this.assertWrapperApproveIsDeclared(params, throwRecipientMismatch);
}

if (txParams.type === 'tokenApproval') {
await this.verifyTssTokenApproval(txParams, txPrebuild.txHex, throwRecipientMismatch);
}

// Verify consolidation transactions send to base address
if (params.verification?.consolidationToBaseAddress) {
const coinSpecific = wallet.coinSpecific();
Expand Down
60 changes: 55 additions & 5 deletions modules/sdk-coin-eth/src/erc7984Token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ import {
decodeFlushERC7984ForwarderTokenCalldata,
decodeSendMultiSigFlushERC7984Data,
sendMultisigMethodId,
sendMultiSigTypes,
confidentialTransferWithProofMethodId,
confidentialTransferWithProofTypes,
getRawDecoded,
buildConfidentialTransferByHandleCalldata,
optionalDeps,
RecoverOptions,
Expand Down Expand Up @@ -65,6 +68,24 @@ import { TransactionBuilder } from './lib';
const STRICT_CONSOLIDATION_MAX_DERIVATION_INDEX = 10000;
const STRICT_CONSOLIDATION_FORWARDER_VERSIONS = [1, 2, 4, 5] as const;

/**
* True when the calldata body after the 4-byte selector is exactly the canonical ABI encoding of
* `types`: no trailing bytes, no dirty address padding, no non-standard dynamic offsets.
*
* Mirrors the check the chain-level TSS payment verifier applies, so the token-coin path
* (`Erc7984Token`) enforces the same calldata shape as the base coin.
*/
function isCanonicalErc7984Calldata(data: string, types: string[]): boolean {
try {
const args = data.slice(10).toLowerCase();
const decoded = getRawDecoded(types, Buffer.from(args, 'hex'));
const encodable = decoded.map((value) => (typeof value === 'string' ? addHexPrefix(value) : value));
return optionalDeps.ethAbi.rawEncode(types, encodable).toString('hex') === args;
} catch {
return false;
}
}

export { Erc7984TokenConfig };

export class Erc7984Token extends Eth {
Expand Down Expand Up @@ -882,6 +903,12 @@ export class Erc7984Token extends Eth {
* 2. Decoded recipient matches txParams.recipients[0].address or buildParams.recipients[0].address.
* 3. encryptedHandle and inputProof are structurally present (non-empty).
* 4. txParams.recipients[0].amount is a positive integer and matches buildParams when both present.
* 5. The transaction carries zero native value and the calldata is canonical for its shape.
*
* Verification limit (CECHO-2689): the transferred amount is encrypted (`euint64` ciphertext plus
* an input proof), so the plaintext `recipients[0].amount` cannot be compared against it. The
* selector, token contract, recipient, native value and calldata shape are all enforced; the
* encrypted amount is verified only structurally (non-empty 32-byte handle, non-empty proof).
*
* Without txHex (first-signer / pre-signing path):
* 1. Requires exactly one recipient in txParams.
Expand Down Expand Up @@ -933,11 +960,9 @@ export class Erc7984Token extends Eth {
return true;
}

// Parse and decode the raw transaction
const txBuilder = this.getTransactionBuilder();
txBuilder.from(txPrebuild.txHex);
const tx = await txBuilder.build();
const txJson = tx.toJson();
// Decode the original signed bytes. A TransactionBuilder round trip reserializes from the fields it
// models, so the checks below would inspect a rebuilt copy instead of what is signed.
const txJson = this.decodeRawTssTxFields(txPrebuild.txHex);

let toAddress: string;
let tokenContractAddress: string;
Expand Down Expand Up @@ -973,6 +998,31 @@ export class Erc7984Token extends Eth {
);
}

// 0. Native value must be zero. A confidentialTransfer moves an encrypted token amount; any
// nonzero `value` would additionally send the chain's native coin to the token contract.
if (txJson.value !== undefined && String(txJson.value) !== '0') {
throw new Error(
`verifyConfidentialTransfer: confidential transfer must not carry native value (got ${txJson.value})`
);
}

// 0b. Calldata must be the canonical ABI encoding for its shape. The EVM ignores trailing
// bytes; accepting them would sign more than the decoded intent describes.
const calldataTypes = txJson.data.startsWith(sendMultisigMethodId)
? sendMultiSigTypes
: confidentialTransferWithProofTypes;
if (!isCanonicalErc7984Calldata(txJson.data, calldataTypes)) {
throw new Error('verifyConfidentialTransfer: confidential transfer calldata is not canonical');
}

// 0c. A confidential transfer carries exactly one recipient. A multi-recipient intent would
// silently ignore every entry after the first.
if (txParams?.recipients && txParams.recipients.length > 1) {
throw new Error(
`verifyConfidentialTransfer: confidential transfers support exactly 1 recipient, got ${txParams.recipients.length}`
);
}

// 1. Token contract address must match this coin
if (tokenContractAddress.toLowerCase() !== this.tokenContractAddress.toLowerCase()) {
throw new Error(
Expand Down
Loading
Loading