From c33fcb2e1f0ac187b7c81b3635105910fe9b3214 Mon Sep 17 00:00:00 2001 From: Deepak Jangid Date: Wed, 25 Nov 2026 18:02:06 +0530 Subject: [PATCH] fix(abstract-eth): verify fillNonce, transferToken, bridgeFunds, DeFi Add fail-closed EVM TSS transaction verification for fillNonce, transferToken, HyperEVM bridgeFunds, and DeFi native value, plus surgical sdk-core propagation for stored bridgeFunds intent.amount, transferToken tokenData, and numeric fillNonce nonce. Ticket: CECHO-2690 --- .../src/abstractEthLikeNewCoins.ts | 728 +++++++++- .../abstract-eth/test/unit/tssVerification.ts | 1226 +++++++++++++++++ modules/sdk-coin-eth/test/unit/eth.ts | 29 +- .../test/unit/tssPaymentVerification.ts | 673 +++++++++ modules/sdk-coin-flr/test/unit/flr.ts | 9 +- modules/sdk-coin-tempo/src/tempo.ts | 6 + modules/sdk-coin-tempo/test/unit/tempo.ts | 10 + .../sdk-core/src/bitgo/baseCoin/iBaseCoin.ts | 6 + .../sdk-core/src/bitgo/utils/tss/baseTypes.ts | 2 +- .../src/bitgo/utils/tss/recipientUtils.ts | 35 + .../sdk-core/src/bitgo/wallet/BuildParams.ts | 3 + .../unit/bitgo/utils/tss/recipientUtils.ts | 122 ++ 12 files changed, 2793 insertions(+), 56 deletions(-) create mode 100644 modules/abstract-eth/test/unit/tssVerification.ts diff --git a/modules/abstract-eth/src/abstractEthLikeNewCoins.ts b/modules/abstract-eth/src/abstractEthLikeNewCoins.ts index bccbb5b5dcc..8636979acf7 100644 --- a/modules/abstract-eth/src/abstractEthLikeNewCoins.ts +++ b/modules/abstract-eth/src/abstractEthLikeNewCoins.ts @@ -63,9 +63,12 @@ import { ChainIdNotFoundError, CoinFeature, coins, + ContractAddressDefinedToken, Erc7984Coin, + EthLikeERC721Token, EthereumNetwork as EthLikeNetwork, ethGasConfigs, + UnderlyingAsset, } from '@bitgo/statics'; import type * as EthLikeCommon from '@ethereumjs/common'; import type * as EthLikeTxLib from '@ethereumjs/tx'; @@ -98,7 +101,6 @@ import { ERC1155TransferBuilder, EthTransactionData, ERC721TransferBuilder, - getBufferedByteCode, getCommon, getCreateForwarderParamsAndTypes, getProxyInitcode, @@ -398,7 +400,6 @@ interface FeeEstimate { feeEstimate: number; } -// TODO: This interface will need to be updated for the new fee model introduced in the London Hard Fork interface EthTransactionParams extends TransactionParams { gasPrice?: number; gasLimit?: number; @@ -407,6 +408,8 @@ interface EthTransactionParams extends TransactionParams { prebuildTx?: PrebuildTransactionResult; tokenName?: string; feeToken?: string; + /** Stored-intent top-level amount shape for `bridgeFunds` intents. */ + amount?: { value: string; symbol: string } | string; defiParams?: DefiIntentParams; /** ERC-7984 shield intent (`type: 'wrapApprove' | 'wrap'`): wrapper coin name and exact amount. */ wrapParams?: { tokenName: string; amount: string }; @@ -417,6 +420,9 @@ interface EthTransactionParams extends TransactionParams { } const MAX_UINT256 = 2n ** 256n - 1n; +const HYPEEVM_CORE_WRITER_CONTRACT = '0x3333333333333333333333333333333333333333'; +const HYPEEVM_BRIDGE_ACTION_HEADER = Buffer.from([0x01, 0x00, 0x00, 0x06]); +const HYPEEVM_BRIDGE_DECIMAL_DIVISOR = 10n ** 10n; export interface VerifyEthTransactionOptions extends VerifyTransactionOptions { txPrebuild: TransactionPrebuild; @@ -606,6 +612,10 @@ const TSS_DEDICATED_INTENT_TYPES = new Set([ 'consolidate', 'consolidateToken', 'tokenApproval', + 'fillNonce', + 'transferToken', + 'transfertoken', + 'bridgeFunds', ]); /** @@ -622,13 +632,44 @@ type TssDecodedArg = ReturnType[number]; const TSS_ERC20_TRANSFER_TYPES = ['address', 'uint256']; const TSS_ERC20_APPROVE_TYPES = ['address', 'uint256']; +const TSS_DEFI_DEPOSIT_TYPES = ['uint256', 'address']; +const TSS_DEFI_REDEEM_TYPES = ['uint256', 'address', 'address']; const TSS_NATIVE_BATCH_TYPES = ['address[]', 'uint256[]']; const TSS_TOKEN_BATCH_TYPES = ['address', 'address[]', 'uint256[]']; +const TSS_BRIDGE_SEND_RAW_ACTION_TYPES = ['bytes']; +const TSS_HYPEEVM_BRIDGE_ARGS_TYPES = ['address', 'uint64', 'uint64']; +const TSS_ERC721_SAFE_TRANSFER_3_TYPES = ['address', 'address', 'uint256']; +const TSS_ERC721_SAFE_TRANSFER_4_TYPES = ['address', 'address', 'uint256', 'bytes']; +const TSS_ERC1155_SAFE_TRANSFER_TYPES = ['address', 'address', 'uint256', 'uint256', 'bytes']; +const TSS_NON_NEGATIVE_INT_RE = /^(0|[1-9][0-9]*)$/; function tssMethodId(name: string, types: string[]): string { return addHexPrefix(optionalDeps.ethAbi.methodID(name, types).toString('hex')).toLowerCase(); } +function isRegisteredFungibleEvmToken(coin: Readonly | undefined): boolean { + return ( + coin instanceof ContractAddressDefinedToken && + !(coin instanceof EthLikeERC721Token) && + !(coin instanceof Erc7984Coin) && + coin.asset !== UnderlyingAsset.ERC721 && + coin.asset !== UnderlyingAsset.ERC1155 + ); +} + +/** + * True only for a *positively* classified NFT coin (ERC-721 / ERC-1155). An unregistered contract, or + * one that merely is not a registered ERC-20, must never inherit the NFT warn-only path. + */ +function isRegisteredNftEvmToken(coin: Readonly | undefined): boolean { + return ( + !!coin && + (coin instanceof EthLikeERC721Token || + coin.asset === UnderlyingAsset.ERC721 || + coin.asset === UnderlyingAsset.ERC1155) + ); +} + function isEmptyTssCalldata(data?: string): boolean { return !data || data === '0x'; } @@ -3674,39 +3715,154 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem } /** - * Resolve a declared token to its contract from local statics. With no token name, a token coin - * declares itself and a base coin declares no asset (`isToken: false`). + * Extract the bare token symbol after the optional `chain:` prefix (lowercased). + */ + private static bareTokenSymbol(name: string): string { + const idx = name.indexOf(':'); + return (idx >= 0 ? name.slice(idx + 1) : name).toLowerCase(); + } + + /** + * Extract a valid 20-byte hex EVM contract address from a statics coin, if present. + */ + private static getHexContractAddress(coin: Readonly | undefined): string | undefined { + if (!coin || !('contractAddress' in coin) || typeof coin.contractAddress !== 'string') { + return undefined; + } + return /^0x[0-9a-fA-F]{40}$/.test(coin.contractAddress) ? coin.contractAddress.toLowerCase() : undefined; + } + + /** + * Look up a declared token or coin name strictly on the signing coin's network. + * + * Never returns a coin from a different network (e.g. Ethereum's bare `usdt` when signing on + * Arbitrum). When a bare symbol is supplied on a chain whose tokens are prefixed (`arbeth:usdt`), + * resolves `${networkPrefix}:${name}` on the signing network first so cross-network bare names + * cannot shadow same-network tokens. + */ + private resolveSameNetworkStaticsCoin(name: string): Readonly | undefined { + const self = coins.getOrUndefined(this.getChain()); + const network = self?.network ?? this.staticsCoin?.network; + if (!network) { + return undefined; + } + + const direct = coins.getOrUndefined(name); + if (direct && direct.network === network) { + return direct; + } + + // Bare symbol (no `chain:` prefix): try qualifying with the signing coin's chain prefix on + // the same network (e.g. bare `usdt` -> `arbeth:usdt` on Arbitrum, or `hteth:stgusd1` on Hoodi). + if (!name.includes(':')) { + const basePrefix = this.getBaseChain().split(':')[0]; + const candidates = new Set(); + if (basePrefix) { + candidates.add(`${basePrefix}:${name}`); + candidates.add(`${basePrefix}:${name.toLowerCase()}`); + } + const selfChainPrefix = this.getChain().includes(':') ? this.getChain().split(':')[0] : undefined; + if (selfChainPrefix) { + candidates.add(`${selfChainPrefix}:${name}`); + candidates.add(`${selfChainPrefix}:${name.toLowerCase()}`); + } + const chainId = 'chainId' in network && typeof network.chainId === 'number' ? network.chainId : undefined; + const chainIdPrefix = chainId !== undefined ? coins.coinNameFromChainId(chainId) : undefined; + if (chainIdPrefix) { + candidates.add(`${chainIdPrefix}:${name}`); + candidates.add(`${chainIdPrefix}:${name.toLowerCase()}`); + } + for (const candidate of candidates) { + const prefixed = coins.getOrUndefined(candidate); + if (prefixed && prefixed.network === network) { + return prefixed; + } + } + } + + return undefined; + } + + /** + * Resolve a declared token to its contract from local statics on the signing coin's network. + * With no token name, a token coin declares itself and a base coin declares no asset (`isToken: false`). + * When signing on a token coin, a declared token name must agree with the signing token. + * + * `mismatch` marks a *known* conflict (an explicitly empty name, a declaration that names the + * signing chain's native asset, a different signing token, or a token that statics knows on another + * network) as opposed to a token nobody has registered here. Callers must fail closed on + * `mismatch`; only a genuinely unregistered token may still warn and continue. */ private resolveTssToken(tokenName?: string): { isToken: boolean; contract?: string; confidential?: boolean; reason?: string; + mismatch?: boolean; } { - // Token coins (e.g. `txdc:usdc`) resolve through their own chain name. + // An explicitly empty (or whitespace-only) name is a declaration, never an omission: it must not + // fall back to the signing token. + if (typeof tokenName === 'string' && tokenName.trim() === '') { + return { + isToken: true, + mismatch: true, + reason: 'declared tokenName is empty and cannot be resolved to a contract', + }; + } + // Token coins (e.g. `txdc:usdc`, `arbeth:usdt`) resolve through their own chain name. const self = coins.getOrUndefined(this.getChain()); const network = self?.network ?? this.staticsCoin?.network; - const declared = tokenName ?? (self?.isToken ? self.name : undefined); + const selfIsToken = Boolean(self?.isToken); + const declared = tokenName ?? (selfIsToken ? self!.name : undefined); if (!declared) { return { isToken: false }; } - const token = coins.getOrUndefined(declared); + const token = this.resolveSameNetworkStaticsCoin(declared); if (token && !token.isToken && token.network === network) { + if (selfIsToken) { + return { + isToken: true, + mismatch: true, + reason: `declared token '${declared}' does not match signing token '${self!.name}'`, + }; + } return { isToken: false }; // the chain's own native coin } - const contract = (token as { contractAddress?: string } | undefined)?.contractAddress; - if (!token || token.network !== network || !contract || !/^0x[0-9a-fA-F]{40}$/.test(contract)) { - return { isToken: true, reason: `token '${declared}' cannot be resolved to a contract on this network` }; + const contract = AbstractEthLikeNewCoins.getHexContractAddress(token); + if (!token || token.network !== network || !contract) { + // A name statics knows only on another network is a known cross-network conflict, not an + // unregistered token. Anything absent from statics stays a warning-only unknown. + const offNetwork = token ? undefined : coins.getOrUndefined(declared); + const mismatch = Boolean(offNetwork && offNetwork.network !== network); + return { + isToken: true, + mismatch, + reason: `token '${declared}' cannot be resolved to a contract on this network`, + }; + } + if (selfIsToken && self) { + const selfContract = AbstractEthLikeNewCoins.getHexContractAddress(self); + if ( + !selfContract || + selfContract !== contract || + AbstractEthLikeNewCoins.bareTokenSymbol(token.name) !== AbstractEthLikeNewCoins.bareTokenSymbol(self.name) + ) { + return { + isToken: true, + mismatch: true, + reason: `declared token '${declared}' does not match signing token '${self.name}'`, + }; + } } if (token instanceof Erc7984Coin) { return { isToken: true, - contract: contract.toLowerCase(), + contract, confidential: true, reason: `token '${declared}' is an ERC-7984 token`, }; } - return { isToken: true, contract: contract.toLowerCase() }; + return { isToken: true, contract }; } /** @@ -3714,7 +3870,12 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem * bypassing `TransactionBuilder.from()` / `.build()` reserialization so calldata bytes cannot be * altered or normalized before verification. */ - private decodeRawTssTxFields(txHex: string | undefined): { to: string; value: string; data: string } { + private decodeRawTssTxFields(txHex: string | undefined): { + to: string; + value: string; + data: string; + nonce: number; + } { if (!txHex) { throw new Error('missing txHex in txPrebuild'); } @@ -3727,6 +3888,7 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem to: (txJson.to ?? '').toLowerCase(), value: txJson.value ?? '0', data: (txJson.data || '0x').toLowerCase(), + nonce: txJson.nonce, }; } @@ -3743,6 +3905,13 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem // Resolve the declared asset first: a declared ERC-7984 payment must never bypass the // confidential-transfer checks by supplying caller-authored explicit calldata. const token = this.resolveTssToken(recipient.tokenName ?? txParams.tokenName); + // A known conflict (declared token vs signing token / network, or an explicitly empty name) is a + // mismatch, never a warning: warn-and-continue would verify the wrong contract. + if (token.mismatch) { + await throwRecipientMismatch(`payment token declaration is invalid: ${token.reason}`, [ + { address: recipient.address, amount: String(recipient.amount) }, + ]); + } if (token.confidential) { // ERC-7984 confidential token payment: MUST call confidentialTransfer(address,bytes32,bytes) @@ -3923,6 +4092,13 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem // Each recipient declares its own asset; a batch moves exactly one. const tokens = recipients.map((recipient) => this.resolveTssToken(recipient.tokenName ?? txParams.tokenName)); + for (const token of tokens) { + // A known conflict (declared token vs signing token / network, or an explicitly empty name) is + // a mismatch, never a warning: warn-and-continue would verify the wrong contract. + if (token.mismatch) { + await mismatch(`batch payment token declaration is invalid: ${token.reason}`); + } + } if (isNativeBatch) { if (tokens.some((token) => token.isToken)) { await mismatch('token batch payment must use batchTransferFrom calldata'); @@ -4020,6 +4196,468 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem } } + /** + * Verify a `fillNonce` TSS intent against raw serialized transaction bytes (CECHO-2690). + * + * Expected shape (fail closed on any deviation): + * - `to` = `wallet.coinSpecific().baseAddress` (every production fillNonce row is a self-send to + * the wallet's own address; `verifyTransaction` does not receive verifiable wallet keychain / + * derivation metadata for arbitrary non-base receive addresses, so an unverified caller-supplied + * `receiveAddress` is rejected rather than trusted to redirect the filler) + * - `data` = empty (`0x`) + * - `value` = `0` or `1` wei (production EVM TSS self-sends use `1` wei) + * - `nonce`, when declared by the caller or the stored intent, equals the signed transaction nonce + */ + private async verifyTssFillNonce( + txParams: EthTransactionParams, + wallet: IWallet, + txHex: string | undefined, + throwRecipientMismatch: (message: string, mismatchedRecipients: Recipient[]) => Promise + ): Promise { + const { to, value, data, nonce } = this.decodeRawTssTxFields(txHex); + const mismatch = (message: string, address = to, amount = value): Promise => + throwRecipientMismatch(message, [{ address, amount }]); + + const baseAddress = wallet.coinSpecific()?.baseAddress; + if (!baseAddress) { + await mismatch('fillNonce transaction requires a wallet base address to verify against'); + return; + } + if (!to || to !== baseAddress.toLowerCase()) { + await mismatch('fillNonce transaction destination does not match wallet base address'); + } + if (!isEmptyTssCalldata(data)) { + await mismatch('fillNonce transaction must not carry calldata'); + } + if (!tssValuesEqual(value, '0') && !tssValuesEqual(value, '1')) { + await mismatch('fillNonce transaction value must be 0 or 1 wei'); + } + if (txParams.nonce !== undefined && txParams.nonce !== null) { + const declaredNonce = String(txParams.nonce).trim(); + if (!TSS_NON_NEGATIVE_INT_RE.test(declaredNonce)) { + await mismatch(`fillNonce declared nonce must be a non-negative integer, got '${txParams.nonce}'`); + } + if (!tssValuesEqual(declaredNonce, nonce)) { + await mismatch(`fillNonce transaction nonce ${nonce} does not match the declared nonce ${declaredNonce}`); + } + } + } + + /** + * Verify a `transferToken` / `transfertoken` TSS intent against raw serialized transaction bytes (CECHO-2690). + * + * - ERC-721 / ERC-1155 NFT transfers stay warning-only for tokenId/quantity semantics, but only for + * a positively classified NFT (declared `tokenType` or a statics NFT coin): canonical NFT calldata + * for the declared standard, the declared contract, zero native value, and the decoded recipient + * are all enforced before the warning is emitted. + * - ERC-20 transfers fail closed on recipient, amount, declared token contract (from `@bitgo/statics`), + * canonical `transfer(address,uint256)` calldata, and `value == 0`. + * - Coordinates amount semantics with COINS-2263 (`BitGo/bitgo-microservices#64621`): + * when `tokenData.tokenQuantity` is present, it is the authoritative ERC-20 quantity, and + * `recipient.amount` must be either the canonical `'0'` placeholder or equal to `tokenQuantity`. + */ + private async verifyTssTransferToken( + txParams: EthTransactionParams, + txHex: string | undefined, + throwRecipientMismatch: (message: string, mismatchedRecipients: Recipient[]) => Promise + ): Promise { + const recipients = txParams.recipients ?? []; + if (recipients.length !== 1) { + await throwRecipientMismatch( + `transferToken transaction must declare a single recipient, got ${recipients.length}`, + [] + ); + } + + const recipient = recipients[0]; + const { to, value, data } = this.decodeRawTssTxFields(txHex); + const mismatch = (message: string, address = to, amount = value): Promise => + throwRecipientMismatch(message, [{ address, amount }]); + + const tokenData = recipient.tokenData; + const tokenType = tokenData?.tokenType ? String(tokenData.tokenType).toUpperCase() : undefined; + const selfCoin = coins.getOrUndefined(this.getChain()); + const network = selfCoin?.network ?? this.getNetwork(); + const declaredContract = tokenData?.tokenContractAddress ?? recipient.tokenAddress; + const declaredTokenName = tokenData?.tokenName ?? recipient.tokenName ?? txParams.tokenName; + // An explicitly empty (or whitespace-only) tokenName is a declaration, never an omission: it must + // not fall back to the signing token or a contract-derived token. + if (typeof declaredTokenName === 'string' && declaredTokenName.trim() === '') { + await mismatch('transferToken declared tokenName is empty'); + } + // Resolve declared token identities strictly on the signing coin's network so a bare symbol + // (e.g. 'usdt' on Arbitrum) resolves to the same-network token ('arbeth:usdt'), never to a + // token on another chain (e.g. Ethereum 'usdt'). + // `getToken` matches only the network *type* and coin family, so a contract registered on a + // different network of the same type (e.g. Hoodi's `terc721:bitgoerc721` while signing on + // another testnet) would come back as a foreign statics entry: require exact network identity. + const declaredNameCoin = declaredTokenName ? this.resolveSameNetworkStaticsCoin(declaredTokenName) : undefined; + const declaredContractCandidate = + declaredContract && network ? getToken(declaredContract, network, this.getFamily()) : undefined; + const declaredContractCoin = + declaredContractCandidate && declaredContractCandidate.network === network + ? declaredContractCandidate + : undefined; + // Positive NFT classification only: the declared tokenType, or a declared token name / contract + // that resolves on this network in @bitgo/statics to a registered ERC-721 / ERC-1155 coin. + // "Not a registered ERC-20" is NOT classification — otherwise any unregistered contract would + // skip verification. + let declaredNftStandard: 'ERC721' | 'ERC1155' | undefined; + const selfIsNft = isRegisteredNftEvmToken(selfCoin); + const declaredNftCoin = [ + declaredNameCoin, + declaredContractCoin, + !declaredTokenName && selfIsNft ? selfCoin : undefined, + ].find(isRegisteredNftEvmToken); + if (tokenType === 'ERC721' || tokenType === 'ERC1155') { + declaredNftStandard = tokenType; + } else if (declaredNftCoin) { + declaredNftStandard = declaredNftCoin.asset === UnderlyingAsset.ERC1155 ? 'ERC1155' : 'ERC721'; + } + const erc721Safe3Selector = tssMethodId('safeTransferFrom', TSS_ERC721_SAFE_TRANSFER_3_TYPES); + const erc721Safe4Selector = tssMethodId('safeTransferFrom', TSS_ERC721_SAFE_TRANSFER_4_TYPES); + const erc1155SafeSelector = tssMethodId('safeTransferFrom', TSS_ERC1155_SAFE_TRANSFER_TYPES); + const erc721TransferFromSelector = tssMethodId('transferFrom', TSS_ERC721_SAFE_TRANSFER_3_TYPES); + const isHederaEvm = this.getFamily() === 'hbarevm'; + const targetCoin = to && network ? getToken(to, network, this.getFamily()) : undefined; + const targetIsRegisteredErc20 = + !!targetCoin && targetCoin.network === network && isRegisteredFungibleEvmToken(targetCoin); + + // Canonical NFT transfer calldata for the declared standard, or `undefined` when the calldata is + // not an NFT transfer of that standard. ERC-20 transferFrom(address,address,uint256) shares the + // 3-argument selector, so it is only admitted on Hedera EVM (HTS NFTs), never against a + // registered ERC-20 contract and never for a declared ERC-1155. + const nftCalldataTypesFor = (standard: 'ERC721' | 'ERC1155'): string[] | undefined => { + if (standard === 'ERC1155') { + return data.startsWith(erc1155SafeSelector) && isCanonicalTssCalldata(data, TSS_ERC1155_SAFE_TRANSFER_TYPES) + ? TSS_ERC1155_SAFE_TRANSFER_TYPES + : undefined; + } + if (data.startsWith(erc721Safe3Selector) && isCanonicalTssCalldata(data, TSS_ERC721_SAFE_TRANSFER_3_TYPES)) { + return TSS_ERC721_SAFE_TRANSFER_3_TYPES; + } + if (data.startsWith(erc721Safe4Selector) && isCanonicalTssCalldata(data, TSS_ERC721_SAFE_TRANSFER_4_TYPES)) { + return TSS_ERC721_SAFE_TRANSFER_4_TYPES; + } + if ( + isHederaEvm && + !targetIsRegisteredErc20 && + data.startsWith(erc721TransferFromSelector) && + isCanonicalTssCalldata(data, TSS_ERC721_SAFE_TRANSFER_3_TYPES) + ) { + return TSS_ERC721_SAFE_TRANSFER_3_TYPES; + } + return undefined; + }; + + // NFT transferToken (ERC-721 / ERC-1155): the tokenId/quantity semantics stay warning-only until + // a dedicated NFT verifier lands, but nothing else is relaxed. Canonical NFT calldata, the + // declared contract, zero native value, and the decoded recipient are all enforced so a + // compromised server cannot smuggle an ERC-20 transfer/approve, native value, or a different + // destination under an NFT label. + if (declaredNftStandard) { + const nftCalldataTypes = nftCalldataTypesFor(declaredNftStandard); + if (!nftCalldataTypes) { + return await mismatch('NFT transferToken calldata must be a canonical NFT safeTransferFrom call'); + } + // Require a concrete, same-network 20-byte contract address (either declared on the intent or + // from a same-network statics NFT coin) and bind `to` to it before emitting a warn-only pass. + // Generic placeholder NFT entries (e.g. `0xerc721:token`) have non-hex contracts and do not + // satisfy this requirement on their own. + const resolvedStaticsNftContract = AbstractEthLikeNewCoins.getHexContractAddress(declaredNftCoin); + const normalizedDeclaredContract = + declaredContract && /^0x[0-9a-fA-F]{40}$/.test(declaredContract) ? declaredContract.toLowerCase() : undefined; + if (declaredContract && !normalizedDeclaredContract) { + await mismatch('NFT transferToken declared contract address is invalid'); + } + // If the intent declared a tokenName that resolves on a DIFFERENT network in statics (e.g. + // `erc721:witch` on Ethereum while signing on Hoodi), fail closed even if a contract was also + // supplied, so cross-network NFT names are never accepted. + const globalNamedCoin = declaredTokenName ? coins.getOrUndefined(declaredTokenName) : undefined; + if (declaredTokenName && globalNamedCoin && globalNamedCoin.network !== network && !declaredNameCoin) { + await mismatch(`NFT transferToken declared token '${declaredTokenName}' does not belong to this network`); + } + if (declaredTokenName && !declaredNameCoin && !normalizedDeclaredContract) { + await mismatch( + `NFT transferToken declared token '${declaredTokenName}' cannot be resolved to a contract on this network` + ); + } + if ( + normalizedDeclaredContract && + resolvedStaticsNftContract && + normalizedDeclaredContract !== resolvedStaticsNftContract + ) { + await mismatch('NFT transferToken declared tokenContractAddress does not match the registered NFT contract'); + } + const expectedNftContract = normalizedDeclaredContract ?? resolvedStaticsNftContract; + if (!expectedNftContract) { + return await mismatch('NFT transferToken requires a declared or registered same-network contract address'); + } + if (to !== expectedNftContract) { + await mismatch('NFT transferToken transaction is not sent to the declared contract'); + } + if (!tssValuesEqual(value, '0')) { + await mismatch('NFT transferToken transaction must not carry native value'); + } + const [, decodedNftRecipient] = decodeTssCalldataArgs(data, nftCalldataTypes); + const decodedNftTo = addHexPrefix(decodedNftRecipient as string).toLowerCase(); + if (!recipient.address || decodedNftTo !== recipient.address.toLowerCase()) { + await mismatch('NFT transferToken destination address does not match the recipient address', decodedNftTo); + } + this.warnTssVerificationIncomplete( + 'transferToken', + `NFT token transfer (${declaredNftStandard}) verification is not implemented: only tokenId/quantity ` + + 'semantics were skipped; calldata shape, contract, recipient, and zero native value were verified' + ); + return; + } + if (tokenType && tokenType !== 'ERC20') { + await mismatch(`transferToken unsupported tokenType '${tokenData?.tokenType}'`); + } + + // Resolve authoritative ERC-20 amount (coordinated with COINS-2263): + // - If tokenData.tokenQuantity is present, it must be a non-negative integer, and + // recipient.amount must be either the canonical '0' placeholder (or empty/undefined) or + // equal to tokenQuantity (prevents amount.value vs tokenQuantity spoofing). + // - Otherwise fall back to recipient.amount (e.g. stored-intent path where resolveEffectiveTxParams + // did not forward tokenData, or direct callers supplying only amount). + let expectedAmount: string; + if (tokenData?.tokenQuantity !== undefined && tokenData?.tokenQuantity !== null) { + const rawQty = String(tokenData.tokenQuantity).trim(); + if (!TSS_NON_NEGATIVE_INT_RE.test(rawQty)) { + await mismatch(`transferToken tokenQuantity must be a non-negative integer, got '${tokenData.tokenQuantity}'`); + } + const trimmedAmount = + recipient.amount === undefined || recipient.amount === null ? '' : String(recipient.amount).trim(); + if (trimmedAmount !== '') { + if (!TSS_NON_NEGATIVE_INT_RE.test(trimmedAmount)) { + await mismatch(`transferToken amount must be a non-negative integer, got '${recipient.amount}'`); + } + if (!tssValuesEqual(trimmedAmount, '0') && !tssValuesEqual(trimmedAmount, rawQty)) { + await mismatch('transferToken amount does not match tokenData.tokenQuantity'); + } + } + expectedAmount = rawQty; + } else { + const rawAmount = + recipient.amount === undefined || recipient.amount === null ? '' : String(recipient.amount).trim(); + if (!TSS_NON_NEGATIVE_INT_RE.test(rawAmount)) { + await mismatch('transferToken requires a valid non-negative integer amount'); + } + expectedAmount = rawAmount; + } + + // Resolve declared ERC-20 token contract from @bitgo/statics on the signing coin's network + // (fail closed if missing, cross-network, or unresolvable). + // - If a tokenName is declared, it MUST resolve on this network (e.g. `usdt` -> `arbeth:usdt` + // on Arbitrum) and, when signing on a token-scoped wallet, must agree with the signing token. + // Never silently fall back to the signing token when the declared name fails to resolve or + // names a different token/network. + // - If no tokenName is declared, resolve via declaredContractCoin on this network, or fall back + // to the signing token coin itself (when signing on a token wallet). + let tokenLookup: string | undefined; + if (declaredTokenName) { + tokenLookup = declaredTokenName; + } else if (declaredContractCoin) { + tokenLookup = declaredContractCoin.name; + } + const token = this.resolveTssToken(tokenLookup); + if (!token.isToken || !token.contract || token.confidential) { + await mismatch( + token.reason + ? `transferToken: ${token.reason}` + : 'transferToken requires a declared ERC-20 token resolvable to a contract on this network' + ); + return; + } + if (declaredContract && declaredContract.toLowerCase() !== token.contract) { + await mismatch('transferToken declared tokenContractAddress does not match the registered token contract'); + } + if (to !== token.contract) { + await mismatch('transferToken transaction is not sent to the declared token contract'); + } + if (!tssValuesEqual(value, '0')) { + await mismatch('transferToken transaction must not carry native value'); + } + + const transferSelector = tssMethodId('transfer', TSS_ERC20_TRANSFER_TYPES); + if (!data.startsWith(transferSelector)) { + await mismatch('transferToken calldata must use ERC-20 transfer(address,uint256)'); + } + if (!isCanonicalTssCalldata(data, TSS_ERC20_TRANSFER_TYPES)) { + await mismatch('transferToken ERC-20 transfer calldata is not canonical'); + } + + const [rawRecipient, rawAmount] = decodeTssCalldataArgs(data, TSS_ERC20_TRANSFER_TYPES); + const decodedRecipient = addHexPrefix(rawRecipient as string).toLowerCase(); + const decodedAmount = (rawAmount as BN).toString(10); + + if (!recipient.address || decodedRecipient !== recipient.address.toLowerCase()) { + await mismatch( + 'transferToken destination address does not match the recipient address', + decodedRecipient, + decodedAmount + ); + } + if (!tssValuesEqual(decodedAmount, expectedAmount)) { + await mismatch( + 'transferToken amount in txPrebuild does not match the declared token amount', + decodedRecipient, + decodedAmount + ); + } + } + + /** + * Verify a `bridgeFunds` TSS intent against raw serialized transaction bytes (CECHO-2690). + * + * Only HyperEVM (`hypeevm` / `thypeevm`, family `hypeevm`) supports `bridgeFunds` on EVM: + * - `to` = HyperCore CoreWriter precompile (`0x3333...3333`) + * - `value` = `0` + * - `data` = canonical `sendRawAction(bytes)` (`0x17938e13`) where the payload is: + * `0x01` (version 1) || `0x000006` (actionId 6) || canonical ABI `(address, uint64, uint64)` + * - `destination` = coin's `systemAddress` from `@bitgo/statics` + * - `tokenId` = coin's `tokenId` from `@bitgo/statics` (`150` mainnet / `1105` testnet) + * - `amount` = `BigInt(declaredAmount.value) / 10^10` (18-decimal wei truncated to 8-decimal HyperCore units); + * the result must be a positive `uint64`, so zero, sub-unit dust, and overflow are rejected + * - `declaredAmount` comes from `txParams.intentAmount`, or the stored-intent `txParams.amount` + * shape that `resolveEffectiveTxParams` propagates — never from calldata + * + * All other EVM chains reject `bridgeFunds` outright. + */ + private async verifyTssBridgeFunds( + txParams: EthTransactionParams, + txHex: string | undefined, + throwRecipientMismatch: (message: string, mismatchedRecipients: Recipient[]) => Promise + ): Promise { + const { to, value, data } = this.decodeRawTssTxFields(txHex); + const mismatch = (message: string, address = to, amount = value): Promise => + throwRecipientMismatch(message, [{ address, amount }]); + + if (this.getFamily() !== 'hypeevm') { + await mismatch(`bridgeFunds is not supported on EVM coin '${this.getChain()}'`); + } + if (txParams.recipients && txParams.recipients.length > 0) { + await mismatch('bridgeFunds transaction must not declare recipients'); + } + const rawAmount = + txParams.intentAmount ?? + (typeof txParams.amount === 'object' && txParams.amount !== null ? txParams.amount : undefined); + if (!rawAmount || typeof rawAmount.value !== 'string' || typeof rawAmount.symbol !== 'string') { + await mismatch('bridgeFunds transaction requires a declared amount ({ value, symbol }) to verify against'); + return; + } + if (!TSS_NON_NEGATIVE_INT_RE.test(rawAmount.value.trim())) { + await mismatch(`bridgeFunds declared amount must be a non-negative integer, got '${rawAmount.value}'`); + } + if (rawAmount.symbol.toLowerCase() !== this.getChain().toLowerCase()) { + await mismatch(`bridgeFunds declared symbol '${rawAmount.symbol}' does not match chain '${this.getChain()}'`); + } + + const staticCoin: unknown = coins.getOrUndefined(this.getChain()) ?? this.staticsCoin; + const expectedTokenId = + staticCoin && typeof staticCoin === 'object' && 'tokenId' in staticCoin && typeof staticCoin.tokenId === 'number' + ? staticCoin.tokenId + : undefined; + const expectedSystemAddress = + staticCoin && + typeof staticCoin === 'object' && + 'systemAddress' in staticCoin && + typeof staticCoin.systemAddress === 'string' && + /^0x[0-9a-fA-F]{40}$/.test(staticCoin.systemAddress) + ? staticCoin.systemAddress.toLowerCase() + : undefined; + if (expectedTokenId === undefined || expectedSystemAddress === undefined) { + await mismatch(`bridgeFunds: missing HyperEVM bridge configuration in statics for '${this.getChain()}'`); + return; + } + if (to !== HYPEEVM_CORE_WRITER_CONTRACT) { + await mismatch('bridgeFunds transaction is not sent to the HyperEVM CoreWriter contract'); + } + if (!tssValuesEqual(value, '0')) { + await mismatch('bridgeFunds transaction must not carry native value'); + } + + const sendRawActionSelector = tssMethodId('sendRawAction', TSS_BRIDGE_SEND_RAW_ACTION_TYPES); + if (!data.startsWith(sendRawActionSelector)) { + await mismatch('bridgeFunds calldata must use sendRawAction(bytes)'); + } + if (!isCanonicalTssCalldata(data, TSS_BRIDGE_SEND_RAW_ACTION_TYPES)) { + await mismatch('bridgeFunds sendRawAction calldata is not canonical'); + } + + const [rawPayload] = decodeTssCalldataArgs(data, TSS_BRIDGE_SEND_RAW_ACTION_TYPES); + const bridgePayload = rawPayload as Buffer; + // Payload = 1 byte version (0x01) + 3 bytes actionId (0x000006) + 3 * 32-byte ABI words = 100 bytes exact + if (!Buffer.isBuffer(bridgePayload) || bridgePayload.length !== 100) { + await mismatch('bridgeFunds payload has invalid length'); + } + if (!bridgePayload.subarray(0, 4).equals(HYPEEVM_BRIDGE_ACTION_HEADER)) { + await mismatch('bridgeFunds payload header must be version 1 and actionId 6'); + } + + const innerArgs = bridgePayload.subarray(4); + let decodedInner: TssDecodedArg[]; + try { + decodedInner = getRawDecoded(TSS_HYPEEVM_BRIDGE_ARGS_TYPES, innerArgs); + const reencodedInner = optionalDeps.ethAbi.rawEncode( + TSS_HYPEEVM_BRIDGE_ARGS_TYPES, + decodedInner.map(toTssEncodable) + ); + if (!reencodedInner.equals(innerArgs)) { + await mismatch('bridgeFunds inner bridge arguments are not canonical'); + } + } catch (e) { + if (e instanceof TxIntentMismatchRecipientError) { + throw e; + } + await mismatch('bridgeFunds inner bridge arguments could not be decoded'); + return; + } + + const [rawDestination, rawTokenId, rawScaledAmount] = decodedInner; + const decodedDestination = addHexPrefix(rawDestination as string).toLowerCase(); + const decodedTokenId = (rawTokenId as BN).toString(10); + const decodedScaledAmount = (rawScaledAmount as BN).toString(10); + + if (decodedDestination !== expectedSystemAddress) { + await mismatch( + 'bridgeFunds destination does not match the HyperEVM system address', + decodedDestination, + decodedScaledAmount + ); + } + if (!tssValuesEqual(decodedTokenId, expectedTokenId.toString())) { + await mismatch('bridgeFunds tokenId does not match the HyperEVM chain configuration', decodedDestination); + } + + // HyperCore amounts are 8-decimal uint64 units. A positive wei amount below one HyperCore unit + // truncates to 0 and would bridge less than the intent declared (or nothing at all), and a value + // above uint64 cannot be carried by the payload at all. + const expectedScaledAmount = BigInt(rawAmount.value.trim()) / HYPEEVM_BRIDGE_DECIMAL_DIVISOR; + if (expectedScaledAmount <= 0n) { + await mismatch( + `bridgeFunds declared amount must be at least one HyperCore unit (${HYPEEVM_BRIDGE_DECIMAL_DIVISOR} wei)`, + decodedDestination, + rawAmount.value + ); + } + if (expectedScaledAmount > UINT64_MAX) { + await mismatch( + 'bridgeFunds declared amount exceeds the HyperCore uint64 limit', + decodedDestination, + expectedScaledAmount.toString() + ); + } + if (!tssValuesEqual(decodedScaledAmount, expectedScaledAmount.toString())) { + await mismatch( + 'bridgeFunds scaled amount does not match the declared amount', + decodedDestination, + decodedScaledAmount + ); + } + } + /** * Verify a `contractCall` / `customTx` (including kebab-case aliases) intent against the decoded * transaction. Fails closed unless exactly one recipient is declared and decoded `to`, `value` @@ -4146,12 +4784,7 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem 'no verifier is implemented for this intent type: the transaction was not compared against the intent' ); } - if (txParams.type && ['defiApprove', 'defiDeposit', 'defiWithdraw'].includes(txParams.type)) { - if (!txPrebuild.txHex) { - throw new Error('missing txHex in txPrebuild'); - } - const baseAddress = wallet.coinSpecific()?.baseAddress; const defiParams = txParams.defiParams; if (!baseAddress || !defiParams) { @@ -4161,32 +4794,37 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem const validatedBaseAddress = baseAddress as string; const validatedDefiParams = defiParams; - const txBuilder = this.getTransactionBuilder(); - txBuilder.from(txPrebuild.txHex); - const txJson = (await txBuilder.build()).toJson(); - const mismatch = async (message: string, address = txJson.to, amount = txJson.value): Promise => + const { to, value, data } = this.decodeRawTssTxFields(txPrebuild.txHex); + const mismatch = async (message: string, address = to, amount = value): Promise => throwRecipientMismatch(message, [{ address: address || '', amount: amount || '' }]); - const data = txJson.data || ''; + + // ERC-4626 DeFi approve, deposit, and withdraw never carry native ETH value + // (native ETH wrapping uses the dedicated `wrap-native` intent, not `defiDeposit`). + if (!tssValuesEqual(value, '0')) { + await mismatch(`${txParams.type} transaction must not carry native value`); + } if (txParams.type === 'defiApprove') { - const selector = addHexPrefix(optionalDeps.ethAbi.methodID('approve', ['address', 'uint256']).toString('hex')); + const selector = tssMethodId('approve', TSS_ERC20_APPROVE_TYPES); if (!data.startsWith(selector)) { await mismatch('defiApprove transaction must use ERC-20 approve(address,uint256) calldata'); } - const [, amount] = getRawDecoded(['address', 'uint256'], getBufferedByteCode(selector, data)); + if (!isCanonicalTssCalldata(data, TSS_ERC20_APPROVE_TYPES)) { + await mismatch('defiApprove approve calldata is not canonical'); + } + const [, amount] = decodeTssCalldataArgs(data, TSS_ERC20_APPROVE_TYPES); if (amount.toString() !== validatedDefiParams.amount) { - await mismatch( - 'defiApprove transaction amount does not match the requested amount', - txJson.to, - amount.toString() - ); + await mismatch('defiApprove transaction amount does not match the requested amount', to, amount.toString()); } } else if (txParams.type === 'defiDeposit') { - const selector = addHexPrefix(optionalDeps.ethAbi.methodID('deposit', ['uint256', 'address']).toString('hex')); + const selector = tssMethodId('deposit', TSS_DEFI_DEPOSIT_TYPES); if (!data.startsWith(selector)) { await mismatch('defiDeposit transaction must use deposit(uint256,address) calldata'); } - const [amount, receiver] = getRawDecoded(['uint256', 'address'], getBufferedByteCode(selector, data)); + if (!isCanonicalTssCalldata(data, TSS_DEFI_DEPOSIT_TYPES)) { + await mismatch('defiDeposit deposit calldata is not canonical'); + } + const [amount, receiver] = decodeTssCalldataArgs(data, TSS_DEFI_DEPOSIT_TYPES); const decodedReceiver = addHexPrefix(receiver.toString()).toLowerCase(); if (decodedReceiver !== validatedBaseAddress.toLowerCase()) { await mismatch( @@ -4203,16 +4841,14 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem ); } } else { - const selector = addHexPrefix( - optionalDeps.ethAbi.methodID('redeem', ['uint256', 'address', 'address']).toString('hex') - ); + const selector = tssMethodId('redeem', TSS_DEFI_REDEEM_TYPES); if (!data.startsWith(selector)) { await mismatch('defiWithdraw transaction must use redeem(uint256,address,address) calldata'); } - const [shares, receiver, owner] = getRawDecoded( - ['uint256', 'address', 'address'], - getBufferedByteCode(selector, data) - ); + if (!isCanonicalTssCalldata(data, TSS_DEFI_REDEEM_TYPES)) { + await mismatch('defiWithdraw redeem calldata is not canonical'); + } + const [shares, receiver, owner] = decodeTssCalldataArgs(data, TSS_DEFI_REDEEM_TYPES); const decodedReceiver = addHexPrefix(receiver.toString()).toLowerCase(); const decodedOwner = addHexPrefix(owner.toString()).toLowerCase(); if ( @@ -4234,7 +4870,6 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem } } } - if (txParams.type === 'wrapApprove') { await this.verifyWrapApproveTransaction(params, throwRecipientMismatch); } else { @@ -4246,6 +4881,12 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem if (txParams.type === 'tokenApproval') { await this.verifyTssTokenApproval(txParams, txPrebuild.txHex, throwRecipientMismatch); + } else if (txType === 'fillNonce') { + await this.verifyTssFillNonce(txParams, wallet, txPrebuild.txHex, throwRecipientMismatch); + } else if (txType === 'transferToken' || txType === 'transfertoken') { + await this.verifyTssTransferToken(txParams, txPrebuild.txHex, throwRecipientMismatch); + } else if (txType === 'bridgeFunds') { + await this.verifyTssBridgeFunds(txParams, txPrebuild.txHex, throwRecipientMismatch); } // Verify consolidation transactions send to base address. The explicit flag is a caller @@ -4317,6 +4958,13 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem } // Sweep amounts are not compared: a consolidation moves whatever the address holds. const token = this.resolveTssToken(txParams.tokenName); + // A known conflict (declared token vs signing token / network, or an explicitly empty name) + // is a mismatch, never a warning: warn-and-continue would sweep an unverified contract. + if (token.mismatch) { + await throwRecipientMismatch(`Consolidation token declaration is invalid: ${token.reason}`, [ + { address: txTo, amount: txValue }, + ]); + } if (token.contract) { if (txTo !== token.contract) { await throwRecipientMismatch('Consolidation transaction does not call the declared token contract', [ diff --git a/modules/abstract-eth/test/unit/tssVerification.ts b/modules/abstract-eth/test/unit/tssVerification.ts new file mode 100644 index 00000000000..2fd308cc8ee --- /dev/null +++ b/modules/abstract-eth/test/unit/tssVerification.ts @@ -0,0 +1,1226 @@ +import 'should'; +import sinon from 'sinon'; +import EthereumAbi from 'ethereumjs-abi'; +import { FeeMarketEIP1559Transaction } from '@ethereumjs/tx'; +import { BitGoAPI } from '@bitgo/sdk-api'; +import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test'; +import { + BitGoBase, + resolveEffectiveTxParams, + TxIntentMismatchRecipientError, + TxRequest, + Wallet, +} from '@bitgo/sdk-core'; +import { BaseCoin as StaticsBaseCoin, coins, EthereumNetwork } from '@bitgo/statics'; +import { AbstractEthLikeNewCoins, TransactionBuilder, TransferBuilder } from '../../src'; + +class TestTransactionBuilder extends TransactionBuilder { + constructor(_coinConfig: Readonly) { + super(_coinConfig); + this._transfer = new TransferBuilder(); + } + + transfer(data?: string): TransferBuilder { + if (data) { + this._transfer = new TransferBuilder(data); + } + return this._transfer as TransferBuilder; + } +} +class TestEvmCoin extends AbstractEthLikeNewCoins { + private readonly chainOverride?: string; + private readonly baseChainOverride?: string; + + constructor( + bitgo: BitGoBase, + staticsCoin: Readonly, + { chainOverride, baseChainOverride }: { chainOverride?: string; baseChainOverride?: string } = {} + ) { + super(bitgo, staticsCoin); + this.chainOverride = chainOverride; + this.baseChainOverride = baseChainOverride; + } + + getChain(): string { + return this.chainOverride ?? super.getChain(); + } + + getBaseChain(): string { + return this.baseChainOverride ?? super.getBaseChain(); + } + + protected getTransactionBuilder(): TransactionBuilder { + return new TestTransactionBuilder(this.staticsCoin as Readonly); + } +} +describe('AbstractEthLikeNewCoins TSS verification (HyperEVM bridgeFunds & Hedera NFT transferFrom)', function () { + const baseAddress = '0x174cfd823af8ce27ed0afee3fcf3c3ba259116be'; + const recipient = '0x7e85bdc27c050e3905ebf4b8e634d9ad6edd0de6'; + const attacker = '0x9f8d0b5e1b3c3f0e2f4b7a6c1d2e3f4a5b6c7d8e'; + const coreWriter = '0x3333333333333333333333333333333333333333'; + const systemAddress = '0x2222222222222222222222222222222222222222'; + + let bitgo: TestBitGoAPI; + let warn: sinon.SinonStub; + + before(function () { + bitgo = TestBitGo.decorate(BitGoAPI, { env: 'test' }); + bitgo.initializeTestVars(); + }); + + beforeEach(function () { + warn = sinon.stub(console, 'warn'); + }); + + afterEach(function () { + sinon.restore(); + }); + + function makeCoin(chain: string): TestEvmCoin { + return new TestEvmCoin(bitgo, coins.get(chain)); + } + + function makeTokenCoin(tokenChain: string, baseChain: string): TestEvmCoin { + // Mirror EthLikeToken / Erc20Token: staticsCoin is the base chain (with EIP-1559), while + // getChain() returns the token's statics name (e.g. 'arbeth:usdt') and getBaseChain() returns + // the base chain ('arbeth'). + return new TestEvmCoin(bitgo, coins.get(baseChain), { + chainOverride: tokenChain, + baseChainOverride: baseChain, + }); + } + + function buildRawEip1559Tx( + coin: TestEvmCoin, + { to, value = '0', data = '0x' }: { to: string; value?: string; data?: string } + ): string { + const chainId = (coin.getNetwork() as EthereumNetwork).chainId; + const common = AbstractEthLikeNewCoins.getCustomChainCommon(chainId); + const tx = FeeMarketEIP1559Transaction.fromTxData( + { + nonce: 1, + maxPriorityFeePerGas: 10, + maxFeePerGas: 100, + gasLimit: 100000, + to, + value: '0x' + BigInt(value).toString(16), + data, + chainId, + }, + { common } + ); + return '0x' + tx.serialize().toString('hex'); + } + + function buildBridgeCalldata({ + version = 1, + actionId = 6, + destination = systemAddress, + tokenId = 150, + scaledAmount = '2100000', + extraInnerHex = '', + extraOuterHex = '', + }: { + version?: number; + actionId?: number; + destination?: string; + tokenId?: number; + scaledAmount?: string; + extraInnerHex?: string; + extraOuterHex?: string; + } = {}): string { + const encodedArgs = EthereumAbi.rawEncode(['address', 'uint64', 'uint64'], [destination, tokenId, scaledAmount]); + const header = Buffer.from([version & 0xff, (actionId >> 16) & 0xff, (actionId >> 8) & 0xff, actionId & 0xff]); + const payload = Buffer.concat([header, encodedArgs, Buffer.from(extraInnerHex, 'hex')]); + const selector = EthereumAbi.methodID('sendRawAction', ['bytes']); + const encodedParams = EthereumAbi.rawEncode(['bytes'], [payload]); + return '0x' + Buffer.concat([selector, encodedParams]).toString('hex') + extraOuterHex; + } + + async function expectMismatch(p: Promise, pattern: RegExp): Promise { + try { + await p; + } catch (e) { + e.should.be.instanceOf(TxIntentMismatchRecipientError); + (e as Error).message.should.match(pattern); + return; + } + throw new Error('expected verifyTransaction to reject'); + } + + describe('HyperEVM bridgeFunds verification', function () { + const prodAmountWei = '21000000000000000'; // 0.021 HYPE -> 2100000 (0x200b20) at 8 decimals + + it('verifies a prod-shaped mainnet hypeevm bridgeFunds transaction (tokenId 150, CoreWriter, 18->8 scaling)', async function () { + const hype = makeCoin('hypeevm'); + const wallet = new Wallet(bitgo, hype, { coinSpecific: { baseAddress } }); + const data = buildBridgeCalldata({ tokenId: 150, scaledAmount: '2100000' }); + const txHex = buildRawEip1559Tx(hype, { to: coreWriter, value: '0', data }); + + const result = await hype.verifyTransaction({ + txParams: { type: 'bridgeFunds', intentAmount: { value: prodAmountWei, symbol: 'hypeevm' } } as never, + txPrebuild: { txHex, coin: 'hypeevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }); + result.should.be.true(); + warn.called.should.be.false(); + }); + + it('verifies a testnet thypeevm bridgeFunds transaction using stored-intent amount field (tokenId 1105)', async function () { + const thype = makeCoin('thypeevm'); + const wallet = new Wallet(bitgo, thype, { coinSpecific: { baseAddress } }); + // Verify truncation semantics: 123456789012345678 / 1e10 === 12345678 + const data = buildBridgeCalldata({ tokenId: 1105, scaledAmount: '12345678' }); + const txHex = buildRawEip1559Tx(thype, { to: coreWriter, value: '0', data }); + + const result = await thype.verifyTransaction({ + txParams: { type: 'bridgeFunds', amount: { value: '123456789012345678', symbol: 'thypeevm' } } as never, + txPrebuild: { txHex, coin: 'thypeevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }); + result.should.be.true(); + warn.called.should.be.false(); + }); + + it('verifies the stored-intent prod shape after real resolveEffectiveTxParams reconstruction', async function () { + const hype = makeCoin('hypeevm'); + const wallet = new Wallet(bitgo, hype, { coinSpecific: { baseAddress } }); + const data = buildBridgeCalldata({ tokenId: 150, scaledAmount: '2100000' }); + const txHex = buildRawEip1559Tx(hype, { to: coreWriter, value: '0', data }); + + // Rebuild the exact stored-intent shape (no caller txParams), as pendingApproval re-signing does. + const txParams = resolveEffectiveTxParams( + { + txRequestId: 'stored-bridge-funds', + walletId: 'fakeWalletId', + intent: { intentType: 'bridgeFunds', amount: { symbol: 'hypeevm', value: prodAmountWei } }, + } as unknown as TxRequest, + undefined, + 'hypeevm' + ); + txParams.intentAmount!.should.deepEqual({ value: prodAmountWei, symbol: 'hypeevm' }); + + const result = await hype.verifyTransaction({ + txParams: txParams as never, + txPrebuild: { txHex, coin: 'hypeevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }); + result.should.be.true(); + warn.called.should.be.false(); + }); + + it('rejects a reconstructed stored intent whose signed scaled amount differs', async function () { + const hype = makeCoin('hypeevm'); + const wallet = new Wallet(bitgo, hype, { coinSpecific: { baseAddress } }); + // Calldata bridges 2100001 units while the stored intent declared 2100000. + const data = buildBridgeCalldata({ tokenId: 150, scaledAmount: '2100001' }); + const txHex = buildRawEip1559Tx(hype, { to: coreWriter, value: '0', data }); + const txParams = resolveEffectiveTxParams( + { + txRequestId: 'stored-bridge-funds', + walletId: 'fakeWalletId', + intent: { intentType: 'bridgeFunds', amount: { symbol: 'hypeevm', value: prodAmountWei } }, + } as unknown as TxRequest, + undefined, + 'hypeevm' + ); + + await expectMismatch( + hype.verifyTransaction({ + txParams: txParams as never, + txPrebuild: { txHex, coin: 'hypeevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /scaled amount does not match the declared amount/ + ); + }); + + it('rejects zero, sub-unit dust, and uint64-overflow declared amounts', async function () { + const hype = makeCoin('hypeevm'); + const wallet = new Wallet(bitgo, hype, { coinSpecific: { baseAddress } }); + const data = buildBridgeCalldata({ tokenId: 150, scaledAmount: '2100000' }); + const txHex = buildRawEip1559Tx(hype, { to: coreWriter, value: '0', data }); + const verifyAmount = (value: string) => + hype.verifyTransaction({ + txParams: { type: 'bridgeFunds', intentAmount: { value, symbol: 'hypeevm' } } as never, + txPrebuild: { txHex, coin: 'hypeevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }); + + // Zero, 1 wei, and just under one 8-decimal HyperCore unit all truncate to 0. + await expectMismatch(verifyAmount('0'), /at least one HyperCore unit/); + await expectMismatch(verifyAmount('1'), /at least one HyperCore unit/); + await expectMismatch(verifyAmount('9999999999'), /at least one HyperCore unit/); + // 2^64 units is one past the uint64 payload limit. + await expectMismatch(verifyAmount((2n ** 64n * 10n ** 10n).toString()), /exceeds the HyperCore uint64 limit/); + }); + + it('accepts the exact uint64 scaled-amount boundary and one unit above dust', async function () { + const hype = makeCoin('hypeevm'); + const wallet = new Wallet(bitgo, hype, { coinSpecific: { baseAddress } }); + const maxUnits = (2n ** 64n - 1n).toString(); + const verifyScaled = (scaledAmount: string) => { + const txHex = buildRawEip1559Tx(hype, { + to: coreWriter, + value: '0', + data: buildBridgeCalldata({ tokenId: 150, scaledAmount }), + }); + return hype.verifyTransaction({ + txParams: { + type: 'bridgeFunds', + intentAmount: { value: (BigInt(scaledAmount) * 10n ** 10n).toString(), symbol: 'hypeevm' }, + } as never, + txPrebuild: { txHex, coin: 'hypeevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }); + }; + + (await verifyScaled(maxUnits)).should.be.true(); + (await verifyScaled('1')).should.be.true(); + }); + + it('rejects wrong contract, nonzero native value, wrong header, wrong destination, wrong tokenId, wrong amount, and non-canonical bytes', async function () { + const hype = makeCoin('hypeevm'); + const wallet = new Wallet(bitgo, hype, { coinSpecific: { baseAddress } }); + const verifyBridge = ( + txHex: string, + txParams: Record = { + type: 'bridgeFunds', + intentAmount: { value: prodAmountWei, symbol: 'hypeevm' }, + } + ) => + hype.verifyTransaction({ + txParams: txParams as never, + txPrebuild: { txHex, coin: 'hypeevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }); + + const validData = buildBridgeCalldata({ tokenId: 150, scaledAmount: '2100000' }); + + // Wrong destination contract (not CoreWriter 0x3333...3333) + await expectMismatch( + verifyBridge(buildRawEip1559Tx(hype, { to: attacker, value: '0', data: validData })), + /not sent to the HyperEVM CoreWriter contract/ + ); + // Nonzero native value + await expectMismatch( + verifyBridge(buildRawEip1559Tx(hype, { to: coreWriter, value: '1', data: validData })), + /must not carry native value/ + ); + // Wrong outer selector + const wrongSelectorData = + '0x' + + Buffer.concat([ + EthereumAbi.methodID('transfer', ['address', 'uint256']), + EthereumAbi.rawEncode(['address', 'uint256'], [attacker, '100']), + ]).toString('hex'); + await expectMismatch( + verifyBridge(buildRawEip1559Tx(hype, { to: coreWriter, value: '0', data: wrongSelectorData })), + /must use sendRawAction\(bytes\)/ + ); + // Wrong version byte + await expectMismatch( + verifyBridge(buildRawEip1559Tx(hype, { to: coreWriter, data: buildBridgeCalldata({ version: 2 }) })), + /payload header must be version 1 and actionId 6/ + ); + // Wrong actionId (e.g. actionId 7 instead of 6) + await expectMismatch( + verifyBridge(buildRawEip1559Tx(hype, { to: coreWriter, data: buildBridgeCalldata({ actionId: 7 }) })), + /payload header must be version 1 and actionId 6/ + ); + // Wrong bridge destination (attacker instead of systemAddress 0x2222...2222) + await expectMismatch( + verifyBridge(buildRawEip1559Tx(hype, { to: coreWriter, data: buildBridgeCalldata({ destination: attacker }) })), + /destination does not match the HyperEVM system address/ + ); + // Wrong tokenId (testnet 1105 on mainnet hypeevm) + await expectMismatch( + verifyBridge(buildRawEip1559Tx(hype, { to: coreWriter, data: buildBridgeCalldata({ tokenId: 1105 }) })), + /tokenId does not match/ + ); + // Wrong scaled amount + await expectMismatch( + verifyBridge( + buildRawEip1559Tx(hype, { to: coreWriter, data: buildBridgeCalldata({ scaledAmount: '2100001' }) }) + ), + /scaled amount does not match/ + ); + // Extra trailing bytes inside inner payload + await expectMismatch( + verifyBridge(buildRawEip1559Tx(hype, { to: coreWriter, data: buildBridgeCalldata({ extraInnerHex: '00' }) })), + /payload has invalid length/ + ); + // Extra trailing bytes after outer ABI encoding + await expectMismatch( + verifyBridge( + buildRawEip1559Tx(hype, { to: coreWriter, data: buildBridgeCalldata({ extraOuterHex: '00'.repeat(32) }) }) + ), + /not canonical/ + ); + // Missing amount in txParams + await expectMismatch( + verifyBridge(buildRawEip1559Tx(hype, { to: coreWriter, data: validData }), { type: 'bridgeFunds' }), + /requires a declared amount/ + ); + // Wrong symbol in txParams + await expectMismatch( + verifyBridge(buildRawEip1559Tx(hype, { to: coreWriter, data: validData }), { + type: 'bridgeFunds', + intentAmount: { value: prodAmountWei, symbol: 'thypeevm' }, + }), + /declared symbol 'thypeevm' does not match chain 'hypeevm'/ + ); + // Non-empty contradictory txParams.recipients must fail closed + await expectMismatch( + verifyBridge(buildRawEip1559Tx(hype, { to: coreWriter, data: validData }), { + type: 'bridgeFunds', + intentAmount: { value: prodAmountWei, symbol: 'hypeevm' }, + recipients: [{ address: attacker, amount: prodAmountWei }], + }), + /bridgeFunds transaction must not declare recipients/ + ); + }); + }); + + describe('Hedera EVM (hbarevm) HTS NFT transferFrom handling', function () { + const htsNftContract = '0x00000000000000000000000000000000007ac203'; + const htsErc20Contract = '0x0000000000000000000000000000000000728a62'; // thbarevm:hbarnativetoken (registered Erc20Coin) + + const transferFromData = (from: string, to: string, idOrAmount: string) => + '0x' + + Buffer.concat([ + EthereumAbi.methodID('transferFrom', ['address', 'address', 'uint256']), + EthereumAbi.rawEncode(['address', 'address', 'uint256'], [from, to, idOrAmount]), + ]).toString('hex'); + + it('warns on HTS NFT transferFrom on thbarevm when targeting an NFT contract with zero native value', async function () { + const thbarevm = makeCoin('thbarevm'); + const wallet = new Wallet(bitgo, thbarevm, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(thbarevm, { + to: htsNftContract, + value: '0', + data: transferFromData(baseAddress, recipient, '1'), + }); + + const result = await thbarevm.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { + tokenType: 'ERC721', + tokenQuantity: '1', + tokenId: '1', + tokenContractAddress: htsNftContract, + }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'thbarevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }); + result.should.be.true(); + warn + .getCalls() + .some((call) => /NFT token transfer \(ERC721\)/.test(String(call.args[0]))) + .should.be.true(); + }); + + it('rejects transferFrom targeting a registered ERC-20 contract even on thbarevm', async function () { + const thbarevm = makeCoin('thbarevm'); + const wallet = new Wallet(bitgo, thbarevm, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(thbarevm, { + to: htsErc20Contract, + value: '0', + data: transferFromData(baseAddress, attacker, '999999'), + }); + + await expectMismatch( + thbarevm.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { + tokenType: 'ERC721', + tokenQuantity: '1', + tokenId: '1', + tokenContractAddress: htsErc20Contract, + }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'thbarevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /canonical NFT safeTransferFrom/ + ); + }); + + it('never warns-only for an unregistered contract without a positive NFT classification', async function () { + // Same NFT-shaped calldata, but the intent declares no tokenType and no resolvable token: + // "not a registered ERC-20" must not be enough to inherit the warn-only path. + const hbarevm = makeCoin('hbarevm'); + const wallet = new Wallet(bitgo, hbarevm, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(hbarevm, { + to: htsNftContract, + value: '0', + data: transferFromData(baseAddress, recipient, '1'), + }); + + await expectMismatch( + hbarevm.verifyTransaction({ + txParams: { type: 'transferToken', recipients: [{ address: recipient, amount: '0' }] } as never, + txPrebuild: { txHex, coin: 'hbarevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /requires a declared ERC-20 token/ + ); + warn.called.should.be.false(); + }); + + it('rejects an NFT transfer whose signed recipient differs from the declared recipient', async function () { + const hbarevm = makeCoin('hbarevm'); + const wallet = new Wallet(bitgo, hbarevm, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(hbarevm, { + to: htsNftContract, + value: '0', + data: transferFromData(baseAddress, attacker, '1'), + }); + + await expectMismatch( + hbarevm.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { + tokenType: 'ERC721', + tokenQuantity: '1', + tokenId: '1', + tokenContractAddress: htsNftContract, + }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'hbarevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /NFT transferToken destination address does not match the recipient address/ + ); + }); + + it('requires the calldata form of the declared NFT standard', async function () { + const hbarevm = makeCoin('hbarevm'); + const wallet = new Wallet(bitgo, hbarevm, { coinSpecific: { baseAddress } }); + // A declared ERC-1155 must not be verified against the 3-argument ERC-721 form. + const txHex = buildRawEip1559Tx(hbarevm, { + to: htsNftContract, + value: '0', + data: transferFromData(baseAddress, recipient, '1'), + }); + + await expectMismatch( + hbarevm.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { + tokenType: 'ERC1155', + tokenQuantity: '1', + tokenId: '1', + tokenContractAddress: htsNftContract, + }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'hbarevm', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /canonical NFT safeTransferFrom/ + ); + }); + }); + + describe('Cross-network token resolution & bare-symbol binding (CECHO-2690 P0)', function () { + const arbethUsdtContract = '0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9'; + const ethUsdtContract = '0xdac17f958d2ee523a2206206994597c13d831ec7'; + const arbethUsdcContract = '0xff970a61a04b1ca14834a43f5de4533ebddb5cc8'; + const tokenQuantity = '1000000'; + + const erc20TransferData = (to: string, amount: string) => + '0x' + + Buffer.concat([ + EthereumAbi.methodID('transfer', ['address', 'uint256']), + EthereumAbi.rawEncode(['address', 'uint256'], [to, amount]), + ]).toString('hex'); + + it('resolves stored bare symbol usdt to Arbitrum USDT (not Ethereum USDT) on arbeth:usdt token wallet', async function () { + const arbethUsdt = makeTokenCoin('arbeth:usdt', 'arbeth'); + const wallet = new Wallet(bitgo, arbethUsdt, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(arbethUsdt, { + to: arbethUsdtContract, + value: '0', + data: erc20TransferData(recipient, tokenQuantity), + }); + + const txParams = resolveEffectiveTxParams( + { + txRequestId: 'stored-arbeth-usdt', + walletId: 'fakeWalletId', + intent: { + intentType: 'transferToken', + recipients: [ + { + address: { address: recipient }, + amount: { value: '0', symbol: 'usdt' }, + tokenData: { tokenName: 'usdt', tokenQuantity, tokenType: 'ERC20' }, + }, + ], + }, + } as unknown as TxRequest, + undefined, + arbethUsdt.getChain() + ); + + const result = await arbethUsdt.verifyTransaction({ + txParams: txParams as never, + txPrebuild: { txHex, coin: 'arbeth:usdt', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }); + result.should.be.true(); + warn.called.should.be.false(); + }); + + it('resolves stored bare symbol usdt to Arbitrum USDT on base arbeth coin', async function () { + const arbeth = makeCoin('arbeth'); + const wallet = new Wallet(bitgo, arbeth, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(arbeth, { + to: arbethUsdtContract, + value: '0', + data: erc20TransferData(recipient, tokenQuantity), + }); + + const txParams = resolveEffectiveTxParams( + { + txRequestId: 'stored-arbeth-base-usdt', + walletId: 'fakeWalletId', + intent: { + intentType: 'transferToken', + recipients: [ + { + address: { address: recipient }, + amount: { value: '0', symbol: 'usdt' }, + tokenData: { tokenName: 'usdt', tokenQuantity, tokenType: 'ERC20' }, + }, + ], + }, + } as unknown as TxRequest, + undefined, + 'arbeth' + ); + + const result = await arbeth.verifyTransaction({ + txParams: txParams as never, + txPrebuild: { txHex, coin: 'arbeth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }); + result.should.be.true(); + warn.called.should.be.false(); + }); + + it('rejects Ethereum USDT contract when signing on arbeth', async function () { + const arbeth = makeCoin('arbeth'); + const wallet = new Wallet(bitgo, arbeth, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(arbeth, { + to: ethUsdtContract, + value: '0', + data: erc20TransferData(recipient, tokenQuantity), + }); + + await expectMismatch( + arbeth.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenName: 'usdt', tokenQuantity, tokenType: 'ERC20' }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'arbeth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /not sent to the declared token contract/ + ); + + // Explicit cross-network contract address is also rejected + await expectMismatch( + arbeth.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { + tokenName: 'usdt', + tokenQuantity, + tokenType: 'ERC20', + tokenContractAddress: ethUsdtContract, + }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'arbeth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /declared tokenContractAddress does not match/ + ); + }); + + it('rejects a mismatched bare symbol (usdc) or unknown bare symbol on an arbeth:usdt token wallet', async function () { + const arbethUsdt = makeTokenCoin('arbeth:usdt', 'arbeth'); + const wallet = new Wallet(bitgo, arbethUsdt, { coinSpecific: { baseAddress } }); + const txToUsdt = buildRawEip1559Tx(arbethUsdt, { + to: arbethUsdtContract, + value: '0', + data: erc20TransferData(recipient, tokenQuantity), + }); + const txToUsdc = buildRawEip1559Tx(arbethUsdt, { + to: arbethUsdcContract, + value: '0', + data: erc20TransferData(recipient, tokenQuantity), + }); + + // Mismatched bare symbol 'usdc' on an 'arbeth:usdt' wallet must be rejected even if tx calls arbeth:usdt or arbeth:usdc + for (const txHex of [txToUsdt, txToUsdc]) { + await expectMismatch( + arbethUsdt.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenName: 'usdc', tokenQuantity, tokenType: 'ERC20' }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'arbeth:usdt', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /does not match signing token 'arbeth:usdt'/ + ); + } + + // Unknown bare symbol must NOT silently fall back to the signing token + await expectMismatch( + arbethUsdt.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenName: 'notatoken', tokenQuantity, tokenType: 'ERC20' }, + }, + ], + } as never, + txPrebuild: { txHex: txToUsdt, coin: 'arbeth:usdt', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /cannot be resolved to a contract on this network/ + ); + }); + }); + + describe('Known token conflicts fail closed on every TSS path (CECHO-2690 P1 #1)', function () { + const arbethUsdcContract = '0xff970a61a04b1ca14834a43f5de4533ebddb5cc8'; + const arbethBatcher = (coins.get('arbeth').network as EthereumNetwork).batcherContractAddress as string; + + const erc20TransferData = (to: string, amount: string) => + '0x' + + Buffer.concat([ + EthereumAbi.methodID('transfer', ['address', 'uint256']), + EthereumAbi.rawEncode(['address', 'uint256'], [to, amount]), + ]).toString('hex'); + const batchTransferFromData = (token: string, addresses: string[], amounts: string[]) => + '0x' + + Buffer.concat([ + EthereumAbi.methodID('batchTransferFrom', ['address', 'address[]', 'uint256[]']), + EthereumAbi.rawEncode(['address', 'address[]', 'uint256[]'], [token, addresses, amounts]), + ]).toString('hex'); + + it('rejects a single payment whose declared token differs from the signing token', async function () { + const arbethUsdt = makeTokenCoin('arbeth:usdt', 'arbeth'); + const wallet = new Wallet(bitgo, arbethUsdt, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(arbethUsdt, { + to: arbethUsdcContract, + value: '0', + data: erc20TransferData(recipient, '1000000'), + }); + + await expectMismatch( + arbethUsdt.verifyTransaction({ + txParams: { + type: 'transfer', + recipients: [{ address: recipient, amount: '1000000', tokenName: 'arbeth:usdc' }], + } as never, + txPrebuild: { txHex, coin: 'arbeth:usdt', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /does not match signing token 'arbeth:usdt'/ + ); + }); + + it('rejects a single payment declaring a token that statics only knows on another network', async function () { + const arbeth = makeCoin('arbeth'); + const wallet = new Wallet(bitgo, arbeth, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(arbeth, { to: recipient, value: '1000' }); + + await expectMismatch( + arbeth.verifyTransaction({ + txParams: { + type: 'transfer', + recipients: [{ address: recipient, amount: '1000', tokenName: 'erc721:witch' }], + } as never, + txPrebuild: { txHex, coin: 'arbeth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /cannot be resolved to a contract on this network/ + ); + }); + + it('rejects a batch payment whose declared token differs from the signing token', async function () { + const arbethUsdt = makeTokenCoin('arbeth:usdt', 'arbeth'); + const wallet = new Wallet(bitgo, arbethUsdt, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(arbethUsdt, { + to: arbethBatcher, + value: '0', + data: batchTransferFromData(arbethUsdcContract, [recipient, attacker], ['1000', '2000']), + }); + + await expectMismatch( + arbethUsdt.verifyTransaction({ + txParams: { + type: 'transfer', + recipients: [ + { address: recipient, amount: '1000', tokenName: 'arbeth:usdc' }, + { address: attacker, amount: '2000', tokenName: 'arbeth:usdc' }, + ], + } as never, + txPrebuild: { txHex, coin: 'arbeth:usdt', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /does not match signing token 'arbeth:usdt'/ + ); + }); + + it('rejects a token consolidation whose declared token differs from the signing token', async function () { + const arbethUsdt = makeTokenCoin('arbeth:usdt', 'arbeth'); + const wallet = new Wallet(bitgo, arbethUsdt, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(arbethUsdt, { + to: arbethUsdcContract, + value: '0', + data: erc20TransferData(baseAddress, '1000'), + }); + + await expectMismatch( + arbethUsdt.verifyTransaction({ + txParams: { type: 'consolidateToken', tokenName: 'arbeth:usdc' } as never, + txPrebuild: { txHex, coin: 'arbeth:usdt', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /Consolidation token declaration is invalid: .*does not match signing token 'arbeth:usdt'/ + ); + }); + }); + + describe('NFT warn-only contract binding & same-network enforcement (CECHO-2690 P1 #2)', function () { + const hoodiNftContract = '0x8397b091514c1f7bebb9dea6ac267ea23b570605'; // terc721:bitgoerc721 (Hoodi) + const ethNftContract = '0x5180db8f5c931aae63c74266b211f580155ecac8'; // erc721:witch (Ethereum mainnet) + + const safeTransferFromData = (from: string, to: string, tokenId: string) => + '0x' + + Buffer.concat([ + EthereumAbi.methodID('safeTransferFrom', ['address', 'address', 'uint256']), + EthereumAbi.rawEncode(['address', 'address', 'uint256'], [from, to, tokenId]), + ]).toString('hex'); + + it('rejects NFT transferToken without any concrete same-network contract address', async function () { + const hteth = makeCoin('hteth'); + const wallet = new Wallet(bitgo, hteth, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(hteth, { + to: hoodiNftContract, + value: '0', + data: safeTransferFromData(baseAddress, recipient, '42'), + }); + + // Declared tokenType: 'ERC721' with no contract address + await expectMismatch( + hteth.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenType: 'ERC721', tokenQuantity: '1', tokenId: '42' }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'hteth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /requires a declared or registered same-network contract address/ + ); + warn.called.should.be.false(); + + // Generic statics NFT placeholder (`terc721:token` has non-hex contract `0xterc721:token`) without declared contract + await expectMismatch( + hteth.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenName: 'terc721:token', tokenQuantity: '1', tokenId: '42' }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'hteth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /requires a declared or registered same-network contract address/ + ); + warn.called.should.be.false(); + }); + + it('rejects a cross-network statics NFT name (erc721:witch on hteth)', async function () { + const hteth = makeCoin('hteth'); + const wallet = new Wallet(bitgo, hteth, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(hteth, { + to: ethNftContract, + value: '0', + data: safeTransferFromData(baseAddress, recipient, '42'), + }); + + // Without tokenType: must NOT classify as NFT from a cross-network statics coin + await expectMismatch( + hteth.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenName: 'erc721:witch', tokenQuantity: '1', tokenId: '42' }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'hteth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /cannot be resolved to a contract on this network/ + ); + warn.called.should.be.false(); + + // With tokenType: 'ERC721' and cross-network tokenName: must still fail closed + await expectMismatch( + hteth.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { + tokenType: 'ERC721', + tokenName: 'erc721:witch', + tokenContractAddress: ethNftContract, + tokenQuantity: '1', + tokenId: '42', + }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'hteth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /does not belong to this network/ + ); + warn.called.should.be.false(); + }); + + it('warns and passes for a same-network statics NFT with matching contract, recipient, canonical calldata, and zero value', async function () { + const hteth = makeCoin('hteth'); + const wallet = new Wallet(bitgo, hteth, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(hteth, { + to: hoodiNftContract, + value: '0', + data: safeTransferFromData(baseAddress, recipient, '42'), + }); + + const result = await hteth.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenName: 'terc721:bitgoerc721', tokenQuantity: '1', tokenId: '42' }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'hteth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }); + result.should.be.true(); + warn + .getCalls() + .some((call) => /NFT token transfer \(ERC721\)/.test(String(call.args[0]))) + .should.be.true(); + + // Same statics NFT name targeting a different contract must fail closed + const wrongContractTx = buildRawEip1559Tx(hteth, { + to: attacker, + value: '0', + data: safeTransferFromData(baseAddress, recipient, '42'), + }); + await expectMismatch( + hteth.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenName: 'terc721:bitgoerc721', tokenQuantity: '1', tokenId: '42' }, + }, + ], + } as never, + txPrebuild: { txHex: wrongContractTx, coin: 'hteth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /not sent to the declared contract/ + ); + }); + + it('ignores a contract-only statics match from a same-type network (Hoodi NFT on teth)', async function () { + // No tokenName: only the contract address is declared, and `getToken` matches any testnet. + const teth = makeCoin('teth'); + const wallet = new Wallet(bitgo, teth, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(teth, { + to: hoodiNftContract, + value: '0', + data: safeTransferFromData(baseAddress, recipient, '42'), + }); + + await expectMismatch( + teth.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenContractAddress: hoodiNftContract, tokenQuantity: '1', tokenId: '42' }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'teth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /requires a declared ERC-20 token/ + ); + warn.called.should.be.false(); + }); + }); + + describe('Explicitly empty tokenName is a declaration, not an omission (CECHO-2690 P1 #3)', function () { + const arbethUsdtContract = '0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9'; + const tokenQuantity = '1000000'; + + const erc20TransferData = (to: string, amount: string) => + '0x' + + Buffer.concat([ + EthereumAbi.methodID('transfer', ['address', 'uint256']), + EthereumAbi.rawEncode(['address', 'uint256'], [to, amount]), + ]).toString('hex'); + + it('rejects an explicitly empty tokenName on a native coin payment', async function () { + const arbeth = makeCoin('arbeth'); + const wallet = new Wallet(bitgo, arbeth, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(arbeth, { to: recipient, value: '1000' }); + + await expectMismatch( + arbeth.verifyTransaction({ + txParams: { + type: 'transfer', + recipients: [{ address: recipient, amount: '1000', tokenName: '' }], + } as never, + txPrebuild: { txHex, coin: 'arbeth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /declared tokenName is empty/ + ); + }); + + it('rejects an explicitly empty tokenName on a token-scoped coin payment', async function () { + const arbethUsdt = makeTokenCoin('arbeth:usdt', 'arbeth'); + const wallet = new Wallet(bitgo, arbethUsdt, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(arbethUsdt, { + to: arbethUsdtContract, + value: '0', + data: erc20TransferData(recipient, tokenQuantity), + }); + + await expectMismatch( + arbethUsdt.verifyTransaction({ + txParams: { + type: 'transfer', + recipients: [{ address: recipient, amount: tokenQuantity, tokenName: '' }], + } as never, + txPrebuild: { txHex, coin: 'arbeth:usdt', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /declared tokenName is empty/ + ); + }); + + it('rejects an explicitly empty tokenData.tokenName on a native coin transferToken', async function () { + const arbeth = makeCoin('arbeth'); + const wallet = new Wallet(bitgo, arbeth, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(arbeth, { + to: arbethUsdtContract, + value: '0', + data: erc20TransferData(recipient, tokenQuantity), + }); + + await expectMismatch( + arbeth.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenName: '', tokenQuantity, tokenType: 'ERC20' }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'arbeth', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /transferToken declared tokenName is empty/ + ); + }); + + it('rejects a whitespace-only tokenData.tokenName on a token-scoped coin transferToken', async function () { + const arbethUsdt = makeTokenCoin('arbeth:usdt', 'arbeth'); + const wallet = new Wallet(bitgo, arbethUsdt, { coinSpecific: { baseAddress } }); + const txHex = buildRawEip1559Tx(arbethUsdt, { + to: arbethUsdtContract, + value: '0', + data: erc20TransferData(recipient, tokenQuantity), + }); + + await expectMismatch( + arbethUsdt.verifyTransaction({ + txParams: { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenName: ' ', tokenQuantity, tokenType: 'ERC20' }, + }, + ], + } as never, + txPrebuild: { txHex, coin: 'arbeth:usdt', walletId: 'fakeWalletId' } as never, + wallet, + verification: {}, + walletType: 'tss', + }), + /transferToken declared tokenName is empty/ + ); + }); + }); +}); diff --git a/modules/sdk-coin-eth/test/unit/eth.ts b/modules/sdk-coin-eth/test/unit/eth.ts index 6f21325c7fa..0cb804cb93c 100644 --- a/modules/sdk-coin-eth/test/unit/eth.ts +++ b/modules/sdk-coin-eth/test/unit/eth.ts @@ -890,12 +890,17 @@ describe('ETH:', function () { walletPassphrase: 'fakeWalletPassphrase', }; + const txBuilder = getBuilder('hteth') as TransactionBuilder; + txBuilder.type(TransactionType.SingleSigSend); + txBuilder.fee({ fee: '10', gasLimit: '21000' }); + txBuilder.counter(1); + txBuilder.contract(baseAddress); + txBuilder.value('1'); const txPrebuild = { - txHex: '0x', + txHex: (await txBuilder.build()).toBroadcastFormat(), coin: 'hteth', walletId: 'fakeWalletId', }; - const verification = {}; const isTransactionVerified = await coin.verifyTransaction({ @@ -1719,8 +1724,9 @@ describe('ETH:', function () { }); it('should not affect approvals of the underlying to other spenders', async function () { - // tokenApproval and customTx have their own verifiers; an intent type with no verifier still passes untouched. - (await verifyAs('transferToken', defiCalldata('approve(address,uint256)', [address2, amount]))).should.equal( + // tokenApproval, customTx, transferToken, and fillNonce have their own verifiers; an intent type + // with no verifier (acceleration) still passes untouched. + (await verifyAs('acceleration', defiCalldata('approve(address,uint256)', [address2, amount]))).should.equal( true ); }); @@ -1737,7 +1743,7 @@ describe('ETH:', function () { ); try { await coin.verifyTransaction({ - txParams: { type: 'transferToken', wallet } as never, + txParams: { type: 'acceleration', wallet } as never, txPrebuild: { txHex, coin: 'hteth', walletId: 'w' } as any, wallet, verification: {}, @@ -1757,12 +1763,10 @@ describe('ETH:', function () { // Every type below skips the wrapApprove check and reaches the guard; none of these txs is an approve of a // wrapper, so all must verify exactly as they did before the guard existed. const benign: Array<[string, string, string]> = [ - // tokenApproval and customTx are verified by their own handlers and are not part of this list. - ['transferToken', defiCalldata('transfer(address,uint256)', [address2, amount]), underlying], - ['transferToken', defiCalldata('approve(address,uint256)', [address2, amount]), underlying], - ['transferToken', defiCalldata('approve(address,uint256)', [wrapper, amount]), address2], + // tokenApproval, customTx, transferToken, and fillNonce are verified by their own handlers and are not part of this list. ['acceleration', defiCalldata('transfer(address,uint256)', [address2, amount]), address2], - ['fillNonce', '0x', address2], + ['acceleration', defiCalldata('approve(address,uint256)', [address2, amount]), underlying], + ['acceleration', defiCalldata('approve(address,uint256)', [wrapper, amount]), address2], ['enabletoken', defiCalldata('transfer(address,uint256)', [address2, amount]), address2], ]; for (const [type, data, to] of benign) { @@ -1771,14 +1775,13 @@ describe('ETH:', function () { }); it('should not affect transfers to the underlying or approves of the wrapper on other contracts', async function () { - (await verifyAs('transferToken', defiCalldata('transfer(address,uint256)', [wrapper, amount]))).should.equal( + (await verifyAs('acceleration', defiCalldata('transfer(address,uint256)', [wrapper, amount]))).should.equal( true ); ( - await verifyAs('transferToken', defiCalldata('approve(address,uint256)', [wrapper, amount]), address2) + await verifyAs('acceleration', defiCalldata('approve(address,uint256)', [wrapper, amount]), address2) ).should.equal(true); }); - it('should still verify a declared wrapApprove through the full check', async function () { const coin = bitgo.coin('hteth') as Hteth; const wallet = new Wallet(bitgo, coin, { coinSpecific: { baseAddress: address1 } }); diff --git a/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts b/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts index 68f9e413609..d4e858d9453 100644 --- a/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts +++ b/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts @@ -9,6 +9,7 @@ import { EcdsaMPCv2Utils, EcdsaUtils, RequestTracer, + resolveEffectiveTxParams, TransactionType, TxIntentMismatchRecipientError, TxRequest, @@ -1163,4 +1164,676 @@ describe('TSS payment verification', function () { }); } }); + + // CECHO-2690: fillNonce must be a plain self-send (no calldata) to the wallet address with value 0 or 1 wei. + describe('fillNonce verification', function () { + it('verifies a prod-shaped fillNonce self-send (1 wei, empty calldata, to == baseAddress)', async function () { + const txHex = await buildTx({ to: baseAddress, value: '1' }); + (await verify({ type: 'fillNonce' }, txHex)).should.be.true(); + warn.called.should.be.false(); + }); + + it('verifies a 0 wei fillNonce self-send', async function () { + const txHex = await buildTx({ to: baseAddress, value: '0' }); + (await verify({ type: 'fillNonce' }, txHex)).should.be.true(); + }); + + it('ignores a caller-declared receiveAddress and still requires the wallet base address', async function () { + // Every production fillNonce row is a self-send (senderAddressIndex 0 to baseAddress); a + // caller-supplied address must never redirect the filler. + const txHex = await buildTx({ to: recipient, value: '1' }); + await expectMismatch( + verify({ type: 'fillNonce', receiveAddress: recipient }, txHex), + /destination does not match wallet base address/ + ); + }); + + it('rejects a fillNonce sent to an address other than the wallet address', async function () { + const txHex = await buildTx({ to: otherRecipient, value: '1' }); + await expectMismatch(verify({ type: 'fillNonce' }, txHex), /destination does not match wallet base address/); + }); + + it('verifies a declared nonce that matches and rejects any other nonce', async function () { + const txHex = await buildTx({ to: baseAddress, value: '1' }); + // buildTx increments to counter 1, so the signed nonce is 1. + (await verify({ type: 'fillNonce', nonce: '1' }, txHex)).should.be.true(); + (await verify({ type: 'fillNonce', nonce: 1 }, txHex)).should.be.true(); + await expectMismatch( + verify({ type: 'fillNonce', nonce: '2' }, txHex), + /nonce 1 does not match the declared nonce 2/ + ); + await expectMismatch( + verify({ type: 'fillNonce', nonce: 'abc' }, txHex), + /declared nonce must be a non-negative integer/ + ); + }); + + it('enforces numeric stored nonce 0 through resolveEffectiveTxParams reconstruction', async function () { + const common = AbstractEthLikeNewCoins.getCustomChainCommon(coin.getChainId()); + const buildWithNonce = (nonce: number) => { + const tx = FeeMarketEIP1559Transaction.fromTxData( + { + nonce, + maxPriorityFeePerGas: 10, + maxFeePerGas: 100, + gasLimit: 21000, + to: baseAddress, + value: 1, + data: '0x', + chainId: coin.getChainId(), + }, + { common } + ); + return '0x' + tx.serialize().toString('hex'); + }; + + const txParams = resolveEffectiveTxParams( + { + txRequestId: 'stored-fill-nonce-zero', + walletId: 'fakeWalletId', + intent: { intentType: 'fillNonce', nonce: 0 }, + } as unknown as TxRequest, + undefined, + 'hteth' + ); + String(txParams.nonce).should.equal('0'); + + (await verify(txParams as Record, buildWithNonce(0))).should.be.true(); + await expectMismatch( + verify(txParams as Record, buildWithNonce(1)), + /nonce 1 does not match the declared nonce 0/ + ); + }); + + it('rejects a fillNonce carrying calldata (including sub-selector raw bytes)', async function () { + const txHex = await buildTx({ to: baseAddress, value: '1', data: erc20Transfer(otherRecipient, '100') }); + await expectMismatch(verify({ type: 'fillNonce' }, txHex), /must not carry calldata/); + + const common = AbstractEthLikeNewCoins.getCustomChainCommon(coin.getChainId()); + const subSelectorTx = FeeMarketEIP1559Transaction.fromTxData( + { + nonce: 1, + maxPriorityFeePerGas: 10, + maxFeePerGas: 100, + gasLimit: 21000, + to: baseAddress, + value: 1, + data: '0x01', + chainId: coin.getChainId(), + }, + { common } + ); + await expectMismatch( + verify({ type: 'fillNonce' }, '0x' + subSelectorTx.serialize().toString('hex')), + /must not carry calldata/ + ); + }); + + it('rejects a fillNonce with value greater than 1 wei', async function () { + const txHex = await buildTx({ to: baseAddress, value: '2' }); + await expectMismatch(verify({ type: 'fillNonce' }, txHex), /value must be 0 or 1 wei/); + }); + + it('rejects a fillNonce when the wallet has no baseAddress and no receiveAddress is declared', async function () { + const noBaseWallet = new Wallet(bitgo, coin, { coinSpecific: {} }); + const txHex = await buildTx({ to: baseAddress, value: '1' }); + await expectMismatch( + coin.verifyTransaction({ + txParams: { type: 'fillNonce' } as never, + txPrebuild: { txHex, coin: 'hteth', walletId: 'fakeWalletId' } as never, + wallet: noBaseWallet, + verification: {}, + walletType: 'tss', + }), + /requires a wallet base address/ + ); + }); + }); + + // CECHO-2690: transferToken ERC-20 fails closed (coordinated with COINS-2263 amount semantics); + // ERC-721 / ERC-1155 NFT transferToken stays warn-only while enforcing canonical NFT calldata and value == 0. + describe('transferToken verification', function () { + const nftContract = '0x5df4076613e714a4cc4284abac87caa927b918a8'; + const erc721Safe3 = (from: string, to: string, tokenId: string) => + calldata('safeTransferFrom', ['address', 'address', 'uint256'], [from, to, tokenId]); + const erc1155Safe = (from: string, to: string, tokenId: string, qty: string) => + calldata( + 'safeTransferFrom', + ['address', 'address', 'uint256', 'uint256', 'bytes'], + [from, to, tokenId, qty, Buffer.alloc(0)] + ); + const erc20TransferFrom = (from: string, to: string, qty: string) => + calldata('transferFrom', ['address', 'address', 'uint256'], [from, to, qty]); + + for (const type of ['transferToken', 'transfertoken']) { + it(`verifies prod eth/arbeth shape (${type}, amount='0' placeholder + tokenData.tokenQuantity)`, async function () { + const txHex = await buildTx({ to: tokenContract, data: erc20Transfer(recipient, '1000000') }); + const txParams = { + type, + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { + tokenType: 'ERC20', + tokenQuantity: '1000000', + tokenName, + tokenContractAddress: tokenContract, + }, + }, + ], + }; + (await verify(txParams, txHex)).should.be.true(); + warn.called.should.be.false(); + }); + } + + it('verifies prod bsc/polygon shape (amount === tokenData.tokenQuantity)', async function () { + const txHex = await buildTx({ to: tokenContract, data: erc20Transfer(recipient, '500000') }); + const txParams = { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '500000', + tokenName, + tokenData: { tokenType: 'ERC20', tokenQuantity: '500000', tokenName }, + }, + ], + }; + (await verify(txParams, txHex)).should.be.true(); + warn.called.should.be.false(); + }); + + it('verifies contract-only ERC-20 transferToken resolved through @bitgo/statics', async function () { + const txHex = await buildTx({ to: tokenContract, data: erc20Transfer(recipient, '250') }); + const txParams = { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '250', + tokenData: { tokenType: 'ERC20', tokenQuantity: '250', tokenContractAddress: tokenContract }, + }, + ], + }; + (await verify(txParams, txHex)).should.be.true(); + }); + + it('rejects amount vs tokenData.tokenQuantity spoofing (COINS-2263)', async function () { + const txHex = await buildTx({ to: tokenContract, data: erc20Transfer(recipient, '1000000') }); + const txParams = { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '3', + tokenData: { tokenType: 'ERC20', tokenQuantity: '1000000', tokenName }, + }, + ], + }; + await expectMismatch(verify(txParams, txHex), /does not match tokenData\.tokenQuantity/); + }); + + it('rejects non-integer tokenQuantity', async function () { + const txHex = await buildTx({ to: tokenContract, data: erc20Transfer(recipient, '100') }); + const txParams = { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenType: 'ERC20', tokenQuantity: '1.5', tokenName }, + }, + ], + }; + await expectMismatch(verify(txParams, txHex), /tokenQuantity must be a non-negative integer/); + }); + + it('rejects recipient, amount, contract, native value, selector, trailing bytes, and missing/multiple recipients', async function () { + const baseIntent = { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenType: 'ERC20', tokenQuantity: '1000', tokenName }, + }, + ], + }; + + await expectMismatch( + verify(baseIntent, await buildTx({ to: tokenContract, data: erc20Transfer(otherRecipient, '1000') })), + /destination address does not match/ + ); + await expectMismatch( + verify(baseIntent, await buildTx({ to: tokenContract, data: erc20Transfer(recipient, '999') })), + /does not match the declared token amount/ + ); + await expectMismatch( + verify(baseIntent, await buildTx({ to: otherTokenContract, data: erc20Transfer(recipient, '1000') })), + /not sent to the declared token contract/ + ); + await expectMismatch( + verify(baseIntent, await buildTx({ to: tokenContract, value: '1', data: erc20Transfer(recipient, '1000') })), + /must not carry native value/ + ); + await expectMismatch( + verify( + baseIntent, + await buildTx({ + to: tokenContract, + data: calldata('approve', ['address', 'uint256'], [otherRecipient, '1000']), + }) + ), + /must use ERC-20 transfer/ + ); + await expectMismatch( + verify( + baseIntent, + await buildTx({ to: tokenContract, data: erc20Transfer(recipient, '1000') + '00'.repeat(32) }) + ), + /not canonical/ + ); + await expectMismatch( + verify( + { type: 'transferToken', recipients: [] }, + await buildTx({ to: tokenContract, data: erc20Transfer(recipient, '1000') }) + ), + /must declare a single recipient/ + ); + await expectMismatch( + verify( + { + type: 'transferToken', + recipients: [ + { address: recipient, amount: '1000', tokenName }, + { address: otherRecipient, amount: '1000', tokenName }, + ], + }, + await buildTx({ to: tokenContract, data: erc20Transfer(recipient, '1000') }) + ), + /must declare a single recipient/ + ); + }); + + it('fails closed when the ERC-20 token cannot be resolved in @bitgo/statics', async function () { + const txHex = await buildTx({ to: otherTokenContract, data: erc20Transfer(recipient, '1000') }); + await expectMismatch( + verify( + { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenType: 'ERC20', tokenQuantity: '1000', tokenName: 'hteth:notatoken' }, + }, + ], + }, + txHex + ), + /cannot be resolved to a contract on this network/ + ); + }); + + it('rejects mismatched declared tokenContractAddress vs registered statics contract', async function () { + const txHex = await buildTx({ to: tokenContract, data: erc20Transfer(recipient, '1000') }); + await expectMismatch( + verify( + { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { + tokenType: 'ERC20', + tokenQuantity: '1000', + tokenName, + tokenContractAddress: otherTokenContract, + }, + }, + ], + }, + txHex + ), + /declared tokenContractAddress does not match/ + ); + }); + + it('warns on ERC-721 and ERC-1155 NFT transferToken with canonical safeTransferFrom and value == 0', async function () { + const erc721Tx = await buildTx({ to: nftContract, data: erc721Safe3(baseAddress, recipient, '42') }); + ( + await verify( + { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { + tokenType: 'ERC721', + tokenQuantity: '1', + tokenId: '42', + tokenContractAddress: nftContract, + }, + }, + ], + }, + erc721Tx + ) + ).should.be.true(); + warned(/NFT token transfer \(ERC721\)/).should.be.true(); + + warn.resetHistory(); + const erc1155Tx = await buildTx({ to: nftContract, data: erc1155Safe(baseAddress, recipient, '7', '3') }); + ( + await verify( + { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { + tokenType: 'ERC1155', + tokenQuantity: '3', + tokenId: '7', + tokenContractAddress: nftContract, + }, + }, + ], + }, + erc1155Tx + ) + ).should.be.true(); + warned(/NFT token transfer \(ERC1155\)/).should.be.true(); + }); + + it('rejects NFT transferToken smuggling nonzero native value, wrong contract, or ERC-20 transferFrom on non-Hedera chains', async function () { + const erc721Intent = { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { + tokenType: 'ERC721', + tokenQuantity: '1', + tokenId: '42', + tokenContractAddress: nftContract, + }, + }, + ], + }; + + await expectMismatch( + verify( + erc721Intent, + await buildTx({ to: nftContract, value: '1', data: erc721Safe3(baseAddress, recipient, '42') }) + ), + /must not carry native value/ + ); + await expectMismatch( + verify( + erc721Intent, + await buildTx({ to: otherTokenContract, data: erc721Safe3(baseAddress, recipient, '42') }) + ), + /not sent to the declared contract/ + ); + await expectMismatch( + verify(erc721Intent, await buildTx({ to: tokenContract, data: erc20Transfer(otherRecipient, '999999') })), + /canonical NFT safeTransferFrom/ + ); + // ERC-20 transferFrom shares selector 0x23b872dd — must NEVER bypass on non-Hedera chains + await expectMismatch( + verify( + erc721Intent, + await buildTx({ to: nftContract, data: erc20TransferFrom(baseAddress, otherRecipient, '999999') }) + ), + /canonical NFT safeTransferFrom/ + ); + await expectMismatch( + verify( + { type: 'transferToken', recipients: [{ address: recipient, amount: '0' }] }, + await buildTx({ to: tokenContract, data: erc20TransferFrom(baseAddress, otherRecipient, '999999') }) + ), + /requires a declared ERC-20 token/ + ); + }); + + it('binds the NFT decoded recipient to the declared recipient', async function () { + // The tokenId/quantity stays warn-only, but the signed destination must still be the declared one. + const erc721Intent = { + type: 'transferToken', + recipients: [ + { + address: recipient, + amount: '0', + tokenData: { tokenType: 'ERC721', tokenQuantity: '1', tokenId: '42', tokenContractAddress: nftContract }, + }, + ], + }; + await expectMismatch( + verify(erc721Intent, await buildTx({ to: nftContract, data: erc721Safe3(baseAddress, otherRecipient, '42') })), + /NFT transferToken destination address does not match the recipient address/ + ); + // A matching calldata recipient still verifies (with the warning) so the binding is not over-tight. + ( + await verify(erc721Intent, await buildTx({ to: nftContract, data: erc721Safe3(baseAddress, recipient, '42') })) + ).should.be.true(); + }); + }); + + // CECHO-2690 P0: a stored transferToken intent keeps tokenData (tokenQuantity / tokenType / contract); + // the sdk-core reconstruction must carry it into verifyTssTransaction, otherwise MPCv1/MPCv2 + // re-signing has only the '0' amount placeholder to verify against. + describe('stored transferToken intent without caller txParams', function () { + const signingBoundaryMessage = 'signing boundary reached after intent verification'; + const tokenQuantity = '1000000'; + + function transferBytes(to: string, amount: string) { + const common = AbstractEthLikeNewCoins.getCustomChainCommon(coin.getChainId()); + const tx = FeeMarketEIP1559Transaction.fromTxData( + { + nonce: 1, + maxPriorityFeePerGas: 10, + maxFeePerGas: 100, + gasLimit: 200000, + to, + value: 0, + data: erc20Transfer(recipient, amount), + chainId: coin.getChainId(), + }, + { common } + ); + return { + signableHex: tx.getMessageToSign(false).toString('hex'), + serializedTxHex: tx.serialize().toString('hex'), + }; + } + + function storedTransferRequest( + bytes: { signableHex: string; serializedTxHex: string }, + tokenData: Record + ): TxRequest { + return { + txRequestId: 'stored-transfer-token', + apiVersion: 'full', + walletId: 'storedTransferWallet', + intent: { + intentType: 'transferToken', + recipients: [{ address: { address: recipient }, amount: { value: '0', symbol: 'stgusd1' }, tokenData }], + }, + transactions: [{ unsignedTx: { derivationPath: 'm/0', ...bytes }, signatureShares: [] }], + } as unknown as TxRequest; + } + + async function runMpcv2(txRequest: TxRequest): Promise<{ error: Error; boundary: Error }> { + const signingWallet = new Wallet(bitgo, coin, { + id: 'storedTransferWallet', + multisigType: 'tss', + multisigTypeVersion: 'MPCv2', + coinSpecific: { baseAddress }, + }); + const utils = new EcdsaMPCv2Utils(bitgo, coin, signingWallet); + sinon + .stub(utils as unknown as Record Promise>, 'pickBitgoPubGpgKeyForSigning') + .resolves('stubbed-gpg-key'); + + const baseConfig = coin.getConfig(); + sinon.stub(coin, 'getConfig').returns({ + ...baseConfig, + features: baseConfig.features.filter((f) => f !== CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX), + } as unknown as Readonly); + + const boundary = new Error(signingBoundaryMessage); + sinon.stub(coin, 'getHashFunction').returns({ + update: () => { + throw boundary; + }, + } as unknown as Hash); + + try { + await utils.signTxRequest({ txRequest, prv: '', reqId: new RequestTracer() }); + } catch (e) { + return { error: e as Error, boundary }; + } + throw new Error('expected signTxRequest to reject'); + } + + it('verifies the prod eth/arbeth shape from the reconstructed stored intent (MPCv2)', async function () { + const { error, boundary } = await runMpcv2( + storedTransferRequest(transferBytes(tokenContract, tokenQuantity), { + tokenName, + tokenQuantity, + tokenType: 'ERC20', + }) + ); + error.should.be.exactly(boundary); + warn.called.should.be.false(); + }); + + it('verifies a contract-only stored intent resolved through @bitgo/statics (MPCv2)', async function () { + const { error, boundary } = await runMpcv2( + storedTransferRequest(transferBytes(tokenContract, '250'), { + tokenQuantity: '250', + tokenType: 'ERC20', + tokenContractAddress: tokenContract, + }) + ); + error.should.be.exactly(boundary); + }); + + it('verifies a stored bare-symbol intent on a token wallet (prod shape)', async function () { + // Production rows persist tokenData.tokenName as the bare symbol ('usdt') with no contract, so the + // name resolves to nothing; the wallet's own `chain:token` identity must bind the signed bytes. + // Testnet token statics omit EIP1559 while mainnet ETH token coins enable it; production + // transferToken bytes are EIP-1559, so mirror that feature on the token coin. + const tokenStatics = coins.get(tokenName); + const tokenCoin = Hteth.createInstance(bitgo, { + ...tokenStatics, + features: [...tokenStatics.features, CoinFeature.EIP1559], + } as unknown as Readonly); + const tokenWallet = new Wallet(bitgo, tokenCoin, { coinSpecific: { baseAddress } }); + const bytes = transferBytes(tokenContract, tokenQuantity); + const txParams = resolveEffectiveTxParams( + storedTransferRequest(bytes, { tokenName: 'stgusd1', tokenQuantity, tokenType: 'ERC20' }), + undefined, + tokenCoin.getChain() + ); + txParams.recipients![0].tokenData!.tokenQuantity.should.equal(tokenQuantity); + + const result = await tokenCoin.verifyTransaction({ + txParams: txParams as never, + txPrebuild: { txHex: '0x' + bytes.serializedTxHex, coin: tokenName, walletId: 'fakeWalletId' } as never, + wallet: tokenWallet, + verification: {}, + walletType: 'tss', + }); + result.should.be.true(); + warn.called.should.be.false(); + }); + + it('rejects a stored intent whose signed amount differs from tokenQuantity (MPCv2)', async function () { + const { error } = await runMpcv2( + storedTransferRequest(transferBytes(tokenContract, '999999'), { + tokenName, + tokenQuantity, + tokenType: 'ERC20', + }) + ); + error.should.be.instanceOf(TxIntentMismatchRecipientError); + error.message.should.match(/does not match the declared token amount/); + }); + }); + + // CECHO-2690: bridgeFunds is rejected outright on non-HyperEVM EVM chains. + describe('bridgeFunds on non-HyperEVM chains', function () { + it('rejects bridgeFunds outright on hteth', async function () { + const txHex = await buildTx({ to: '0x3333333333333333333333333333333333333333', value: '0' }); + await expectMismatch( + verify({ type: 'bridgeFunds', intentAmount: { value: '10000000000000000', symbol: 'hteth' } }, txHex), + /bridgeFunds is not supported on EVM coin 'hteth'/ + ); + }); + }); + + // CECHO-2690: DeFi intents (defiApprove, defiDeposit, defiWithdraw) never carry native ETH value + // and must use canonical ABI calldata. + describe('DeFi native value and canonical calldata verification', function () { + const defiParams = { vaultId: 'hteth-usdc-test', amount: '10', operationId: 'op-1' }; + const approveData = calldata('approve', ['address', 'uint256'], [recipient, '10']); + const depositData = calldata('deposit', ['uint256', 'address'], ['10', baseAddress]); + const redeemData = calldata('redeem', ['uint256', 'address', 'address'], ['10', baseAddress, baseAddress]); + + it('rejects nonzero native value on defiApprove, defiDeposit, and defiWithdraw', async function () { + await expectMismatch( + verify( + { type: 'defiApprove', defiParams }, + await buildTx({ to: tokenContract, value: '1', data: approveData }) + ), + /defiApprove transaction must not carry native value/ + ); + await expectMismatch( + verify( + { type: 'defiDeposit', defiParams }, + await buildTx({ to: tokenContract, value: '10', data: depositData }) + ), + /defiDeposit transaction must not carry native value/ + ); + await expectMismatch( + verify( + { type: 'defiWithdraw', defiParams }, + await buildTx({ to: tokenContract, value: '1', data: redeemData }) + ), + /defiWithdraw transaction must not carry native value/ + ); + }); + + it('rejects non-canonical trailing bytes on defiApprove, defiDeposit, and defiWithdraw', async function () { + await expectMismatch( + verify( + { type: 'defiApprove', defiParams }, + await buildTx({ to: tokenContract, data: approveData + '00'.repeat(32) }) + ), + /not canonical/ + ); + await expectMismatch( + verify( + { type: 'defiDeposit', defiParams }, + await buildTx({ to: tokenContract, data: depositData + '00'.repeat(32) }) + ), + /not canonical/ + ); + await expectMismatch( + verify( + { type: 'defiWithdraw', defiParams }, + await buildTx({ to: tokenContract, data: redeemData + '00'.repeat(32) }) + ), + /not canonical/ + ); + }); + }); }); diff --git a/modules/sdk-coin-flr/test/unit/flr.ts b/modules/sdk-coin-flr/test/unit/flr.ts index 602fd28d2be..e8f87ed3100 100644 --- a/modules/sdk-coin-flr/test/unit/flr.ts +++ b/modules/sdk-coin-flr/test/unit/flr.ts @@ -552,12 +552,17 @@ describe('flr', function () { walletPassphrase: 'fakeWalletPassphrase', }; + const txBuilder = tflrCoin.getTransactionBuilder(); + txBuilder.type(TransactionType.SingleSigSend); + txBuilder.fee({ fee: '10', gasLimit: '21000' }); + txBuilder.counter(1); + txBuilder.contract('0x174cfd823af8ce27ed0afee3fcf3c3ba259116be'); + txBuilder.value('1'); const txPrebuild = { - txHex: '0x', + txHex: (await txBuilder.build()).toBroadcastFormat(), coin: 'tflr', walletId: 'fakeWalletId', }; - const verification = {}; const isTransactionVerified = await tflrCoin.verifyTransaction({ diff --git a/modules/sdk-coin-tempo/src/tempo.ts b/modules/sdk-coin-tempo/src/tempo.ts index e714dd687d4..84c702279ea 100644 --- a/modules/sdk-coin-tempo/src/tempo.ts +++ b/modules/sdk-coin-tempo/src/tempo.ts @@ -256,6 +256,12 @@ export class Tempo extends AbstractEthLikeNewCoins { async verifyTransaction(params: VerifyEthTransactionOptions): Promise { const { txParams, txPrebuild } = params; + // `bridgeFunds` is HyperEVM-only. This override never reaches the abstract TSS intent dispatch, + // so without an explicit rejection Tempo would accept the intent with no bridge verification at all. + if (txParams?.type === 'bridgeFunds') { + throw new Error('bridgeFunds is not supported on Tempo'); + } + if (!txPrebuild?.txHex) { return true; } diff --git a/modules/sdk-coin-tempo/test/unit/tempo.ts b/modules/sdk-coin-tempo/test/unit/tempo.ts index 369e1be8269..52da605f834 100644 --- a/modules/sdk-coin-tempo/test/unit/tempo.ts +++ b/modules/sdk-coin-tempo/test/unit/tempo.ts @@ -254,4 +254,14 @@ describe('Tempo Recovery', function () { buildStub.calledOnce.should.equal(true); }); }); + + describe('verifyTransaction — unsupported intents', function () { + it('rejects a bridgeFunds intent instead of accepting it unverified', async function () { + // bridgeFunds is HyperEVM-only and Tempo overrides verifyTransaction, so it never reaches the + // abstract TSS intent dispatch: the intent must be rejected explicitly, with or without txHex. + await basecoin + .verifyTransaction({ txParams: { type: 'bridgeFunds' }, txPrebuild: {} } as never) + .should.be.rejectedWith(/bridgeFunds is not supported on Tempo/); + }); + }); }); diff --git a/modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts b/modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts index 733eaa69182..41a33475c88 100644 --- a/modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts +++ b/modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts @@ -86,6 +86,8 @@ export interface ITransactionRecipient { programId?: string; memo?: string; data?: string; + /** Structured token data Wallet Platform persists on stored intents (authoritative ERC-20/NFT quantity and contract). */ + tokenData?: TokenTransferRecipientParams; } /** @@ -296,6 +298,10 @@ export interface TransactionParams { numberOfSplits?: number; /** Top-level token name for token-scoped intents (e.g. `tokenApproval`, `consolidate`). */ tokenName?: string; + /** Top-level amount for recipient-less intents that persist `intent.amount` (e.g. `bridgeFunds`). */ + intentAmount?: { value: string; symbol: string }; + /** Nonce the caller — or the persisted intent — requires the signed transaction to carry. */ + nonce?: string | number; } export interface AddressVerificationData { diff --git a/modules/sdk-core/src/bitgo/utils/tss/baseTypes.ts b/modules/sdk-core/src/bitgo/utils/tss/baseTypes.ts index 1bdca39d154..5ac5357d67e 100644 --- a/modules/sdk-core/src/bitgo/utils/tss/baseTypes.ts +++ b/modules/sdk-core/src/bitgo/utils/tss/baseTypes.ts @@ -490,7 +490,7 @@ export interface PopulatedIntent extends PopulatedIntentBase, DefiIntentFields { recipients?: IntentRecipient[]; /** Canton split (fanout): number of equal-value holdings the unspents are split into. */ numberOfSplits?: number; - nonce?: string; + nonce?: string | number; token?: string; enableTokens?: TokenEnablement[]; /** diff --git a/modules/sdk-core/src/bitgo/utils/tss/recipientUtils.ts b/modules/sdk-core/src/bitgo/utils/tss/recipientUtils.ts index 1c108b891e1..b48fc3265d3 100644 --- a/modules/sdk-core/src/bitgo/utils/tss/recipientUtils.ts +++ b/modules/sdk-core/src/bitgo/utils/tss/recipientUtils.ts @@ -156,6 +156,9 @@ export function resolveEffectiveTxParams( address: getIntentRecipientAddress(intentRecipient.address), amount: intentRecipient.amount.value, data: intentRecipient.data, + // Carry the structured token data (authoritative tokenQuantity / tokenType / contract) so the + // coin verifier can bind the declared ERC-20 quantity and contract to the signed bytes. + ...(intentRecipient.tokenData && { tokenData: intentRecipient.tokenData }), ...(tokenName && { tokenName }), }; }); @@ -207,6 +210,38 @@ export function resolveEffectiveTxParams( effectiveTxParams.wrapParams = { tokenName: intent.tokenName, amount: intent.amount }; } + // Propagate the persisted top-level amount for `bridgeFunds` only: those intents carry no recipients, + // and pendingApproval re-signing (MPCv1/MPCv2) passes no caller txParams, so the verifier would + // otherwise have nothing to compare the bridge payload's scaled amount against. + if ( + !effectiveTxParams.intentAmount && + effectiveTxParams.type === 'bridgeFunds' && + intent?.intentType === 'bridgeFunds' && + typeof intent.amount === 'object' && + intent.amount !== null && + typeof intent.amount.value === 'string' && + typeof intent.amount.symbol === 'string' + ) { + effectiveTxParams.intentAmount = { value: intent.amount.value, symbol: intent.amount.symbol }; + } + + // Propagate the persisted intent nonce so coin verifiers that require an exact nonce (e.g. the + // EVM `fillNonce` self-send) can check it on stored-request signing paths that carry no txParams. + // Wallet Platform can persist numeric `0`, so handle finite non-negative integer numbers as well + // as non-empty strings without truthiness checks. + if (effectiveTxParams.nonce === undefined && intent?.nonce !== undefined && intent.nonce !== null) { + if (typeof intent.nonce === 'string' && intent.nonce !== '') { + effectiveTxParams.nonce = intent.nonce; + } else if ( + typeof intent.nonce === 'number' && + Number.isFinite(intent.nonce) && + Number.isInteger(intent.nonce) && + intent.nonce >= 0 + ) { + effectiveTxParams.nonce = String(intent.nonce); + } + } + // Propagate the persisted top-level tokenName for `tokenApproval` only: those intents store tokenName // at the intent root with no recipients, and pendingApproval/stored-intent signing carries no caller // txParams. Any other type must not inherit it, or a caller's native payment would be verified as a diff --git a/modules/sdk-core/src/bitgo/wallet/BuildParams.ts b/modules/sdk-core/src/bitgo/wallet/BuildParams.ts index 54ba202ab7d..01cdd5a8733 100644 --- a/modules/sdk-core/src/bitgo/wallet/BuildParams.ts +++ b/modules/sdk-core/src/bitgo/wallet/BuildParams.ts @@ -185,6 +185,9 @@ export const BuildParams = t.exact( wrapParams: t.unknown, // ERC-7984 unwrap (unshield): { tokenName, amount } passthrough to WP unwrapParams: t.unknown, + // Top-level { value, symbol } amount for recipient-less intents (e.g. bridgeFunds). Without this + // key the exact BuildParams codec rejects the intent's declared amount before signing. + intentAmount: t.unknown, // WebAuthn attestation for the withdrawal intent — pass-through only. attestation: AttestationPayload, }), diff --git a/modules/sdk-core/test/unit/bitgo/utils/tss/recipientUtils.ts b/modules/sdk-core/test/unit/bitgo/utils/tss/recipientUtils.ts index e1d7bfba642..df76e263409 100644 --- a/modules/sdk-core/test/unit/bitgo/utils/tss/recipientUtils.ts +++ b/modules/sdk-core/test/unit/bitgo/utils/tss/recipientUtils.ts @@ -248,6 +248,128 @@ describe('recipientUtils', function () { }); }); + describe('stored bridgeFunds amount propagation (CECHO-2690)', function () { + // Production stored-intent shape (45 rows): { intentType: 'bridgeFunds', amount: { symbol, value } }. + const storedBridgeIntent = { + intentType: 'bridgeFunds', + amount: { symbol: 'hypeevm', value: '21000000000000000' }, + } as PopulatedIntent; + + it('derives intentAmount from the intent when txParams is undefined (pendingApproval re-sign path)', function () { + const result = resolveEffectiveTxParams(makeTxRequest({ intent: storedBridgeIntent }), undefined, 'hypeevm'); + assert.strictEqual(result.type, 'bridgeFunds'); + assert.deepStrictEqual(result.intentAmount, { value: '21000000000000000', symbol: 'hypeevm' }); + assert.strictEqual(result.recipients, undefined); + }); + + it('does not overwrite a caller-supplied intentAmount', function () { + const callerAmount = { value: '1', symbol: 'hypeevm' }; + const result = resolveEffectiveTxParams(makeTxRequest({ intent: storedBridgeIntent }), { + intentAmount: callerAmount, + }); + assert.deepStrictEqual(result.intentAmount, callerAmount); + }); + + it('does not attach the stored amount to a caller-declared payment', function () { + const result = resolveEffectiveTxParams(makeTxRequest({ intent: storedBridgeIntent }), { + type: 'transfer', + recipients: [{ address: '0xabc', amount: '1' }], + }); + assert.strictEqual(result.intentAmount, undefined); + }); + + it('ignores a string amount and a non-bridgeFunds intent', function () { + const stringAmount = makeTxRequest({ + intent: { intentType: 'bridgeFunds', amount: '21000000000000000' } as PopulatedIntent, + }); + assert.strictEqual(resolveEffectiveTxParams(stringAmount, {}).intentAmount, undefined); + + const otherIntent = makeTxRequest({ + intent: { + intentType: 'payment', + amount: { value: '21000000000000000', symbol: 'hypeevm' }, + recipients: [{ address: { address: '0xabc' }, amount: { value: '1', symbol: 'hypeevm' } }], + } as PopulatedIntent, + }); + assert.strictEqual(resolveEffectiveTxParams(otherIntent, undefined).intentAmount, undefined); + }); + }); + + describe('stored transferToken tokenData preservation (CECHO-2690)', function () { + // Production ETH/Arbitrum shape: amount.value is the '0' placeholder and tokenData carries the quantity. + const storedTokenIntent = { + intentType: 'transferToken', + recipients: [ + { + address: { address: '0x7e85bdc27c050e3905ebf4b8e634d9ad6edd0de6' }, + amount: { value: '0', symbol: 'usdt' }, + tokenData: { tokenName: 'usdt', tokenQuantity: '1000000', tokenType: 'ERC20' }, + }, + ], + } as unknown as PopulatedIntent; + + it('carries tokenData onto the reconstructed recipient', function () { + const result = resolveEffectiveTxParams(makeTxRequest({ intent: storedTokenIntent }), undefined, 'eth'); + assert.strictEqual(result.type, 'transferToken'); + assert.strictEqual(result.recipients?.[0].amount, '0'); + assert.deepStrictEqual(result.recipients?.[0].tokenData, { + tokenName: 'usdt', + tokenQuantity: '1000000', + tokenType: 'ERC20', + }); + }); + + it('does not invent tokenData when the stored intent has none', function () { + const txRequest = makeTxRequest({ + intent: { + intentType: 'transferToken', + recipients: [{ address: { address: '0xabc' }, amount: { value: '1', symbol: 'eth' } }], + } as unknown as PopulatedIntent, + }); + assert.strictEqual(resolveEffectiveTxParams(txRequest, {}).recipients?.[0].tokenData, undefined); + }); + + it('leaves caller-supplied recipients untouched', function () { + const callerRecipients = [{ address: '0xabc', amount: '5' }]; + const result = resolveEffectiveTxParams(makeTxRequest({ intent: storedTokenIntent }), { + recipients: callerRecipients, + }); + assert.strictEqual(result.recipients, callerRecipients); + }); + }); + + describe('intent nonce propagation (CECHO-2690)', function () { + it('derives nonce from the intent when txParams is undefined', function () { + const txRequest = makeTxRequest({ intent: { intentType: 'fillNonce', nonce: '7' } as PopulatedIntent }); + assert.strictEqual(resolveEffectiveTxParams(txRequest, undefined).nonce, '7'); + }); + + it('does not overwrite a caller-supplied nonce', function () { + const txRequest = makeTxRequest({ intent: { intentType: 'fillNonce', nonce: '7' } as PopulatedIntent }); + assert.strictEqual(resolveEffectiveTxParams(txRequest, { nonce: '9' }).nonce, '9'); + }); + + it('preserves numeric stored nonce including 0', function () { + const zeroNonceReq = makeTxRequest({ intent: { intentType: 'fillNonce', nonce: 0 } as PopulatedIntent }); + assert.strictEqual(resolveEffectiveTxParams(zeroNonceReq, undefined).nonce, '0'); + + const nonZeroNonceReq = makeTxRequest({ intent: { intentType: 'fillNonce', nonce: 42 } as PopulatedIntent }); + assert.strictEqual(resolveEffectiveTxParams(nonZeroNonceReq, undefined).nonce, '42'); + }); + + it('does not overwrite caller-supplied numeric nonce 0', function () { + const txRequest = makeTxRequest({ intent: { intentType: 'fillNonce', nonce: '7' } as PopulatedIntent }); + assert.strictEqual(resolveEffectiveTxParams(txRequest, { nonce: 0 }).nonce, 0); + }); + + it('ignores negative, non-integer, or non-finite numeric stored nonces', function () { + for (const badNonce of [-1, 1.5, NaN, Infinity]) { + const txRequest = makeTxRequest({ intent: { intentType: 'fillNonce', nonce: badNonce } as PopulatedIntent }); + assert.strictEqual(resolveEffectiveTxParams(txRequest, undefined).nonce, undefined); + } + }); + }); + describe('tx-level memo propagation', function () { it('derives memo from the intent when txParams is undefined (pendingApproval re-sign path)', function () { const txRequest = makeTxRequest({