From 54c37a8c4c77bbcc958b3674f838907dcaea5877 Mon Sep 17 00:00:00 2001 From: Ko Date: Tue, 17 Nov 2026 14:46:47 +0800 Subject: [PATCH 1/5] feat(trade): add checks that a remote signer returned the transaction it was sent Adds src/signed-tx-binding.js, which compares the signed bytes a remote signer (Privy, WalletConnect) returns with the transaction the CLI sent it: - Solana: identical message bytes and signature count, the wallet is one of the required signers, and its signature slot verifies (ed25519). - EVM: decode the signed transaction (replay-protected legacy, type 1 or type 2; blob and set-code transactions are refused), recover the sender, and compare it and the given fields with what was sent. A mismatch is a new error code, SIGNED_TX_MISMATCH, which execute treats as terminal. Nothing calls the checks yet; the Privy and WalletConnect changes that use them follow separately. Also adds the shared test helpers they use: honest test signers with fixed keys, and an execute harness. Co-Authored-By: Claude Opus 5.5 --- docs/error-codes.md | 1 + src/__tests__/fixtures/execute-harness.js | 174 +++++++++++++ src/__tests__/fixtures/remote-signers.js | 67 +++++ src/__tests__/signed-tx-binding.test.js | 253 +++++++++++++++++++ src/error-codes.js | 1 + src/signed-tx-binding.js | 287 ++++++++++++++++++++++ src/trading.js | 3 + 7 files changed, 786 insertions(+) create mode 100644 src/__tests__/fixtures/execute-harness.js create mode 100644 src/__tests__/fixtures/remote-signers.js create mode 100644 src/__tests__/signed-tx-binding.test.js create mode 100644 src/signed-tx-binding.js diff --git a/docs/error-codes.md b/docs/error-codes.md index 4339f967..871d5b83 100644 --- a/docs/error-codes.md +++ b/docs/error-codes.md @@ -168,6 +168,7 @@ A connection failure is `NETWORK_ERROR` and never `UNAUTHORIZED`: the CLI could | `BROADCAST_FAILED` | The transaction could not be broadcast. | No | | `TX_REVERTED` | The transaction reverted or failed on chain. | No | | `TXHASH_MISMATCH` | The RPC returned a different transaction hash than the one signed. | No | +| `SIGNED_TX_MISMATCH` | The remote signer (Privy or WalletConnect) returned a transaction that differs from the one checked; the CLI did not broadcast it. | No | | `RECEIPT_TIMEOUT` | The transaction was not confirmed in time and may still land. Check the transaction before retrying. | No | | `OUTCOME_VERIFICATION_FAILED` | The CLI could not verify the trade outcome. | No | | `SWAP_OUTCOME_MISMATCH` | The simulated swap outcome does not match the quote; nothing was signed. | No | diff --git a/src/__tests__/fixtures/execute-harness.js b/src/__tests__/fixtures/execute-harness.js new file mode 100644 index 00000000..8096a6d8 --- /dev/null +++ b/src/__tests__/fixtures/execute-harness.js @@ -0,0 +1,174 @@ +/** + * Harness for `trade execute` tests with a remote signer (Privy or + * WalletConnect): quote builders, a stub for every network call that records + * what reaches the execute endpoint, and an `execute()` that returns the logs + * and the error instead of throwing. + */ +import { beforeEach, afterEach, vi } from 'vitest'; +import fs from 'fs'; +import path from 'path'; +import os from 'os'; + +import { saveQuote as saveQuoteRaw, buildTradingCommands, evmTxHash } from '../../trading.js'; +import { SIMULATION_RPCS } from '../../rpc-urls.js'; +import { base58Decode, base58Encode } from '../../wallet.js'; + +export const BASE_ETH = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'; +export const BASE_USDC = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'; +export const OUT_TOKEN = '0x4200000000000000000000000000000000000006'; +export const LIFI_ROUTER = '0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae'; +export const ATTACKER = '0x000000000000000000000000000000000000dead'; +export const SOL_MINT = 'So11111111111111111111111111111111111111112'; +export const SOL_USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; +export const APPROVE_SELECTOR = '0x095ea7b3'; + +/** Calldata approving an unlimited amount to ATTACKER. */ +export const UNLIMITED_APPROVAL_TO_ATTACKER = APPROVE_SELECTOR + ATTACKER.slice(2).padStart(64, '0') + 'f'.repeat(64); + +const screenApi = { + baseUrl: 'https://api.nansen.ai', + selection: { kind: 'anonymous' }, + requestCredentials: async () => ({}), + request: async (endpoint, body) => { + if (endpoint.startsWith('/api/v1/sanctions/screen')) { + return { results: (body?.addresses || []).map(address => ({ address, sanctioned: false })) }; + } + throw new Error(`unexpected endpoint ${endpoint}`); + }, +}; + +export function saveQuote(resp, ...rest) { + return saveQuoteRaw({ ...resp, metadata: { quoteId: 'backend-quote-id' } }, ...rest); +} + +export function evmIntent(walletAddress, { fromToken = BASE_ETH, toToken = BASE_USDC, amount = '1000000000000000000' } = {}) { + return { + chain: 'base', toChain: null, walletAddress, recipient: null, + fromToken, toToken, swapMode: 'exactIn', amount, maxInputAmount: amount, + }; +} + +export function solIntent(walletAddress) { + return { + chain: 'solana', toChain: null, walletAddress, recipient: null, + fromToken: SOL_MINT, toToken: SOL_USDC, swapMode: 'exactIn', amount: '1000000000', maxInputAmount: '1000000000', + }; +} + +export const nativeSwapQuote = () => ({ + success: true, + quotes: [{ + aggregator: 'lifi', inputMint: BASE_ETH, outputMint: BASE_USDC, + inAmount: '1000000000000000000', outAmount: '3000000000', + transaction: { to: LIFI_ROUTER, data: '0x12345678', value: '1000000000000000000', gas: '210000', maxFeePerGas: '6600000', maxPriorityFeePerGas: '1100000' }, + }], +}); + +export const erc20SwapQuote = () => ({ + success: true, + quotes: [{ + aggregator: 'lifi', inputMint: BASE_USDC, outputMint: OUT_TOKEN, + inAmount: '1000000', outAmount: '990000', inputAmount: '1000000', + approvalAddress: LIFI_ROUTER, + transaction: { to: LIFI_ROUTER, data: '0x12345678', value: '0', gas: '210000', maxFeePerGas: '1000000', maxPriorityFeePerGas: '1000000' }, + }], +}); + +/** Unsigned one-signer Solana transaction; fee payer = wallet. */ +export function unsignedSolanaTx(walletAddress, blockhashByte = 3) { + const message = Buffer.concat([ + Buffer.from([1, 0, 1, 2]), + base58Decode(walletAddress), + Buffer.alloc(32, 2), + Buffer.alloc(32, blockhashByte), + Buffer.from([1, 1, 1, 0, 1, 0]), + ]); + return Buffer.concat([Buffer.from([1]), Buffer.alloc(64), message]).toString('base64'); +} + +export const solanaQuote = (tx) => ({ + success: true, + quotes: [{ aggregator: 'jupiter', inputMint: SOL_MINT, outputMint: SOL_USDC, inAmount: '1000000000', outAmount: '50000000', transaction: tx }], +}); + +/** + * Register beforeEach/afterEach hooks that give each test its own HOME, the + * legacy execute route, test Privy credentials and no simulation RPCs. + */ +export function useExecuteEnv() { + let tempDir; let originalHome; let origSim; + beforeEach(() => { + originalHome = process.env.HOME; + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nansen-remote-signer-')); + process.env.HOME = tempDir; + process.env.NANSEN_TRADING_EXECUTION_ROUTE = 'legacy'; + process.env.PRIVY_APP_ID = 'test-app-id'; + process.env.PRIVY_APP_SECRET = 'test-secret'; + delete process.env.NANSEN_WALLET_PASSWORD; + origSim = { solana: SIMULATION_RPCS.solana, base: SIMULATION_RPCS.base }; + SIMULATION_RPCS.solana = null; + SIMULATION_RPCS.base = null; + }); + afterEach(() => { + process.env.HOME = originalHome; + fs.rmSync(tempDir, { recursive: true, force: true }); + delete process.env.NANSEN_TRADING_EXECUTION_ROUTE; + delete process.env.PRIVY_APP_ID; + delete process.env.PRIVY_APP_SECRET; + SIMULATION_RPCS.solana = origSim.solana; + SIMULATION_RPCS.base = origSim.base; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); +} + +/** + * Stub every network call. `privySign(body)` answers Privy's sign request; + * every POST to the execute endpoint is recorded in the returned array. + */ +export function stubNetwork({ privyAddress, privySign } = {}) { + const executeBodies = []; + let allowance = 0n; + vi.stubGlobal('fetch', vi.fn().mockImplementation((url, opts) => { + const u = String(url); + let body = {}; + try { body = typeof opts?.body === 'string' ? JSON.parse(opts.body) : {}; } catch { /* not JSON */ } + if (u.includes('privy.io') && opts?.method === 'GET') { + return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'w', address: privyAddress }) }); + } + if (u.includes('privy.io') && opts?.method === 'POST') { + return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: { signed_transaction: privySign(body) } }) }); + } + if (u.includes('trading-api')) { + executeBodies.push(body); + const signed = String(body.signedTransaction); + if (signed.startsWith('0x')) { + // An approval that lands raises the allowance the CLI re-reads. + if (body.signedTransaction && executeBodies.length === 1 && signed.includes(APPROVE_SELECTOR.slice(2))) allowance = 10n ** 30n; + return Promise.resolve({ ok: true, text: () => Promise.resolve(JSON.stringify({ status: 'Success', txHash: evmTxHash(signed), chainType: 'evm', broadcaster: 't' })) }); + } + const sig = base58Encode(Buffer.from(signed, 'base64').subarray(1, 65)); + return Promise.resolve({ ok: true, text: () => Promise.resolve(JSON.stringify({ status: 'Success', signature: sig, chainType: 'solana', broadcaster: 't' })) }); + } + const r = (result) => Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve(JSON.stringify({ jsonrpc: '2.0', id: body.id, result })), json: () => Promise.resolve({ jsonrpc: '2.0', id: body.id, result }) }); + switch (body.method) { + case 'eth_getTransactionCount': return r('0x5'); + case 'eth_getCode': return r('0x6080604052'); + case 'eth_call': return r('0x' + allowance.toString(16).padStart(64, '0')); + case 'eth_getTransactionReceipt': return r({ status: '0x1', blockNumber: '0x100' }); + case 'getSignatureStatuses': return r({ context: { slot: 1 }, value: [{ slot: 1, confirmations: 1, err: null, confirmationStatus: 'confirmed' }] }); + case 'getBalance': return r({ context: { slot: 1 }, value: 10_000_000_000 }); + default: return r(null); + } + })); + return executeBodies; +} + +/** Run `trade execute --quote `; returns the logs and the error, if any. */ +export async function execute(quoteId) { + const logs = []; + const cmds = buildTradingCommands({ log: (m) => logs.push(m), exit: () => {} }); + let err = null; + try { await cmds.execute([], screenApi, {}, { quote: quoteId }); } catch (e) { err = e; } + return { logs, err }; +} diff --git a/src/__tests__/fixtures/remote-signers.js b/src/__tests__/fixtures/remote-signers.js new file mode 100644 index 00000000..f3a4dceb --- /dev/null +++ b/src/__tests__/fixtures/remote-signers.js @@ -0,0 +1,67 @@ +/** + * Test stand-ins for the remote signers (Privy, WalletConnect). + * + * The CLI checks that a remote signer hands back exactly the transaction it was + * sent, signed by the expected wallet, so a stub can no longer answer with + * placeholder bytes. These helpers sign what the stub received with fixed test + * keys, the way a real signer would. + */ +import { secp256k1 } from '@noble/curves/secp256k1.js'; +import { ed25519 } from '@noble/curves/ed25519.js'; +import { signEip1559Transaction, signSolanaTransaction } from '../../trading.js'; +import { keccak256, toChecksumAddress } from '../../crypto.js'; +import { base58Encode } from '../../wallet.js'; +import { parseTransactionMessage, readCompactU16 } from '../../solana-tx.js'; + +export const TEST_EVM_KEY = '11'.repeat(32); +export const TEST_EVM_ADDRESS = toChecksumAddress( + keccak256(Buffer.from(secp256k1.getPublicKey(Buffer.from(TEST_EVM_KEY, 'hex'), false)).subarray(1)).subarray(12).toString('hex'), +); + +const SOL_SEED = Buffer.alloc(32, 0x22); +const SOL_PUB = Buffer.from(ed25519.getPublicKey(SOL_SEED)); +/** 64-byte seed||pubkey hex, the form signSolanaTransaction takes. */ +export const TEST_SOL_KEY = Buffer.concat([SOL_SEED, SOL_PUB]).toString('hex'); +export const TEST_SOL_ADDRESS = base58Encode(SOL_PUB); +export const TEST_SOL_PUBKEY_BYTES = SOL_PUB; + +/** Sign the transaction a Privy `eth_signTransaction` request body carries. */ +export function privySignedEvm(privyBody, key = TEST_EVM_KEY) { + const t = privyBody.params.transaction; + return signEip1559Transaction({ + chainId: t.chain_id, + nonce: t.nonce, + maxPriorityFeePerGas: t.max_priority_fee_per_gas, + maxFeePerGas: t.max_fee_per_gas, + gasLimit: t.gas_limit, + to: t.to, + value: t.value, + data: t.data, + }, key); +} + +/** + * Sign the transaction a Privy Solana `signTransaction` request body carries, + * in the slot of the key's own account (not always slot 0: an x402 payment has + * the facilitator as fee payer), as Privy does. + */ +export function privySignedSolana(privyBody, key = TEST_SOL_KEY) { + return signSolanaSlot(privyBody.params.transaction, key); +} + +export function signSolanaSlot(txBase64, key = TEST_SOL_KEY) { + const bytes = Buffer.from(txBase64, 'base64'); + const { value: sigCount, size } = readCompactU16(bytes, 0); + const message = bytes.subarray(size + 64 * sigCount); + const signer = base58Encode(Buffer.from(key, 'hex').subarray(32)); + const index = Math.max(0, parseTransactionMessage(txBase64).staticAccountKeys.indexOf(signer)); + const single = Buffer.concat([Buffer.from([1]), Buffer.alloc(64), message]).toString('base64'); + const signature = Buffer.from(signSolanaTransaction(single, key), 'base64').subarray(1, 65); + signature.copy(bytes, size + 64 * index); + return bytes.toString('base64'); +} + +/** The fee payer's signature (the transaction id) in signed base64 bytes. */ +export function solanaSigOf(signedTxBase64) { + return base58Encode(Buffer.from(signedTxBase64, 'base64').subarray(1, 65)); +} diff --git a/src/__tests__/signed-tx-binding.test.js b/src/__tests__/signed-tx-binding.test.js new file mode 100644 index 00000000..f5093021 --- /dev/null +++ b/src/__tests__/signed-tx-binding.test.js @@ -0,0 +1,253 @@ +import { describe, it, expect } from 'vitest'; +import { RLP } from '@ethereumjs/rlp'; +import { + assertSolanaSignedMatches, + assertEvmSignedMatches, + decodeSignedEvmTransaction, +} from '../signed-tx-binding.js'; +import { + signEip1559Transaction, + signLegacyTransaction, + signSolanaTransaction, + toBuffer, +} from '../trading.js'; +import { keccak256, rlpEncode, signSecp256k1 } from '../crypto.js'; +import { base58Decode, generateEvmWallet, generateSolanaWallet } from '../wallet.js'; + +// ============= EVM ============= + +const ROUTER = '0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae'; +const OTHER = '0x000000000000000000000000000000000000dead'; + +const wallet = generateEvmWallet(); +const stranger = generateEvmWallet(); + +const SENT = { + chainId: 8453, + nonce: '0x5', + gasLimit: '0x3d090', + maxFeePerGas: '0x64b540', + maxPriorityFeePerGas: '0x10c8e0', + to: ROUTER, + value: '0x2386f26fc10000', + data: '0x4630a0d8' + 'ab'.repeat(40), +}; + +// Every field Privy is sent, in the shape signEip1559Transaction takes. +const sign1559 = (overrides = {}, key = wallet.privateKey) => signEip1559Transaction({ ...SENT, ...overrides }, key); +const FULL_EXPECTED = { ...SENT, type: 2, accessList: [] }; + +describe('decodeSignedEvmTransaction', () => { + it('decodes a type-2 transaction and recovers the signer', () => { + const tx = decodeSignedEvmTransaction(sign1559()); + expect(tx).toMatchObject({ + type: 2, + chainId: 8453n, + nonce: 5n, + gasLimit: 250000n, + maxFeePerGas: 6600000n, + maxPriorityFeePerGas: 1100000n, + to: ROUTER, + value: 10000000000000000n, + data: SENT.data, + accessList: [], + from: wallet.address.toLowerCase(), + }); + }); + + it('decodes an EIP-155 legacy transaction, chain id from v', () => { + const signed = signLegacyTransaction({ + nonce: '0x7', gasPrice: '0x3b9aca00', gasLimit: '0x5208', to: ROUTER, value: '0x1', data: '0x', chainId: 8453, + }, wallet.privateKey); + expect(decodeSignedEvmTransaction(signed)).toMatchObject({ + type: 0, chainId: 8453n, nonce: 7n, gasPrice: 1000000000n, to: ROUTER, value: 1n, data: '0x', + from: wallet.address.toLowerCase(), + }); + }); + + it('decodes a type-1 transaction', () => { + const fields = [toBuffer(8453), toBuffer(1), toBuffer(1000), toBuffer(21000), toBuffer(ROUTER), toBuffer(5), toBuffer('0x'), []]; + const payload = Buffer.concat([Buffer.from([1]), rlpEncode(fields)]); + const { r, s, v } = signSecp256k1(keccak256(payload), Buffer.from(wallet.privateKey, 'hex')); + const strip = (b) => { let i = 0; while (i < b.length && b[i] === 0) i++; return b.subarray(i); }; + const signed = '0x' + Buffer.concat([Buffer.from([1]), rlpEncode([...fields, toBuffer(v), strip(r), strip(s)])]).toString('hex'); + expect(decodeSignedEvmTransaction(signed)).toMatchObject({ + type: 1, chainId: 8453n, nonce: 1n, gasPrice: 1000n, gasLimit: 21000n, value: 5n, from: wallet.address.toLowerCase(), + }); + }); + + it('refuses a legacy transaction without EIP-155 replay protection', () => { + // v = 27: valid pre-EIP-155 shape, signable on any chain. + const raw = RLP.encode([new Uint8Array([1]), new Uint8Array([1]), new Uint8Array([0x52, 0x08]), toBuffer(ROUTER), new Uint8Array(), new Uint8Array(), new Uint8Array([27]), new Uint8Array(32).fill(1), new Uint8Array(32).fill(1)]); + expect(() => decodeSignedEvmTransaction('0x' + Buffer.from(raw).toString('hex'))).toThrow(/no EIP-155 chain id/); + }); + + it('refuses EIP-7702 set-code and blob transactions', () => { + expect(() => decodeSignedEvmTransaction('0x04' + Buffer.from(RLP.encode([])).toString('hex'))).toThrow(/unsupported transaction type 0x04/); + expect(() => decodeSignedEvmTransaction('0x03' + Buffer.from(RLP.encode([])).toString('hex'))).toThrow(/unsupported transaction type 0x03/); + }); + + it('refuses malformed bytes', () => { + expect(() => decodeSignedEvmTransaction('0xdeadbeef01')).toThrow(); + expect(() => decodeSignedEvmTransaction('0xnothex')).toThrow(/not 0x-prefixed hex/); + expect(() => decodeSignedEvmTransaction(undefined)).toThrow(/not 0x-prefixed hex/); + // A valid type-2 envelope with trailing junk. + expect(() => decodeSignedEvmTransaction(sign1559() + '00')).toThrow(); + }); +}); + +describe('assertEvmSignedMatches', () => { + it('accepts the transaction that was sent, signed by the wallet', () => { + expect(() => assertEvmSignedMatches(sign1559(), FULL_EXPECTED, { from: wallet.address })).not.toThrow(); + }); + + it('accepts decimal-string and bigint forms of the expected values', () => { + expect(() => assertEvmSignedMatches(sign1559(), { + ...FULL_EXPECTED, value: '10000000000000000', nonce: 5n, chainId: '8453', + }, { from: wallet.address })).not.toThrow(); + }); + + it.each([ + ['to', { to: OTHER }, /to is 0x0+dead/], + ['data', { data: '0xa9059cbb' }, /data differs/], + ['value', { value: '0x1' }, /value is 1, expected 10000000000000000/], + ['chainId', { chainId: 1 }, /chainId is 1, expected 8453/], + ['nonce', { nonce: '0x6' }, /nonce is 6, expected 5/], + ['gasLimit', { gasLimit: '0x3d091' }, /gasLimit is 250001/], + ['maxFeePerGas', { maxFeePerGas: '0x64b541' }, /maxFeePerGas is 6600001/], + ['maxPriorityFeePerGas', { maxPriorityFeePerGas: '0x10c8df' }, /maxPriorityFeePerGas is 1099999/], + ])('refuses a changed %s', (_name, change, message) => { + expect(() => assertEvmSignedMatches(sign1559(change), FULL_EXPECTED, { from: wallet.address, label: 'swap transaction' })) + .toThrow(expect.objectContaining({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(message) })); + }); + + it('refuses the right transaction signed by another key', () => { + expect(() => assertEvmSignedMatches(sign1559({}, stranger.privateKey), FULL_EXPECTED, { from: wallet.address })) + .toThrow(expect.objectContaining({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/signed by 0x/) })); + }); + + it('refuses a different envelope type when the type is pinned', () => { + const legacy = signLegacyTransaction({ nonce: '0x5', gasPrice: '0x64b540', gasLimit: '0x3d090', to: ROUTER, value: SENT.value, data: SENT.data, chainId: 8453 }, wallet.privateKey); + expect(() => assertEvmSignedMatches(legacy, { to: ROUTER, value: SENT.value, data: SENT.data, chainId: 8453, type: 2 }, { from: wallet.address })) + .toThrow(expect.objectContaining({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/type is 0, expected 2/) })); + }); + + it('only compares the fields it is given (a wallet may choose nonce, gas and fees)', () => { + const walletChosen = sign1559({ nonce: '0x63', gasLimit: '0x7a120', maxFeePerGas: '0x1', maxPriorityFeePerGas: '0x1' }); + expect(() => assertEvmSignedMatches(walletChosen, { to: ROUTER, value: SENT.value, data: SENT.data, chainId: 8453 }, { from: wallet.address })) + .not.toThrow(); + }); + + it('treats a missing data field as empty calldata', () => { + const transfer = sign1559({ data: '0x' }); + expect(() => assertEvmSignedMatches(transfer, { to: ROUTER, value: SENT.value, chainId: 8453 }, { from: wallet.address })).not.toThrow(); + expect(() => assertEvmSignedMatches(transfer, { to: ROUTER, value: SENT.value, chainId: 8453, data: '0x12' }, { from: wallet.address })) + .toThrow(/data differs/); + }); + + it('refuses bytes that do not decode, saying nothing was broadcast', () => { + expect(() => assertEvmSignedMatches('0xdeadbeef01', FULL_EXPECTED, { from: wallet.address, label: 'approval transaction' })) + .toThrow(expect.objectContaining({ + code: 'SIGNED_TX_MISMATCH', + message: expect.stringMatching(/Refusing to broadcast the approval transaction: .*do not decode.*Nothing was broadcast\./), + })); + }); + + it('uses the caller note in place of the default', () => { + expect(() => assertEvmSignedMatches(sign1559({ to: OTHER }), FULL_EXPECTED, { from: wallet.address, note: 'The wallet may still have sent it.' })) + .toThrow(/The wallet may still have sent it\.$/); + }); + + it('requires the expected signer and the core fields', () => { + expect(() => assertEvmSignedMatches(sign1559(), FULL_EXPECTED, {})).toThrow(/expected signer .* is required/); + expect(() => assertEvmSignedMatches(sign1559(), { to: ROUTER, value: '0x0' }, { from: wallet.address })).toThrow(/expected.chainId is required/); + }); +}); + +// ============= Solana ============= + +const solWallet = generateSolanaWallet(); +const solOther = generateSolanaWallet(); + +// [sigCount][sigs][message]; message header + keys + blockhash + one instruction. +function unsignedTx(signerKeys, { requiredSigs = signerKeys.length, blockhash = 3, version0 = false } = {}) { + const keys = signerKeys.map(k => base58Decode(k)); + const body = Buffer.concat([ + Buffer.from([requiredSigs, 0, 1, keys.length + 1]), + ...keys, + Buffer.alloc(32, 2), + Buffer.alloc(32, blockhash), + Buffer.from([1, keys.length, 1, 0, 1, 0]), + ]); + const message = version0 ? Buffer.concat([Buffer.from([0x80]), body, Buffer.from([0])]) : body; + return Buffer.concat([Buffer.from([requiredSigs]), Buffer.alloc(64 * requiredSigs), message]).toString('base64'); +} + +// Sign slot `index` of a (possibly multi-signer) transaction. +function signSlot(txBase64, privateKeyHex, index) { + const bytes = Buffer.from(txBase64, 'base64'); + const sigCount = bytes[0]; + const message = bytes.subarray(1 + 64 * sigCount); + const oneSig = Buffer.from(signSolanaTransaction(Buffer.concat([Buffer.from([1]), Buffer.alloc(64), message]).toString('base64'), privateKeyHex), 'base64').subarray(1, 65); + oneSig.copy(bytes, 1 + 64 * index); + return bytes.toString('base64'); +} + +describe('assertSolanaSignedMatches', () => { + it('accepts the same message signed by the wallet (legacy and v0)', () => { + for (const version0 of [false, true]) { + const tx = unsignedTx([solWallet.address], { version0 }); + expect(() => assertSolanaSignedMatches(tx, signSolanaTransaction(tx, solWallet.privateKey), { signer: solWallet.address })).not.toThrow(); + } + }); + + it('refuses a different message, even one the wallet validly signed', () => { + const tx = unsignedTx([solWallet.address]); + const substituted = signSolanaTransaction(unsignedTx([solWallet.address], { blockhash: 9 }), solWallet.privateKey); + expect(() => assertSolanaSignedMatches(tx, substituted, { signer: solWallet.address, label: 'swap transaction' })) + .toThrow(expect.objectContaining({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/swap transaction: .*message bytes differ.*Nothing was broadcast/) })); + }); + + it('refuses a changed signature count', () => { + const tx = unsignedTx([solWallet.address]); + const signed = Buffer.from(signSolanaTransaction(tx, solWallet.privateKey), 'base64'); + const twoSigs = Buffer.concat([Buffer.from([2]), signed.subarray(1, 65), Buffer.alloc(64), signed.subarray(65)]).toString('base64'); + expect(() => assertSolanaSignedMatches(tx, twoSigs, { signer: solWallet.address })).toThrow(/signature count 2, expected 1/); + }); + + it('refuses an unsigned or invalidly signed wallet slot', () => { + const tx = unsignedTx([solWallet.address]); + expect(() => assertSolanaSignedMatches(tx, tx, { signer: solWallet.address })).toThrow(/no valid signature from/); + const junk = Buffer.from(tx, 'base64'); + junk.fill(7, 1, 65); + expect(() => assertSolanaSignedMatches(tx, junk.toString('base64'), { signer: solWallet.address })).toThrow(/no valid signature from/); + }); + + it('refuses a signature from another required signer while the wallet slot is empty', () => { + const tx = unsignedTx([solOther.address, solWallet.address]); + const onlyOther = signSlot(tx, solOther.privateKey, 0); + expect(() => assertSolanaSignedMatches(tx, onlyOther, { signer: solWallet.address })).toThrow(/no valid signature from/); + }); + + it('accepts the wallet signing slot 1 while another signer (an x402 fee payer) has not signed yet', () => { + const tx = unsignedTx([solOther.address, solWallet.address]); + expect(() => assertSolanaSignedMatches(tx, signSlot(tx, solWallet.privateKey, 1), { signer: solWallet.address })).not.toThrow(); + }); + + it('refuses when the wallet is not a required signer', () => { + const tx = unsignedTx([solOther.address]); + expect(() => assertSolanaSignedMatches(tx, signSolanaTransaction(tx, solOther.privateKey), { signer: solWallet.address })) + .toThrow(/is not a required signer/); + }); + + it('refuses missing or unparseable returned bytes', () => { + const tx = unsignedTx([solWallet.address]); + expect(() => assertSolanaSignedMatches(tx, undefined, { signer: solWallet.address })).toThrow(/no signed transaction/); + expect(() => assertSolanaSignedMatches(tx, Buffer.from([5]).toString('base64'), { signer: solWallet.address })).toThrow(/do not parse/); + }); + + it('requires the expected signer', () => { + const tx = unsignedTx([solWallet.address]); + expect(() => assertSolanaSignedMatches(tx, tx, {})).toThrow(/expected signer .* is required/); + }); +}); diff --git a/src/error-codes.js b/src/error-codes.js index 2b37a3c4..d1b42436 100644 --- a/src/error-codes.js +++ b/src/error-codes.js @@ -149,6 +149,7 @@ export const ERROR_CODES = { BROADCAST_FAILED: { group: 'trade', description: 'The transaction could not be broadcast.' }, TX_REVERTED: { group: 'trade', description: 'The transaction reverted or failed on chain.' }, TXHASH_MISMATCH: { group: 'trade', description: 'The RPC returned a different transaction hash than the one signed.' }, + SIGNED_TX_MISMATCH: { group: 'trade', description: 'The remote signer (Privy or WalletConnect) returned a transaction that differs from the one checked; the CLI did not broadcast it.' }, RECEIPT_TIMEOUT: { group: 'trade', description: 'The transaction was not confirmed in time and may still land. Check the transaction before retrying.' }, OUTCOME_VERIFICATION_FAILED: { group: 'trade', description: 'The CLI could not verify the trade outcome.' }, SWAP_OUTCOME_MISMATCH: { group: 'trade', description: 'The simulated swap outcome does not match the quote; nothing was signed.' }, diff --git a/src/signed-tx-binding.js b/src/signed-tx-binding.js new file mode 100644 index 00000000..c0de6d41 --- /dev/null +++ b/src/signed-tx-binding.js @@ -0,0 +1,287 @@ +/** + * Nansen CLI - Signed-transaction binding for remote signers. + * + * Privy and WalletConnect sign transactions outside this process. Every + * pre-sign check (target, intent binding, value, fee cap, simulation) runs on + * the transaction the CLI sent for signing, so the bytes a remote signer hands + * back must encode exactly that transaction before anything is broadcast. + * These checks compare the returned bytes with what was sent and confirm the + * expected wallet produced the signature. Any difference throws + * SIGNED_TX_MISMATCH. + */ + +import { RLP } from '@ethereumjs/rlp'; +import { secp256k1 } from '@noble/curves/secp256k1.js'; +import { ed25519 } from '@noble/curves/ed25519.js'; +import { CommandError } from './api.js'; +import { keccak256, bigIntToMinBuf } from './crypto.js'; +import { readCompactU16, parseTransactionMessage } from './solana-tx.js'; +import { base58Decode } from './wallet.js'; + +const DEFAULT_NOTE = 'Nothing was broadcast.'; + +function mismatch(label, detail, note = DEFAULT_NOTE) { + return new CommandError( + `Refusing to broadcast the ${label}: the signer returned a transaction that does not match the one this CLI checked (${detail}). ${note}`, + 'SIGNED_TX_MISMATCH', + ); +} + +// ============= Solana ============= + +function splitSolanaTx(bytes) { + const { value: sigCount, size } = readCompactU16(bytes, 0); + const messageStart = size + sigCount * 64; + if (bytes.length <= messageStart) throw new Error('transaction is too short'); + return { sigCount, sigStart: size, message: bytes.subarray(messageStart) }; +} + +// A malformed key or signature makes verify throw; treat it as not signed. +function verifyEd25519(signature, message, signer) { + try { + return ed25519.verify(signature, message, base58Decode(signer)); + } catch { + return false; + } +} + +/** + * Assert a signed Solana transaction carries exactly the message of the + * unsigned transaction it was produced from, signed by `signer`. + * + * Only the signer's own slot is checked: other required signers (an x402 + * facilitator paying the fee, for example) may still be unsigned. + * + * @param {string} unsignedTxBase64 - the transaction sent to the signer + * @param {string} signedTxBase64 - the transaction the signer returned + * @param {object} opts + * @param {string} opts.signer - base58 public key that must have signed + * @param {string} [opts.label] - what the transaction is, for the error + * @param {string} [opts.note] - sentence appended to the error + */ +export function assertSolanaSignedMatches(unsignedTxBase64, signedTxBase64, { signer, label = 'Solana transaction', note } = {}) { + if (!signer) throw new Error(`assertSolanaSignedMatches: the expected signer of the ${label} is required`); + if (typeof signedTxBase64 !== 'string' || signedTxBase64.length === 0) { + throw mismatch(label, 'no signed transaction', note); + } + + const parsed = parseTransactionMessage(unsignedTxBase64); + const unsigned = splitSolanaTx(Buffer.from(unsignedTxBase64, 'base64')); + let signed; + try { + signed = splitSolanaTx(Buffer.from(signedTxBase64, 'base64')); + } catch (err) { + throw mismatch(label, `the returned bytes do not parse: ${err.message}`, note); + } + + if (signed.sigCount !== unsigned.sigCount) { + throw mismatch(label, `signature count ${signed.sigCount}, expected ${unsigned.sigCount}`, note); + } + if (!signed.message.equals(unsigned.message)) { + throw mismatch(label, 'the message bytes differ', note); + } + + const index = parsed.staticAccountKeys.indexOf(signer); + if (index < 0 || index >= parsed.header.numRequiredSignatures || index >= signed.sigCount) { + throw mismatch(label, `${signer} is not a required signer of the transaction`, note); + } + + const signedBytes = Buffer.from(signedTxBase64, 'base64'); + const sigOffset = signed.sigStart + index * 64; + const signature = signedBytes.subarray(sigOffset, sigOffset + 64); + if (!verifyEd25519(signature, signed.message, signer)) { + throw mismatch(label, `no valid signature from ${signer}`, note); + } +} + +// ============= EVM ============= + +const TX_TYPE_LEGACY = 0; +const TX_TYPE_ACCESS_LIST = 1; +const TX_TYPE_EIP1559 = 2; + +function toHex(bytes) { + return '0x' + Buffer.from(bytes).toString('hex'); +} + +function asBytes(field, name) { + if (!(field instanceof Uint8Array)) throw new Error(`${name} is not a byte string`); + return field; +} + +// RLP integers are minimal big-endian: a leading zero byte is non-canonical. +function asUint(field, name) { + const bytes = asBytes(field, name); + if (bytes.length > 0 && bytes[0] === 0) throw new Error(`${name} has a leading zero`); + return bytes.length === 0 ? 0n : BigInt(toHex(bytes)); +} + +function asAddress(field, name) { + const bytes = asBytes(field, name); + if (bytes.length !== 20) throw new Error(`${name} is not a 20-byte address`); + return toHex(bytes); +} + +function asAccessList(field) { + if (!Array.isArray(field)) throw new Error('accessList is not a list'); + return field; +} + +function recoverSender(payload, yParity, r, s) { + if (yParity !== 0n && yParity !== 1n) throw new Error(`invalid signature recovery bit ${yParity}`); + const sig = new secp256k1.Signature(r, s).addRecoveryBit(Number(yParity)); + const pub = sig.recoverPublicKey(keccak256(payload)).toBytes(false); + return toHex(keccak256(Buffer.from(pub).subarray(1)).subarray(12)); +} + +/** + * Decode a signed EVM transaction and recover its sender. + * + * Accepts legacy transactions with EIP-155 replay protection, type 1 and + * type 2. Pre-EIP-155 legacy transactions (no chain id) and every other + * type, including EIP-7702 set-code transactions, are refused. + * + * @param {string} signedTxHex - 0x-prefixed hex of the signed transaction + * @returns {{ type, chainId, nonce, gasLimit, gasPrice?, maxFeePerGas?, maxPriorityFeePerGas?, to, value, data, accessList, from }} + */ +export function decodeSignedEvmTransaction(signedTxHex) { + if (typeof signedTxHex !== 'string' || !/^0x([0-9a-fA-F]{2})+$/.test(signedTxHex)) { + throw new Error('signed transaction is not 0x-prefixed hex'); + } + const raw = Buffer.from(signedTxHex.slice(2), 'hex'); + const first = raw[0]; + + if (first >= 0xc0) { + const fields = RLP.decode(raw); + if (!Array.isArray(fields) || fields.length !== 9) throw new Error('legacy transaction must have 9 fields'); + const [nonce, gasPrice, gasLimit, to, value, data, v, r, s] = fields; + const vNum = asUint(v, 'v'); + if (vNum < 35n) throw new Error('legacy transaction has no EIP-155 chain id'); + const chainId = (vNum - 35n) / 2n; + const yParity = (vNum - 35n) % 2n; + // EIP-155 signing payload: the six fields, then chainId, 0, 0. + const payload = Buffer.from(RLP.encode([...fields.slice(0, 6), bigIntToMinBuf(chainId), new Uint8Array(), new Uint8Array()])); + return { + type: TX_TYPE_LEGACY, + chainId, + nonce: asUint(nonce, 'nonce'), + gasPrice: asUint(gasPrice, 'gasPrice'), + gasLimit: asUint(gasLimit, 'gasLimit'), + to: asAddress(to, 'to'), + value: asUint(value, 'value'), + data: toHex(asBytes(data, 'data')), + accessList: [], + from: recoverSender(payload, yParity, asUint(r, 'r'), asUint(s, 's')), + }; + } + + if (first === TX_TYPE_ACCESS_LIST || first === TX_TYPE_EIP1559) { + const fields = RLP.decode(raw.subarray(1)); + const isEip1559 = first === TX_TYPE_EIP1559; + const expectedLength = isEip1559 ? 12 : 11; + if (!Array.isArray(fields) || fields.length !== expectedLength) { + throw new Error(`type ${first} transaction must have ${expectedLength} fields`); + } + const unsignedCount = expectedLength - 3; + const payload = Buffer.concat([Buffer.from([first]), Buffer.from(RLP.encode(fields.slice(0, unsignedCount)))]); + const [yParity, r, s] = fields.slice(unsignedCount); + const tx = isEip1559 + ? (() => { + const [chainId, nonce, prio, maxFee, gasLimit, to, value, data, accessList] = fields; + return { + type: TX_TYPE_EIP1559, + chainId: asUint(chainId, 'chainId'), + nonce: asUint(nonce, 'nonce'), + maxPriorityFeePerGas: asUint(prio, 'maxPriorityFeePerGas'), + maxFeePerGas: asUint(maxFee, 'maxFeePerGas'), + gasLimit: asUint(gasLimit, 'gasLimit'), + to: asAddress(to, 'to'), + value: asUint(value, 'value'), + data: toHex(asBytes(data, 'data')), + accessList: asAccessList(accessList), + }; + })() + : (() => { + const [chainId, nonce, gasPrice, gasLimit, to, value, data, accessList] = fields; + return { + type: TX_TYPE_ACCESS_LIST, + chainId: asUint(chainId, 'chainId'), + nonce: asUint(nonce, 'nonce'), + gasPrice: asUint(gasPrice, 'gasPrice'), + gasLimit: asUint(gasLimit, 'gasLimit'), + to: asAddress(to, 'to'), + value: asUint(value, 'value'), + data: toHex(asBytes(data, 'data')), + accessList: asAccessList(accessList), + }; + })(); + tx.from = recoverSender(payload, asUint(yParity, 'yParity'), asUint(r, 'r'), asUint(s, 's')); + return tx; + } + + throw new Error(`unsupported transaction type 0x${first.toString(16).padStart(2, '0')}`); +} + +const UINT_FIELDS = ['chainId', 'nonce', 'gasLimit', 'value', 'maxFeePerGas', 'maxPriorityFeePerGas', 'gasPrice']; + +function normalizeData(data) { + const hex = (data === undefined || data === null || data === '') ? '0x' : String(data); + return hex.toLowerCase(); +} + +/** + * Assert a signed EVM transaction is the one that was sent for signing, + * signed by `from`. + * + * `to`, `value`, `data` and `chainId` are always compared. Every other field + * present in `expected` (nonce, gasLimit, maxFeePerGas, maxPriorityFeePerGas, + * gasPrice, type) is compared too; leave out the ones the signer is allowed + * to choose. `accessList: []` requires an empty access list. + * + * @param {string} signedTxHex - the transaction the signer returned + * @param {object} expected - the fields sent for signing (hex, decimal string, number or bigint) + * @param {object} opts + * @param {string} opts.from - the wallet address that must have signed + * @param {string} [opts.label] - what the transaction is, for the error + * @param {string} [opts.note] - sentence appended to the error + * @returns {object} the decoded transaction + */ +export function assertEvmSignedMatches(signedTxHex, expected, { from, label = 'EVM transaction', note } = {}) { + if (!from) throw new Error(`assertEvmSignedMatches: the expected signer of the ${label} is required`); + for (const key of ['chainId', 'to', 'value']) { + if (expected?.[key] === undefined || expected?.[key] === null) { + throw new Error(`assertEvmSignedMatches: expected.${key} is required`); + } + } + + let tx; + try { + tx = decodeSignedEvmTransaction(signedTxHex); + } catch (err) { + throw mismatch(label, `the returned bytes do not decode: ${err.message}`, note); + } + + if (tx.from !== String(from).toLowerCase()) { + throw mismatch(label, `signed by ${tx.from}, expected ${from}`, note); + } + if (tx.to !== String(expected.to).toLowerCase()) { + throw mismatch(label, `to is ${tx.to}, expected ${expected.to}`, note); + } + if (tx.data !== normalizeData(expected.data)) { + throw mismatch(label, 'data differs', note); + } + for (const key of UINT_FIELDS) { + if (expected[key] === undefined) continue; + const want = BigInt(expected[key]); + if (tx[key] !== want) { + throw mismatch(label, `${key} is ${tx[key] ?? 'absent'}, expected ${want}`, note); + } + } + if (expected.type !== undefined && tx.type !== expected.type) { + throw mismatch(label, `type is ${tx.type}, expected ${expected.type}`, note); + } + if (Array.isArray(expected.accessList) && expected.accessList.length === 0 && tx.accessList.length !== 0) { + throw mismatch(label, 'it carries an access list', note); + } + return tx; +} diff --git a/src/trading.js b/src/trading.js index cf46866c..36c9e924 100644 --- a/src/trading.js +++ b/src/trading.js @@ -1635,6 +1635,9 @@ function isFatalBroadcastError(err) { return err?.broadcastAmbiguous === true || err?.code === 'TXHASH_MISMATCH' || err?.code === 'INVALID_SIGNED_TX' + // A remote signer returned a transaction other than the one checked. The + // next quote would go to the same signer, so stop here. + || err?.code === 'SIGNED_TX_MISMATCH' || err?.code === 'RECEIPT_TIMEOUT' || err?.code === 'BROADCAST_FAILED' // A confirmed revert is terminal too. Although its outcome is definitive From df459396924f3331b05cc1156d0d81609a52c8df Mon Sep 17 00:00:00 2001 From: Ko Date: Tue, 17 Nov 2026 15:00:36 +0800 Subject: [PATCH 2/5] fix(privy): check the signed transaction Privy returns before using it Privy signs remotely and returns signed bytes, which the CLI broadcast as they came back. Every pre-sign check had run on the transaction sent for signing, so a response encoding a different transaction would have been broadcast unchecked. signEvmTransaction and signSolanaTransaction now take the wallet address and refuse a response that is not the transaction sent, signed by that wallet (SIGNED_TX_MISMATCH; nothing is broadcast). EVM: every field sent must match. Solana: same message, and the wallet's signature slot verifies (an x402 payment has the facilitator as fee payer, so the wallet signs a later slot). Every caller passes the wallet: swaps, approvals and allowance revokes, wallet send (Solana), limit orders and x402 payments. Tests sign with fixed test keys instead of returning placeholder bytes. Co-Authored-By: Claude Opus 5.5 --- .changeset/privy-signed-tx-binding.md | 5 + src/__tests__/limit-order.test.js | 34 +++++ src/__tests__/privy-signed-tx.test.js | 104 ++++++++++++++++ src/__tests__/privy.test.js | 133 +++++++++++++++----- src/__tests__/trading.test.js | 173 +++++++++++++------------- src/__tests__/transfer.test.js | 13 +- src/limit-order.js | 7 +- src/privy.js | 59 ++++++++- src/trading.js | 8 +- src/transfer.js | 2 +- 10 files changed, 400 insertions(+), 138 deletions(-) create mode 100644 .changeset/privy-signed-tx-binding.md create mode 100644 src/__tests__/privy-signed-tx.test.js diff --git a/.changeset/privy-signed-tx-binding.md b/.changeset/privy-signed-tx-binding.md new file mode 100644 index 00000000..de3714a4 --- /dev/null +++ b/.changeset/privy-signed-tx-binding.md @@ -0,0 +1,5 @@ +--- +"nansen-cli": patch +--- + +Privy signing now checks the signed transaction Privy returns before it is used. The transaction must be exactly the one the CLI sent for signing and checked, signed by the wallet; otherwise the CLI stops with `SIGNED_TX_MISMATCH` and broadcasts nothing. This covers `trade execute` (swaps, approvals and allowance revokes), `wallet send` on Solana, limit orders and x402 payments. diff --git a/src/__tests__/limit-order.test.js b/src/__tests__/limit-order.test.js index f0c8961d..ab442c27 100644 --- a/src/__tests__/limit-order.test.js +++ b/src/__tests__/limit-order.test.js @@ -30,10 +30,12 @@ import { updateOrder, cancelOrderRequest, confirmCancelOrder, + signTransaction, } from '../limit-order.js'; import { createWallet, base58Decode, base58Encode, generateSolanaWallet } from '../wallet.js'; import { SIMULATION_RPCS } from '../rpc-urls.js'; import { PrivyClient } from '../privy.js'; +import { TEST_SOL_ADDRESS, TEST_SOL_PUBKEY_BYTES, privySignedSolana } from './fixtures/remote-signers.js'; const TEST_USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; const TEST_WSOL_MINT = 'So11111111111111111111111111111111111111112'; @@ -445,6 +447,38 @@ describe('signSolanaMessage', () => { }); }); +// ============= Transaction signing (remote signers) ============= + +describe('signTransaction via Privy', () => { + // One instruction; fee payer is the test wallet. + const tx = (blockhashByte = 3) => Buffer.concat([ + Buffer.from([1]), Buffer.alloc(64), + Buffer.from([1, 0, 1, 2]), TEST_SOL_PUBKEY_BYTES, Buffer.alloc(32, 2), Buffer.alloc(32, blockhashByte), Buffer.from([1, 1, 1, 0, 1, 0]), + ]).toString('base64'); + + afterEach(() => vi.unstubAllGlobals()); + + function privyReturning(sign) { + vi.stubGlobal('fetch', vi.fn().mockImplementation(async (_url, opts) => ({ + ok: true, + json: async () => ({ data: { signed_transaction: sign(JSON.parse(opts.body)) } }), + }))); + return { privyClient: new PrivyClient('app-id', 'app-secret'), walletId: 'wl_sol_1' }; + } + + it('returns the signed deposit when Privy signed what it was sent', async () => { + const walletInfo = privyReturning(privySignedSolana); + const signed = await signTransaction(tx(), 'privy', walletInfo, { signer: TEST_SOL_ADDRESS }); + expect(signed).toBe(privySignedSolana({ params: { transaction: tx() } })); + }); + + it('refuses a different transaction from Privy', async () => { + const walletInfo = privyReturning(() => privySignedSolana({ params: { transaction: tx(9) } })); + await expect(signTransaction(tx(), 'privy', walletInfo, { signer: TEST_SOL_ADDRESS, label: 'limit-order deposit transaction' })) + .rejects.toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/limit-order deposit transaction.*message bytes differ/) }); + }); +}); + // ============= Authentication Flow ============= describe('authenticate', () => { diff --git a/src/__tests__/privy-signed-tx.test.js b/src/__tests__/privy-signed-tx.test.js new file mode 100644 index 00000000..2aaecfba --- /dev/null +++ b/src/__tests__/privy-signed-tx.test.js @@ -0,0 +1,104 @@ +/** + * `trade execute` with a Privy wallet that hands back a transaction other than + * the one the CLI checked. Every pre-sign check (target, intent binding, value, + * fee cap, simulation) ran on the transaction sent for signing, so the returned + * bytes must never reach the execute endpoint unless they encode exactly that + * transaction, signed by the wallet. + */ +import { describe, it, expect } from 'vitest'; + +import { + ATTACKER, + APPROVE_SELECTOR, + BASE_USDC, + OUT_TOKEN, + UNLIMITED_APPROVAL_TO_ATTACKER, + erc20SwapQuote, + evmIntent, + execute, + nativeSwapQuote, + saveQuote, + solIntent, + solanaQuote, + stubNetwork, + unsignedSolanaTx, + useExecuteEnv, +} from './fixtures/execute-harness.js'; +import { + TEST_EVM_ADDRESS, + TEST_SOL_ADDRESS, + privySignedEvm, + privySignedSolana, +} from './fixtures/remote-signers.js'; + +useExecuteEnv(); + +const PRIVY_IDS = { evm: 'wl_evm', solana: 'wl_sol' }; + +// Rewrite the transaction a Privy request carries, then sign it honestly. +const privySignsInstead = (change) => (body) => privySignedEvm({ params: { transaction: { ...body.params.transaction, ...change(body.params.transaction) } } }); + +describe('Privy: the signed transaction must be the one that was checked', () => { + it('broadcasts when Privy signs exactly what it was sent (control)', async () => { + const executeBodies = stubNetwork({ privyAddress: TEST_EVM_ADDRESS, privySign: privySignedEvm }); + const quoteId = saveQuote(nativeSwapQuote(), 'base', 'privy', PRIVY_IDS, null, { swapMode: 'exactIn', request: evmIntent(TEST_EVM_ADDRESS) }); + const { err, logs } = await execute(quoteId); + expect(err).toBeNull(); + expect(executeBodies).toHaveLength(1); + expect(logs.some(l => l.includes('Transaction successful'))).toBe(true); + }); + + it('refuses an EVM swap whose recipient and calldata were substituted', async () => { + const executeBodies = stubNetwork({ + privyAddress: TEST_EVM_ADDRESS, + privySign: privySignsInstead(() => ({ to: ATTACKER, data: '0xa9059cbb' })), + }); + const quoteId = saveQuote(nativeSwapQuote(), 'base', 'privy', PRIVY_IDS, null, { swapMode: 'exactIn', request: evmIntent(TEST_EVM_ADDRESS) }); + const { err, logs } = await execute(quoteId); + expect(err).toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/swap transaction.*to is 0x0+dead/) }); + expect(executeBodies).toHaveLength(0); + expect(logs.some(l => l.includes('Trying next quote'))).toBe(false); + }); + + it('refuses an EVM swap signed by a key other than the wallet', async () => { + const executeBodies = stubNetwork({ privyAddress: TEST_EVM_ADDRESS, privySign: (body) => privySignedEvm(body, '22'.repeat(32)) }); + const quoteId = saveQuote(nativeSwapQuote(), 'base', 'privy', PRIVY_IDS, null, { swapMode: 'exactIn', request: evmIntent(TEST_EVM_ADDRESS) }); + const { err } = await execute(quoteId); + expect(err).toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/signed by 0x/) }); + expect(executeBodies).toHaveLength(0); + }); + + it('refuses an approval whose spender was substituted, before anything is broadcast', async () => { + const executeBodies = stubNetwork({ + privyAddress: TEST_EVM_ADDRESS, + privySign: (body) => (body.params.transaction.data.startsWith(APPROVE_SELECTOR) + ? privySignsInstead(() => ({ data: UNLIMITED_APPROVAL_TO_ATTACKER }))(body) + : privySignedEvm(body)), + }); + const quoteId = saveQuote(erc20SwapQuote(), 'base', 'privy', PRIVY_IDS, null, { + swapMode: 'exactIn', request: evmIntent(TEST_EVM_ADDRESS, { fromToken: BASE_USDC, toToken: OUT_TOKEN, amount: '1000000' }), + }); + const { err } = await execute(quoteId); + expect(err).toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/approval transaction.*data differs/) }); + expect(executeBodies).toHaveLength(0); + }); + + it('broadcasts a Solana swap Privy signed as sent (control)', async () => { + const executeBodies = stubNetwork({ privyAddress: TEST_SOL_ADDRESS, privySign: privySignedSolana }); + const quoteId = saveQuote(solanaQuote(unsignedSolanaTx(TEST_SOL_ADDRESS)), 'solana', 'privy', PRIVY_IDS, null, { swapMode: 'exactIn', request: solIntent(TEST_SOL_ADDRESS) }); + const { err } = await execute(quoteId); + expect(err).toBeNull(); + expect(executeBodies).toHaveLength(1); + }); + + it('refuses a Solana swap whose message was substituted', async () => { + const executeBodies = stubNetwork({ + privyAddress: TEST_SOL_ADDRESS, + privySign: () => privySignedSolana({ params: { transaction: unsignedSolanaTx(TEST_SOL_ADDRESS, 9) } }), + }); + const quoteId = saveQuote(solanaQuote(unsignedSolanaTx(TEST_SOL_ADDRESS)), 'solana', 'privy', PRIVY_IDS, null, { swapMode: 'exactIn', request: solIntent(TEST_SOL_ADDRESS) }); + const { err } = await execute(quoteId); + expect(err).toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/swap transaction.*message bytes differ/) }); + expect(executeBodies).toHaveLength(0); + }); +}); diff --git a/src/__tests__/privy.test.js b/src/__tests__/privy.test.js index 68f91979..e13f2141 100644 --- a/src/__tests__/privy.test.js +++ b/src/__tests__/privy.test.js @@ -8,6 +8,7 @@ import os from "os"; import path from "path"; import { PrivyClient, assertPrivyWalletAddress, createPrivyPaymentSignatures, createPrivyWalletPair } from "../privy.js"; import { resetSessionSpendForTests } from "../x402-policy.js"; +import { TEST_EVM_ADDRESS, TEST_SOL_ADDRESS, TEST_SOL_PUBKEY_BYTES, privySignedEvm, privySignedSolana } from "./fixtures/remote-signers.js"; // Prevent evaluatePaymentRequirement → resolveMaxAmountUsd → getWalletConfig // from reading the real ~/.nansen/wallets/config.json. Without this mock the @@ -140,58 +141,116 @@ describe("PrivyClient", () => { vi.unstubAllGlobals(); }); + const EVM_TX = { + to: "0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae", + value: "0x0", + data: "0x12345678", + chain_id: 8453, + nonce: "0x5", + gas_limit: "0x33450", + max_fee_per_gas: "0x64b540", + max_priority_fee_per_gas: "0x10c8e0", + }; + it("signEvmTransaction sends correct RPC request", async () => { const client = new PrivyClient("app-id", "app-secret"); - const mockFetch = vi.fn().mockResolvedValue({ + const mockFetch = vi.fn().mockImplementation(async (_url, opts) => ({ ok: true, - json: () => Promise.resolve({ data: { signed_transaction: "0xsigned" } }), - }); + json: async () => ({ data: { signed_transaction: privySignedEvm(JSON.parse(opts.body)) } }), + })); vi.stubGlobal("fetch", mockFetch); - const result = await client.signEvmTransaction("wl_123", { - to: "0xRecipient", - value: "0x0", - data: "0xCalldata", - chain_id: 8453, - nonce: 5, - gas_limit: "210000", - }); + const result = await client.signEvmTransaction("wl_123", EVM_TX, { from: TEST_EVM_ADDRESS }); const [url, opts] = mockFetch.mock.calls[0]; expect(url).toBe("https://api.privy.io/v1/wallets/wl_123/rpc"); const body = JSON.parse(opts.body); expect(body.method).toBe("eth_signTransaction"); - expect(body.params.transaction.to).toBe("0xRecipient"); - expect(body.params.transaction.chain_id).toBe(8453); - expect(body.params.transaction.nonce).toBe(5); - expect(body.params.transaction.gas_limit).toBe("210000"); - expect(result.data.signed_transaction).toBe("0xsigned"); + expect(body.params.transaction).toEqual(EVM_TX); + expect(result.data.signed_transaction).toBe(privySignedEvm(body)); vi.unstubAllGlobals(); }); + // One instruction; fee payer is the test wallet. + const SOL_TX = Buffer.concat([ + Buffer.from([1]), Buffer.alloc(64), + Buffer.from([1, 0, 1, 2]), TEST_SOL_PUBKEY_BYTES, Buffer.alloc(32, 2), Buffer.alloc(32, 3), Buffer.from([1, 1, 1, 0, 1, 0]), + ]).toString("base64"); + it("signSolanaTransaction sends correct RPC request with chain_type", async () => { const client = new PrivyClient("app-id", "app-secret"); - const mockFetch = vi.fn().mockResolvedValue({ + const mockFetch = vi.fn().mockImplementation(async (_url, opts) => ({ ok: true, - json: () => Promise.resolve({ data: { signed_transaction: "c2lnbmVk" } }), - }); + json: async () => ({ data: { signed_transaction: privySignedSolana(JSON.parse(opts.body)) } }), + })); vi.stubGlobal("fetch", mockFetch); - const result = await client.signSolanaTransaction("wl_456", "dW5zaWduZWQ="); + const result = await client.signSolanaTransaction("wl_456", SOL_TX, { signer: TEST_SOL_ADDRESS }); const [url, opts] = mockFetch.mock.calls[0]; expect(url).toBe("https://api.privy.io/v1/wallets/wl_456/rpc"); const body = JSON.parse(opts.body); expect(body.method).toBe("signTransaction"); expect(body.chain_type).toBe("solana"); - expect(body.params.transaction).toBe("dW5zaWduZWQ="); + expect(body.params.transaction).toBe(SOL_TX); expect(body.params.encoding).toBe("base64"); - expect(result.data.signed_transaction).toBe("c2lnbmVk"); + expect(result.data.signed_transaction).toBe(privySignedSolana(body)); vi.unstubAllGlobals(); }); + // Privy signs remotely: whatever comes back is checked against what was sent + // before any caller can broadcast it. + it.each([ + ["a different recipient", (body) => privySignedEvm({ params: { transaction: { ...body.params.transaction, to: "0x000000000000000000000000000000000000dead" } } }), /to is 0x0+dead/], + ["a raised fee", (body) => privySignedEvm({ params: { transaction: { ...body.params.transaction, max_fee_per_gas: "0x64b541" } } }), /maxFeePerGas is 6600001/], + ["bytes that are not a transaction", () => "0xsigned", /do not decode/], + ])("signEvmTransaction refuses %s", async (_name, sign, message) => { + const client = new PrivyClient("app-id", "app-secret"); + vi.stubGlobal("fetch", vi.fn().mockImplementation(async (_url, opts) => ({ + ok: true, + json: async () => ({ data: { signed_transaction: sign(JSON.parse(opts.body)) } }), + }))); + await expect(client.signEvmTransaction("wl_123", EVM_TX, { from: TEST_EVM_ADDRESS, label: "swap transaction" })) + .rejects.toMatchObject({ code: "SIGNED_TX_MISMATCH", message: expect.stringMatching(message) }); + vi.unstubAllGlobals(); + }); + + it("signEvmTransaction refuses the right transaction signed by another wallet", async () => { + const client = new PrivyClient("app-id", "app-secret"); + vi.stubGlobal("fetch", vi.fn().mockImplementation(async (_url, opts) => ({ + ok: true, + json: async () => ({ data: { signed_transaction: privySignedEvm(JSON.parse(opts.body), "22".repeat(32)) } }), + }))); + await expect(client.signEvmTransaction("wl_123", EVM_TX, { from: TEST_EVM_ADDRESS })) + .rejects.toMatchObject({ code: "SIGNED_TX_MISMATCH", message: expect.stringMatching(/signed by 0x/) }); + vi.unstubAllGlobals(); + }); + + it("signSolanaTransaction refuses a different message", async () => { + const client = new PrivyClient("app-id", "app-secret"); + const other = Buffer.from(SOL_TX, "base64"); + other[other.length - 7] ^= 1; // flip a byte of the recent blockhash + vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ data: { signed_transaction: privySignedSolana({ params: { transaction: other.toString("base64") } }) } }), + })); + await expect(client.signSolanaTransaction("wl_456", SOL_TX, { signer: TEST_SOL_ADDRESS })) + .rejects.toMatchObject({ code: "SIGNED_TX_MISMATCH", message: expect.stringMatching(/message bytes differ/) }); + vi.unstubAllGlobals(); + }); + + it("signing requires the wallet address it is checked against", async () => { + const client = new PrivyClient("app-id", "app-secret"); + const mockFetch = vi.fn(); + vi.stubGlobal("fetch", mockFetch); + await expect(client.signEvmTransaction("wl_123", EVM_TX)).rejects.toThrow(/wallet address \(from\) is required/); + await expect(client.signSolanaTransaction("wl_456", SOL_TX)).rejects.toThrow(/wallet address \(signer\) is required/); + expect(mockFetch).not.toHaveBeenCalled(); + vi.unstubAllGlobals(); + }); + }); describe("assertPrivyWalletAddress", () => { @@ -328,6 +387,7 @@ describe("createPrivyPaymentSignatures", () => { extra: { feePayer: "11111111111111111111111111111111" }, }; + let lastSigned; vi.stubGlobal("fetch", vi.fn().mockImplementation((url, options) => { // Solana RPC (fetchRecentBlockhash). Match on the JSON-RPC method, not // the hostname, so the stub still applies when NANSEN_SOLANA_RPC points @@ -346,15 +406,15 @@ describe("createPrivyPaymentSignatures", () => { return Promise.resolve({ ok: true, json: () => Promise.resolve({ - data: [{ id: "wl_sol_1", address: "7UX2i7SucgLMQcfZ75s3VXmZZY4YRUyJN9X1RgfMoDUi", chain_type: "solana" }], + data: [{ id: "wl_sol_1", address: TEST_SOL_ADDRESS, chain_type: "solana" }], }), }); } - // Privy: signSolanaTransaction + // Privy: signSolanaTransaction (signs what it was sent with the test key) return Promise.resolve({ ok: true, json: () => Promise.resolve({ - data: { signed_transaction: "c2lnbmVkdHhiYXNlNjQ=" }, + data: { signed_transaction: (lastSigned = privySignedSolana(JSON.parse(options.body))) }, }), }); })); @@ -372,7 +432,7 @@ describe("createPrivyPaymentSignatures", () => { }); const decoded = JSON.parse(atob(results[0].signature)); expect(decoded.x402Version).toBe(2); - expect(decoded.payload.transaction).toBe("c2lnbmVkdHhiYXNlNjQ="); + expect(decoded.payload.transaction).toBe(lastSigned); expect(decoded.resource.url).toBe("https://api.nansen.ai/test"); }); @@ -559,14 +619,17 @@ describe("createPrivyPaymentSignatures", () => { json: async () => ({ data: [ { id: "w-1", address: "0x1234567890abcdef1234567890abcdef12345678", chain_type: "ethereum" }, - { id: "wl_sol_1", address: "7UX2i7SucgLMQcfZ75s3VXmZZY4YRUyJN9X1RgfMoDUi", chain_type: "solana" }, + { id: "wl_sol_1", address: TEST_SOL_ADDRESS, chain_type: "solana" }, ], }), }; } if (body.method === "eth_signTypedData_v4") signed.push(body.params.typed_data.message.value); - if (body.method === "signTransaction") signed.push("solana"); - return { ok: true, json: async () => ({ data: { signature: "0xfakesignature", signed_transaction: "c2lnbmVkdHhiYXNlNjQ=" } }) }; + if (body.method === "signTransaction") { + signed.push("solana"); + return { ok: true, json: async () => ({ data: { signed_transaction: privySignedSolana(body) } }) }; + } + return { ok: true, json: async () => ({ data: { signature: "0xfakesignature" } }) }; })); return signed; } @@ -659,7 +722,7 @@ describe("createPrivyPaymentSignatures", () => { ["a short balance", "49999", 0], ["an exact balance", "50000", 1], ])("checks the Privy Solana balance before signing (%s)", async (_label, balance, expected) => { - const owner = "7UX2i7SucgLMQcfZ75s3VXmZZY4YRUyJN9X1RgfMoDUi"; + const owner = TEST_SOL_ADDRESS; const mint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; const { deriveATA } = await import("../x402-svm.js"); const solRequirement = { @@ -686,7 +749,7 @@ describe("createPrivyPaymentSignatures", () => { if (url.includes("/wallets") && !url.includes("/rpc")) { return { ok: true, json: async () => ({ data: [{ id: "wl_sol_1", address: owner, chain_type: "solana" }] }) }; } - return { ok: true, json: async () => ({ data: { signed_transaction: "signed-tx" } }) }; + return { ok: true, json: async () => ({ data: { signed_transaction: privySignedSolana(body) } }) }; }); vi.stubGlobal("fetch", fetchMock); const results = []; @@ -723,12 +786,16 @@ describe("createPrivyPaymentSignatures", () => { json: async () => ({ data: [ { id: "w-1", address: "0x1234567890abcdef1234567890abcdef12345678", chain_type: "ethereum" }, - { id: "wl_sol_1", address: solRequirement.payTo, chain_type: "solana" }, + { id: "wl_sol_1", address: TEST_SOL_ADDRESS, chain_type: "solana" }, ], }), }; } - return { ok: true, json: async () => ({ data: { signature: "0xfakesignature", signed_transaction: "c2lnbmVkdHhiYXNlNjQ=" } }) }; + const parsed = body ? JSON.parse(body) : {}; + if (parsed.method === "signTransaction") { + return { ok: true, json: async () => ({ data: { signed_transaction: privySignedSolana(parsed) } }) }; + } + return { ok: true, json: async () => ({ data: { signature: "0xfakesignature" } }) }; }); vi.stubGlobal("fetch", fetchMock); const signingCalls = (method) => fetchMock.mock.calls.filter(([, options]) => diff --git a/src/__tests__/trading.test.js b/src/__tests__/trading.test.js index af3e1705..c5ef5eba 100644 --- a/src/__tests__/trading.test.js +++ b/src/__tests__/trading.test.js @@ -117,6 +117,14 @@ import { } from '../wallet.js'; import * as wcTrading from '../walletconnect-trading.js'; import { parseTransactionMessage } from '../solana-tx.js'; +import { + TEST_EVM_ADDRESS, + TEST_SOL_ADDRESS, + TEST_SOL_KEY, + TEST_SOL_PUBKEY_BYTES, + privySignedEvm, + privySignedSolana, +} from './fixtures/remote-signers.js'; let originalHome; let tempDir; @@ -133,16 +141,24 @@ const FIXTURE_SOL_SIG = base58Encode(Buffer.alloc(64, 7)); const FIXTURE_EVM_HASH = '0x' + 'a7'.repeat(32); // A Solana transaction id is its first signature, and the CLI confirms the one -// it reads from the bytes it signed. solanaSignedTxWithSig builds signed bytes -// carrying `sig`, for signer stubs (Privy); solanaSigOf reads it back, for -// execute stubs answering a transaction the local key signed. -function solanaSignedTxWithSig(sig) { - return Buffer.concat([Buffer.from([0x01]), base58Decode(sig)]).toString('base64'); -} +// it reads from the bytes it signed. solanaSigOf reads it back, for execute +// stubs answering a transaction a signer produced. function solanaSigOf(signedTxBase64) { return base58Encode(Buffer.from(signedTxBase64, 'base64').subarray(1, 65)); } +// A one-instruction Solana transaction whose fee payer is the Privy test +// wallet, and the signature the Privy stub (privySignedSolana) gives it. +function privySolanaTx() { + const messageBytes = Buffer.from([ + 0x01, 0x00, 0x01, 0x02, + ...TEST_SOL_PUBKEY_BYTES, ...Buffer.alloc(32), ...Buffer.alloc(32), + 0x01, 0x01, 0x01, 0x00, 0x04, 0x02, 0x00, 0x00, 0x00, + ]); + return Buffer.concat([Buffer.from([0x01]), Buffer.alloc(64), messageBytes]).toString('base64'); +} +const PRIVY_SOL_SIG = solanaSigOf(signSolanaTransaction(privySolanaTx(), TEST_SOL_KEY)); + // A Solana swap is only reported successful once getSignatureStatuses says the // signature is confirmed. Tests about something else call this after stubbing // fetch: it answers that poll with `status` and hands every other request to @@ -2098,14 +2114,14 @@ describe('EVM swap gas zero fallback (execute)', () => { if (urlStr.includes('privy.io') && opts?.method === 'GET') { return Promise.resolve({ ok: true, - json: () => Promise.resolve({ id: 'wl_evm_1', address: '0xPrivyAddr', chain_type: 'ethereum' }), + json: () => Promise.resolve({ id: 'wl_evm_1', address: TEST_EVM_ADDRESS, chain_type: 'ethereum' }), }); } if (urlStr.includes('privy.io') && opts?.method === 'POST') { if (body.params?.transaction) privyTransactions.push(body.params.transaction); return Promise.resolve({ ok: true, - json: () => Promise.resolve({ data: { signed_transaction: '0xdeadbeef01' } }), + json: () => Promise.resolve({ data: { signed_transaction: privySignedEvm(JSON.parse(opts.body)) } }), }); } if (urlStr.includes('trading-api') && isExecutePath(urlStr)) { @@ -2628,7 +2644,7 @@ describe('EVM swap gas zero fallback (execute)', () => { }, 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, { swapMode: 'exactIn', request: evmIntent({ - walletAddress: '0xPrivyAddr', + walletAddress: TEST_EVM_ADDRESS, fromToken: BASE_ETH, toToken: BASE_USDC, amount: '1000000000000000000', @@ -2677,7 +2693,7 @@ describe('EVM swap gas zero fallback (execute)', () => { const quoteId = saveQuote({ success: true, quotes: [divergentNativeQuote()] }, 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, { swapMode: 'exactIn', request: evmIntent({ - walletAddress: '0xPrivyAddr', + walletAddress: TEST_EVM_ADDRESS, fromToken: BASE_ETH, toToken: BASE_USDC, amount: '1000000000000000000', @@ -2772,7 +2788,7 @@ describe('EVM swap gas zero fallback (execute)', () => { }, 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, { swapMode: 'exactIn', request: evmIntent({ - walletAddress: '0xPrivyAddr', + walletAddress: TEST_EVM_ADDRESS, fromToken: BASE_ETH, toToken: BASE_USDC, amount: '1000000000000000000', @@ -2885,7 +2901,7 @@ describe('EVM swap gas zero fallback (execute)', () => { process.env.PRIVY_APP_SECRET = 'test-secret'; __setAllowanceTimingForTests({ verifyDelayMs: 0, propagationDelayMs: 0 }); const { executeBodies, privyTransactions } = stubGasFallbackFetch({ allowance: 0n }); - const quoteId = highFeeErc20Quote('0xPrivyAddr', 'privy', [{ evm: 'wl_evm_1', solana: 'wl_sol_1' }]); + const quoteId = highFeeErc20Quote(TEST_EVM_ADDRESS, 'privy', [{ evm: 'wl_evm_1', solana: 'wl_sol_1' }]); const logs = []; const cmds = buildTradingCommands({ log: (msg) => logs.push(msg), exit: () => {} }); @@ -2968,7 +2984,7 @@ describe('Privy execute support', () => { }, 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, { swapMode: 'exactIn', request: evmIntent({ - walletAddress: '0xPrivyAddr', + walletAddress: TEST_EVM_ADDRESS, fromToken: BASE_ETH, toToken: BASE_USDC, amount: '1000000000000000000', @@ -2982,14 +2998,14 @@ describe('Privy execute support', () => { if (urlStr.includes('privy.io') && opts?.method === 'GET') { return Promise.resolve({ ok: true, - json: () => Promise.resolve({ id: 'wl_evm_1', address: '0xPrivyAddr', chain_type: 'ethereum' }), + json: () => Promise.resolve({ id: 'wl_evm_1', address: TEST_EVM_ADDRESS, chain_type: 'ethereum' }), }); } // Privy signEvmTransaction if (urlStr.includes('privy.io') && opts?.method === 'POST') { return Promise.resolve({ ok: true, - json: () => Promise.resolve({ data: { signed_transaction: '0xdeadbeef01' } }), + json: () => Promise.resolve({ data: { signed_transaction: privySignedEvm(JSON.parse(opts.body)) } }), }); } // RPC call (nonce, simulation, waitForReceipt) @@ -3053,7 +3069,7 @@ describe('Privy execute support', () => { }, 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, { swapMode: 'exactIn', request: evmIntent({ - walletAddress: '0xPrivyAddr', + walletAddress: TEST_EVM_ADDRESS, fromToken: BASE_ETH, toToken: BASE_USDC, amount: '1000000000000000000', @@ -3067,14 +3083,14 @@ describe('Privy execute support', () => { if (urlStr.includes('privy.io') && opts?.method === 'GET') { return Promise.resolve({ ok: true, - json: () => Promise.resolve({ id: 'wl_evm_1', address: '0xPrivyAddr', chain_type: 'ethereum' }), + json: () => Promise.resolve({ id: 'wl_evm_1', address: TEST_EVM_ADDRESS, chain_type: 'ethereum' }), }); } if (urlStr.includes('privy.io') && opts?.method === 'POST') { privySignCalls.push(JSON.parse(opts.body)); return Promise.resolve({ ok: true, - json: () => Promise.resolve({ data: { signed_transaction: '0xdeadbeef01' } }), + json: () => Promise.resolve({ data: { signed_transaction: privySignedEvm(JSON.parse(opts.body)) } }), }); } if (urlStr.includes('base') || urlStr.includes('mainnet')) { @@ -3110,11 +3126,10 @@ describe('Privy execute support', () => { expect(logs.some(l => l.includes('Transaction successful'))).toBe(false); }); - it('aborts (does not try the next quote) when the signed tx cannot be hashed after a successful broadcast', async () => { - // The wallet (here Privy) hands back malformed signed bytes; /execute reports - // Success, but we then cannot derive a local hash for what we just broadcast. - // That is INVALID_SIGNED_TX, and post-broadcast it must be fatal — trying the - // next quote would broadcast a SECOND swap while the first's fate is unknown. + it('refuses malformed signed bytes from Privy before broadcasting, and tries no other quote', async () => { + // Privy hands back bytes that are not a transaction. They are checked + // against the transaction sent for signing before anything is broadcast, so + // nothing reaches /execute, and the next quote (same signer) is not tried. const quoteId = saveQuote({ success: true, quotes: [ @@ -3132,7 +3147,7 @@ describe('Privy execute support', () => { }, 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, { swapMode: 'exactIn', request: evmIntent({ - walletAddress: '0xPrivyAddr', fromToken: BASE_ETH, toToken: BASE_USDC, + walletAddress: TEST_EVM_ADDRESS, fromToken: BASE_ETH, toToken: BASE_USDC, amount: '1000000000000000000', maxInputAmount: '1000000000000000000', }), }); @@ -3141,7 +3156,7 @@ describe('Privy execute support', () => { vi.stubGlobal('fetch', vi.fn().mockImplementation((url, opts) => { const urlStr = typeof url === 'string' ? url : url.toString(); if (urlStr.includes('privy.io') && opts?.method === 'GET') { - return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'wl_evm_1', address: '0xPrivyAddr', chain_type: 'ethereum' }) }); + return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'wl_evm_1', address: TEST_EVM_ADDRESS, chain_type: 'ethereum' }) }); } // Privy returns bytes that are NOT valid hex. if (urlStr.includes('privy.io') && opts?.method === 'POST') { @@ -3167,11 +3182,9 @@ describe('Privy execute support', () => { delete process.env.NANSEN_WALLET_PASSWORD; await expect(cmds.execute([], screenApi, {}, { quote: quoteId })) - .rejects.toMatchObject({ code: 'INVALID_SIGNED_TX' }); + .rejects.toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/swap transaction.*do not decode.*Nothing was broadcast/) }); - // Exactly one broadcast, and the derivation failure reached the user rather - // than being swallowed into ALL_QUOTES_FAILED after a second broadcast. - expect(executeBodies).toHaveLength(1); + expect(executeBodies).toHaveLength(0); expect(logs.some(l => l.includes('Trying next quote'))).toBe(false); expect(logs.some(l => l.includes('Transaction successful'))).toBe(false); }); @@ -3186,13 +3199,13 @@ describe('Privy execute support', () => { inAmount: '1000000000', outAmount: '50000000', // A valid, parseable benign transaction (one non-SPL instruction) — the - // pre-signing safety check now parses this before Privy signs it. - transaction: 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAECAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQECAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAQEBAAEA', + // pre-signing safety check parses this before Privy signs it. + transaction: privySolanaTx(), metadata: { requestId: 'req-123' }, }], }, 'solana', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, { swapMode: 'exactIn', - request: solanaIntent({ walletAddress: 'SolPrivyAddr1111111111111111111111111111' }), + request: solanaIntent({ walletAddress: TEST_SOL_ADDRESS }), }); vi.stubGlobal('fetch', vi.fn().mockImplementation((url, opts) => { @@ -3202,21 +3215,21 @@ describe('Privy execute support', () => { if (urlStr.includes('privy.io') && opts?.method === 'GET') { return Promise.resolve({ ok: true, - json: () => Promise.resolve({ id: 'wl_sol_1', address: 'SolPrivyAddr1111111111111111111111111111', chain_type: 'solana' }), + json: () => Promise.resolve({ id: 'wl_sol_1', address: TEST_SOL_ADDRESS, chain_type: 'solana' }), }); } // Privy signSolanaTransaction (POST) if (urlStr.includes('privy.io')) { return Promise.resolve({ ok: true, - json: () => Promise.resolve({ data: { signed_transaction: solanaSignedTxWithSig(FIXTURE_SOL_SIG) } }), + json: () => Promise.resolve({ data: { signed_transaction: privySignedSolana(JSON.parse(opts.body)) } }), }); } // Trading API executeTransaction if (urlStr.includes('trading-api')) { return Promise.resolve({ ok: true, - text: () => Promise.resolve(JSON.stringify({ status: 'Success', signature: FIXTURE_SOL_SIG, chainType: 'solana', broadcaster: 'test' })), + text: () => Promise.resolve(JSON.stringify({ status: 'Success', signature: PRIVY_SOL_SIG, chainType: 'solana', broadcaster: 'test' })), }); } return Promise.resolve({ ok: true, json: () => Promise.resolve({}) }); @@ -3258,7 +3271,7 @@ describe('Privy execute support', () => { }], }, 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, { swapMode: 'exactIn', - request: evmIntent({ walletAddress: '0xPrivyAddr', fromToken: BASE_USDC, toToken: OUT_TOKEN }), + request: evmIntent({ walletAddress: TEST_EVM_ADDRESS, fromToken: BASE_USDC, toToken: OUT_TOKEN }), }); const rpcCalls = []; @@ -3271,14 +3284,14 @@ describe('Privy execute support', () => { if (urlStr.includes('privy.io') && opts?.method === 'GET') { return Promise.resolve({ ok: true, - json: () => Promise.resolve({ id: 'wl_evm_1', address: '0xPrivyAddr', chain_type: 'ethereum' }), + json: () => Promise.resolve({ id: 'wl_evm_1', address: TEST_EVM_ADDRESS, chain_type: 'ethereum' }), }); } // Privy signEvmTransaction if (urlStr.includes('privy.io') && opts?.method === 'POST') { return Promise.resolve({ ok: true, - json: () => Promise.resolve({ data: { signed_transaction: '0xdeadbeef02' } }), + json: () => Promise.resolve({ data: { signed_transaction: privySignedEvm(JSON.parse(opts.body)) } }), }); } // RPC calls @@ -3351,7 +3364,7 @@ describe('Privy execute support', () => { }, 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, { swapMode: 'exactIn', request: evmIntent({ - walletAddress: '0xPrivyAddr', + walletAddress: TEST_EVM_ADDRESS, fromToken: BASE_USDC, toToken: OUT_TOKEN, amount: '100000', @@ -3372,7 +3385,7 @@ describe('Privy execute support', () => { if (urlStr.includes('privy.io') && opts?.method === 'GET') { return Promise.resolve({ ok: true, - json: () => Promise.resolve({ id: 'wl_evm_1', address: '0xPrivyAddr', chain_type: 'ethereum' }), + json: () => Promise.resolve({ id: 'wl_evm_1', address: TEST_EVM_ADDRESS, chain_type: 'ethereum' }), }); } if (urlStr.includes('privy.io') && opts?.method === 'POST') { @@ -3430,7 +3443,7 @@ describe('Privy execute support', () => { }, 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, { swapMode: 'exactIn', request: evmIntent({ - walletAddress: '0xPrivyAddr', + walletAddress: TEST_EVM_ADDRESS, fromToken: BASE_USDC, toToken: OUT_TOKEN, amount: '100000', @@ -3459,12 +3472,12 @@ describe('Privy execute support', () => { if (urlStr.includes('privy.io') && opts?.method === 'GET') { return Promise.resolve({ ok: true, - json: () => Promise.resolve({ id: 'wl_evm_1', address: '0xPrivyAddr', chain_type: 'ethereum' }), + json: () => Promise.resolve({ id: 'wl_evm_1', address: TEST_EVM_ADDRESS, chain_type: 'ethereum' }), }); } if (urlStr.includes('privy.io') && opts?.method === 'POST') { privyPostCount++; - const data = privyPostCount === 1 ? { signed_transaction: '0xdeadbeef03' } : {}; + const data = privyPostCount === 1 ? { signed_transaction: privySignedEvm(JSON.parse(opts.body)) } : {}; return Promise.resolve({ ok: true, json: () => Promise.resolve({ data }) }); } if (urlStr.includes('base') || urlStr.includes('mainnet')) { @@ -7176,7 +7189,7 @@ describe('exactOut max-input enforcement (adversarial)', () => { let body = {}; try { body = opts?.body ? JSON.parse(opts.body) : {}; } catch { /* non-JSON */ } if (urlStr.includes('privy.io') && opts?.method === 'GET') { - return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'wl_evm_1', address: '0xPrivyAddr', chain_type: 'ethereum' }) }); + return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'wl_evm_1', address: TEST_EVM_ADDRESS, chain_type: 'ethereum' }) }); } if (body.method === 'eth_getCode') { return Promise.resolve({ text: () => Promise.resolve(JSON.stringify({ jsonrpc: '2.0', id: body.id, result: '0x6080604052' })) }); @@ -7222,7 +7235,7 @@ describe('exactOut max-input enforcement (adversarial)', () => { vi.stubGlobal('fetch', trackingFetch(calls)); const quoteId = saveQuote({ success: true, quotes: [overpayingExactOutQuote(inputMint, native)] }, - 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, exactOutRequestMeta(inputMint, '0xPrivyAddr')); + 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, exactOutRequestMeta(inputMint, TEST_EVM_ADDRESS)); const cmds = buildTradingCommands({ log: () => {}, exit: () => {} }); @@ -7315,7 +7328,7 @@ describe('exactOut max-input enforcement (adversarial)', () => { vi.stubGlobal('fetch', trackingFetch(calls)); const quoteId = saveQuote({ success: true, quotes: [emptyInputAmountQuote()] }, - 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, exactOutRequestMeta(ERC20_IN, '0xPrivyAddr')); + 'base', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, exactOutRequestMeta(ERC20_IN, TEST_EVM_ADDRESS)); const logs = []; const cmds = buildTradingCommands({ log: (m) => logs.push(m), exit: () => {} }); @@ -7729,7 +7742,7 @@ describe('Solana intent binding (adversarial)', () => { const urlStr = typeof url === 'string' ? url : url.toString(); calls.push({ url: urlStr, method: opts?.method }); if (urlStr.includes('privy.io') && opts?.method === 'GET') { - return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'wl_sol_1', address: 'SolPrivyAddr1111111111111111111111111111', chain_type: 'solana' }) }); + return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'wl_sol_1', address: TEST_SOL_ADDRESS, chain_type: 'solana' }) }); } return Promise.resolve({ ok: true, text: () => Promise.resolve(JSON.stringify({ jsonrpc: '2.0', id: 1, result: null })), json: () => Promise.resolve({}) }); })); @@ -7746,7 +7759,7 @@ describe('Solana intent binding (adversarial)', () => { }, 'solana', 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, { swapMode: 'exactIn', request: solanaIntent({ - walletAddress: 'SolPrivyAddr1111111111111111111111111111', + walletAddress: TEST_SOL_ADDRESS, amount: '1000000000', maxInputAmount: '1000000000', }), @@ -9997,14 +10010,7 @@ describe('standard execution route — swap command flow', () => { it('prints a Signature line (not Tx Hash) for a Solana standard-route success', async () => { // Solana via Privy keeps the local wallet out of the picture, isolating the // output label on the normalised response. - const sigCount = Buffer.from([0x01]); - const emptySig = Buffer.alloc(64); - const messageBytes = Buffer.from([ - 0x01, 0x00, 0x01, 0x02, - ...Buffer.alloc(32), ...Buffer.alloc(32), ...Buffer.alloc(32), - 0x01, 0x01, 0x01, 0x00, 0x04, 0x02, 0x00, 0x00, 0x00, - ]); - const txBase64 = Buffer.concat([sigCount, emptySig, messageBytes]).toString('base64'); + const txBase64 = privySolanaTx(); const quoteId = saveQuote( { success: true, metadata: { quoteId: 'backend-quote-id' }, quotes: [{ aggregator: 'jupiter', inputMint: SOL_MINT, outputMint: SOL_USDC, inAmount: '1000000000', outAmount: '50000000', transaction: txBase64, metadata: { requestId: 'req-1' } }] }, @@ -10012,19 +10018,19 @@ describe('standard execution route — swap command flow', () => { 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, - { swapMode: 'exactIn', request: solanaIntent({ walletAddress: 'SolPrivyAddr1111111111111111111111111111' }) }, + { swapMode: 'exactIn', request: solanaIntent({ walletAddress: TEST_SOL_ADDRESS }) }, ); vi.stubGlobal('fetch', vi.fn().mockImplementation((url, opts) => { const urlStr = typeof url === 'string' ? url : url.toString(); if (urlStr.startsWith('https://api.privy.io/') && opts?.method === 'GET') { - return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'wl_sol_1', address: 'SolPrivyAddr1111111111111111111111111111', chain_type: 'solana' }) }); + return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'wl_sol_1', address: TEST_SOL_ADDRESS, chain_type: 'solana' }) }); } if (urlStr.startsWith('https://api.privy.io/')) { - return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: { signed_transaction: solanaSignedTxWithSig('4WtRY1XgSpkCoEzqWeFhLFmseb4dqGeaSWDj46pcp5mA7zGBukhW7kXHNquUaLoWX52pWEtRRn5en4JfZXYkbTj') } }) }); + return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: { signed_transaction: privySignedSolana(JSON.parse(opts.body)) } }) }); } if (urlStr.includes('trading-api') && urlStr.endsWith('/execution/standard')) { - return Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve(JSON.stringify({ success: true, txHash: '4WtRY1XgSpkCoEzqWeFhLFmseb4dqGeaSWDj46pcp5mA7zGBukhW7kXHNquUaLoWX52pWEtRRn5en4JfZXYkbTj' })) }); + return Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve(JSON.stringify({ success: true, txHash: PRIVY_SOL_SIG })) }); } return Promise.resolve({ ok: true, text: () => Promise.resolve(JSON.stringify({})) }); })); @@ -10037,7 +10043,7 @@ describe('standard execution route — swap command flow', () => { confirmSolanaSignatures(); await cmds.execute([], screenApi, {}, { quote: quoteId }); - expect(logs.some(l => l.includes('Signature:') && l.includes('4WtRY1XgSpkCoEzqWeFhLFmseb4dqGeaSWDj46pcp5mA7zGBukhW7kXHNquUaLoWX52pWEtRRn5en4JfZXYkbTj'))).toBe(true); + expect(logs.some(l => l.includes('Signature:') && l.includes(PRIVY_SOL_SIG))).toBe(true); expect(logs.some(l => l.includes('Tx Hash:'))).toBe(false); }); @@ -10045,14 +10051,7 @@ describe('standard execution route — swap command flow', () => { // closed before its signature poll: a node-rejected broadcast must never print // the success banner and exit 0 for a transaction that may not have propagated. it('fails closed on a Solana node-rejected broadcast instead of reporting success', async () => { - const sigCount = Buffer.from([0x01]); - const emptySig = Buffer.alloc(64); - const messageBytes = Buffer.from([ - 0x01, 0x00, 0x01, 0x02, - ...Buffer.alloc(32), ...Buffer.alloc(32), ...Buffer.alloc(32), - 0x01, 0x01, 0x01, 0x00, 0x04, 0x02, 0x00, 0x00, 0x00, - ]); - const txBase64 = Buffer.concat([sigCount, emptySig, messageBytes]).toString('base64'); + const txBase64 = privySolanaTx(); const quoteId = saveQuote( { success: true, metadata: { quoteId: 'backend-quote-id' }, quotes: [{ aggregator: 'jupiter', inputMint: SOL_MINT, outputMint: SOL_USDC, inAmount: '1000000000', outAmount: '50000000', transaction: txBase64, metadata: { requestId: 'req-1' } }] }, @@ -10060,19 +10059,19 @@ describe('standard execution route — swap command flow', () => { 'privy', { evm: 'wl_evm_1', solana: 'wl_sol_1' }, null, - { swapMode: 'exactIn', request: solanaIntent({ walletAddress: 'SolPrivyAddr1111111111111111111111111111' }) }, + { swapMode: 'exactIn', request: solanaIntent({ walletAddress: TEST_SOL_ADDRESS }) }, ); vi.stubGlobal('fetch', vi.fn().mockImplementation((url, opts) => { const urlStr = typeof url === 'string' ? url : url.toString(); if (urlStr.startsWith('https://api.privy.io/') && opts?.method === 'GET') { - return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'wl_sol_1', address: 'SolPrivyAddr1111111111111111111111111111', chain_type: 'solana' }) }); + return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'wl_sol_1', address: TEST_SOL_ADDRESS, chain_type: 'solana' }) }); } if (urlStr.startsWith('https://api.privy.io/')) { - return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: { signed_transaction: 'c2lnbmVkVHg=' } }) }); + return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: { signed_transaction: privySignedSolana(JSON.parse(opts.body)) } }) }); } if (urlStr.includes('trading-api') && urlStr.endsWith('/execution/standard')) { - return Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve(JSON.stringify({ success: true, txHash: '4WtRY1XgSpkCoEzqWeFhLFmseb4dqGeaSWDj46pcp5mA7zGBukhW7kXHNquUaLoWX52pWEtRRn5en4JfZXYkbTj', broadcastSucceeded: false, broadcastError: 'node rejected' })) }); + return Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve(JSON.stringify({ success: true, txHash: PRIVY_SOL_SIG, broadcastSucceeded: false, broadcastError: 'node rejected' })) }); } return Promise.resolve({ ok: true, text: () => Promise.resolve(JSON.stringify({})) }); })); @@ -10090,7 +10089,7 @@ describe('standard execution route — swap command flow', () => { // user can check the explorer. expect(logs.some(l => l.includes('Transaction successful'))).toBe(false); expect(logs.some(l => l.includes('may still propagate'))).toBe(true); - expect(logs.some(l => l.includes('4WtRY1XgSpkCoEzqWeFhLFmseb4dqGeaSWDj46pcp5mA7zGBukhW7kXHNquUaLoWX52pWEtRRn5en4JfZXYkbTj'))).toBe(true); + expect(logs.some(l => l.includes(PRIVY_SOL_SIG))).toBe(true); // The quote stays spent — this path must never invite a re-execute. expect(() => loadQuote(quoteId)).toThrow(); }); @@ -10474,17 +10473,19 @@ describe('standard execution route — swap command flow', () => { // lands can still fail, so the CLI must read the signature status before it // prints the success banner. Same three outcomes as the EVM receipt poll. describe('Solana swap: on-chain confirmation after broadcast', () => { - const SIG = '4WtRY1XgSpkCoEzqWeFhLFmseb4dqGeaSWDj46pcp5mA7zGBukhW7kXHNquUaLoWX52pWEtRRn5en4JfZXYkbTj'; - const PRIVY_SOL_ADDR = 'SolPrivyAddr1111111111111111111111111111'; + // The Privy stub signs with the test key, so the signature is the real + // (deterministic) ed25519 signature of solanaTx() by the test wallet. + const PRIVY_SOL_ADDR = TEST_SOL_ADDRESS; function solanaTx() { const messageBytes = Buffer.from([ 0x01, 0x00, 0x01, 0x02, - ...Buffer.alloc(32), ...Buffer.alloc(32), ...Buffer.alloc(32), + ...TEST_SOL_PUBKEY_BYTES, ...Buffer.alloc(32), ...Buffer.alloc(32), 0x01, 0x01, 0x01, 0x00, 0x04, 0x02, 0x00, 0x00, 0x00, ]); return Buffer.concat([Buffer.from([0x01]), Buffer.alloc(64), messageBytes]).toString('base64'); } + const SIG = solanaSigOf(signSolanaTransaction(solanaTx(), TEST_SOL_KEY)); // Two candidates, so a test can prove the loop never signs the second one. function saveTwoCandidateQuote() { @@ -10501,9 +10502,9 @@ describe('Solana swap: on-chain confirmation after broadcast', () => { // `statuses` is the sequence getSignatureStatuses returns (the last entry // repeats). An Error entry makes that poll fail at the transport. - // `signedSig` is the signature in the bytes Privy signs; the execute API - // always reports SIG. - function stubFetch({ route, statuses, signedSig = SIG }) { + // `reportedSig` is the signature the execute API reports; Privy always + // signs, so the signed bytes carry SIG. + function stubFetch({ route, statuses, reportedSig = SIG }) { const executeCalls = []; const statusCalls = []; vi.stubGlobal('fetch', vi.fn().mockImplementation((url, opts) => { @@ -10512,13 +10513,13 @@ describe('Solana swap: on-chain confirmation after broadcast', () => { return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'wl_sol_1', address: PRIVY_SOL_ADDR, chain_type: 'solana' }) }); } if (urlStr.startsWith('https://api.privy.io/')) { - return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: { signed_transaction: solanaSignedTxWithSig(signedSig) } }) }); + return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: { signed_transaction: privySignedSolana(JSON.parse(opts.body)) } }) }); } if (urlStr.includes('trading-api') && (urlStr.endsWith('/execution/standard') || urlStr.endsWith('/execute'))) { executeCalls.push(urlStr); const body = route === 'standard' - ? { success: true, txHash: SIG } - : { status: 'Success', signature: SIG, chainType: 'solana', broadcaster: 'jupiter' }; + ? { success: true, txHash: reportedSig } + : { status: 'Success', signature: reportedSig, chainType: 'solana', broadcaster: 'jupiter' }; return Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve(JSON.stringify(body)) }); } const body = opts?.body ? JSON.parse(opts.body) : {}; @@ -10621,9 +10622,9 @@ describe('Solana swap: on-chain confirmation after broadcast', () => { }); it('refuses a reported signature that is not the one this CLI signed, without polling it', async () => { - // The API reports SIG, which may well be confirmed, but the transaction - // Privy signed carries a different signature. - const { executeCalls, statusCalls } = stubFetch({ route, statuses: [CONFIRMED_SOL_STATUS], signedSig: FIXTURE_SOL_SIG }); + // The API reports FIXTURE_SOL_SIG, which may well be confirmed, but the + // transaction Privy signed carries SIG. + const { executeCalls, statusCalls } = stubFetch({ route, statuses: [CONFIRMED_SOL_STATUS], reportedSig: FIXTURE_SOL_SIG }); const quoteId = saveTwoCandidateQuote(); const logs = []; const cmds = buildTradingCommands({ log: (m) => logs.push(m), exit: () => {} }); diff --git a/src/__tests__/transfer.test.js b/src/__tests__/transfer.test.js index 7bf0cc80..f7ed5ee7 100644 --- a/src/__tests__/transfer.test.js +++ b/src/__tests__/transfer.test.js @@ -25,6 +25,7 @@ import { base58Encode } from '../wallet.js'; import * as wallet from '../wallet.js'; import * as wcTrading from '../walletconnect-trading.js'; import { PrivyClient } from '../privy.js'; +import { TEST_SOL_ADDRESS, privySignedSolana } from './fixtures/remote-signers.js'; // ============= Unit Tests ============= @@ -1377,13 +1378,13 @@ describe('sendTokens via Privy', () => { name: 'pv', provider: 'privy', evm: '0x742d35Cc6bF4F3F4e0e3a8DD7e37fF4e4be4E4b4', - solana: '9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM', + solana: TEST_SOL_ADDRESS, privyWalletIds: { evm: 'wl_evm_1', solana: 'wl_sol_1' }, }); getWalletSpy = vi.spyOn(PrivyClient.prototype, 'getWallet').mockImplementation(async (walletId) => ({ id: walletId, address: walletId === 'wl_sol_1' - ? '9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM' + ? TEST_SOL_ADDRESS : '0x742d35Cc6bF4F3F4e0e3a8DD7e37fF4e4be4E4b4', })); }); @@ -1529,7 +1530,7 @@ describe('sendTokens via Privy', () => { name: 'pv', provider: 'privy', evm: null, - solana: '9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM', + solana: TEST_SOL_ADDRESS, privyWalletIds: { evm: undefined, solana: 'wl_sol_1' }, }); @@ -1563,7 +1564,7 @@ describe('sendTokens via Privy', () => { signCallBody = JSON.parse(opts.body); return { ok: true, - json: () => Promise.resolve({ data: { signed_transaction: 'c2lnbmVkdHg=' } }), + json: () => Promise.resolve({ data: { signed_transaction: privySignedSolana(JSON.parse(opts.body)) } }), }; } // Solana RPC: sendTransaction @@ -1647,7 +1648,7 @@ describe('sendTokens via Privy', () => { if (url?.includes('privy.io')) { return { ok: true, - json: () => Promise.resolve({ data: { signed_transaction: 'c2lnbmVkdHg=' } }), + json: () => Promise.resolve({ data: { signed_transaction: privySignedSolana(JSON.parse(opts.body)) } }), }; } // sendTransaction @@ -1703,7 +1704,7 @@ describe('sendTokens via Privy', () => { }); expect(result.dryRun).toBe(true); - expect(result.from).toBe('9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM'); + expect(result.from).toBe(TEST_SOL_ADDRESS); expect(result.chain).toBe('solana'); expect(fetch).toHaveBeenCalledTimes(1); }); diff --git a/src/limit-order.js b/src/limit-order.js index 8285d4ee..53df2ab3 100644 --- a/src/limit-order.js +++ b/src/limit-order.js @@ -387,7 +387,7 @@ function getLocalWalletPrivateKey(walletName) { * Sign a Solana transaction (base64) using the appropriate wallet type. * Returns base64-encoded signed transaction. */ -export async function signTransaction(txBase64, walletType, walletInfo) { +export async function signTransaction(txBase64, walletType, walletInfo, { signer, label = 'limit-order transaction' } = {}) { if (walletType === 'local') { return signSolanaTransaction(txBase64, walletInfo.privateKeyHex); } @@ -396,6 +396,7 @@ export async function signTransaction(txBase64, walletType, walletInfo) { const result = await walletInfo.privyClient.signSolanaTransaction( walletInfo.walletId, txBase64, + { signer, label }, ); return result.data?.signed_transaction || result.signed_transaction; } @@ -909,7 +910,7 @@ EXAMPLES: }); if (!depositOutcome.proceed) throw new Error(`Refusing to sign deposit — ${depositOutcome.reason}`); log(' Signing deposit transaction...'); - const signedDepositTx = await signTransaction(deposit.transaction, walletType, walletInfo); + const signedDepositTx = await signTransaction(deposit.transaction, walletType, walletInfo, { signer: pubkey, label: 'limit-order deposit transaction' }); // 6. Create order log(' Submitting order...'); @@ -1151,7 +1152,7 @@ EXAMPLES: }); if (!cancelOutcome.proceed) throw new Error(`Refusing to sign withdrawal — ${cancelOutcome.reason}`); log(' Signing withdrawal transaction...'); - const signedTx = await signTransaction(cancelResult.transaction, walletType, walletInfo); + const signedTx = await signTransaction(cancelResult.transaction, walletType, walletInfo, { signer: pubkey, label: 'limit-order cancel transaction' }); // 5. Confirm cancellation log(' Confirming cancellation...'); diff --git a/src/privy.js b/src/privy.js index e1d32ebe..8c206140 100644 --- a/src/privy.js +++ b/src/privy.js @@ -23,6 +23,7 @@ import { buildPaymentSignatureHeader, } from "./walletconnect-x402.js"; import { trace } from "./debug.js"; +import { assertEvmSignedMatches, assertSolanaSignedMatches } from "./signed-tx-binding.js"; // ============= Constants ============= @@ -123,19 +124,67 @@ export class PrivyClient { }); } - async signEvmTransaction(walletId, transaction) { - return this._request("POST", `/wallets/${walletId}/rpc`, { + /** + * Sign (never send) an EVM transaction. The returned bytes are checked to + * encode exactly `transaction`, signed by `from`, before they are handed + * back: every pre-sign check the caller ran applies to `transaction`, so a + * different transaction must never reach a broadcast. Throws + * SIGNED_TX_MISMATCH otherwise. A response without signed bytes is returned + * as is; callers already treat that as a failed signature. + * + * @param {string} walletId + * @param {object} transaction - snake_case fields sent to Privy + * @param {object} opts + * @param {string} opts.from - the wallet's address + * @param {string} [opts.label] - what the transaction is, for errors + */ + async signEvmTransaction(walletId, transaction, { from, label } = {}) { + if (!from) throw new Error("signEvmTransaction: the wallet address (from) is required to check the signed transaction"); + const result = await this._request("POST", `/wallets/${walletId}/rpc`, { method: "eth_signTransaction", params: { transaction }, }); + const signed = result?.data?.signed_transaction || result?.signed_transaction; + if (signed) { + // Privy signs exactly what it is given (an EIP-1559 transaction with no + // access list), so every field must come back unchanged. + assertEvmSignedMatches(signed, { + chainId: transaction.chain_id, + nonce: transaction.nonce, + gasLimit: transaction.gas_limit, + maxFeePerGas: transaction.max_fee_per_gas, + maxPriorityFeePerGas: transaction.max_priority_fee_per_gas, + to: transaction.to, + value: transaction.value, + data: transaction.data, + type: 2, + accessList: [], + }, { from, label }); + } + return result; } - async signSolanaTransaction(walletId, transactionBase64) { - return this._request("POST", `/wallets/${walletId}/rpc`, { + /** + * Sign (never send) a Solana transaction. The returned bytes are checked to + * carry the same message, signed by `signer`; throws SIGNED_TX_MISMATCH + * otherwise. A response without signed bytes is returned as is. + * + * @param {string} walletId + * @param {string} transactionBase64 + * @param {object} opts + * @param {string} opts.signer - the wallet's base58 address + * @param {string} [opts.label] - what the transaction is, for errors + */ + async signSolanaTransaction(walletId, transactionBase64, { signer, label } = {}) { + if (!signer) throw new Error("signSolanaTransaction: the wallet address (signer) is required to check the signed transaction"); + const result = await this._request("POST", `/wallets/${walletId}/rpc`, { method: "signTransaction", chain_type: "solana", params: { transaction: transactionBase64, encoding: "base64" }, }); + const signed = result?.data?.signed_transaction || result?.signed_transaction; + if (signed) assertSolanaSignedMatches(transactionBase64, signed, { signer, label }); + return result; } async signSolanaMessage(walletId, messageBuffer) { @@ -496,7 +545,7 @@ async function signPrivySolanaRequirement(client, solWallet, requirement, url, o ); const signed = await signWithSessionCharge(svmDecision, async () => { - const signResult = await client.signSolanaTransaction(solWallet.id, txBase64); + const signResult = await client.signSolanaTransaction(solWallet.id, txBase64, { signer: solWallet.address, label: 'x402 payment transaction' }); const signedTx = signResult.data?.signed_transaction || signResult.signed_transaction; if (!signedTx) throw new Error('Privy returned no signed transaction'); diff --git a/src/trading.js b/src/trading.js index 36c9e924..c61e8174 100644 --- a/src/trading.js +++ b/src/trading.js @@ -4002,7 +4002,7 @@ EXAMPLES: } log(' Signing Solana transaction via Privy...'); - const signResult = await privyClient.signSolanaTransaction(solWalletId, txBase64); + const signResult = await privyClient.signSolanaTransaction(solWalletId, txBase64, { signer: walletAddress, label: 'swap transaction' }); signedTransaction = signResult.data?.signed_transaction || signResult.signed_transaction; requestId = currentQuote.metadata?.requestId; @@ -4110,7 +4110,7 @@ EXAMPLES: gas_limit: toHex(APPROVAL_GAS_LIMIT), max_fee_per_gas: toHex(approvalMaxFee), max_priority_fee_per_gas: toHex(approvalPriorityFee), - }); + }, { from: walletAddress, label: 'allowance-revoke transaction' }); const signedRevoke = revokeSignResult.data?.signed_transaction || revokeSignResult.signed_transaction; if (!signedRevoke) { log(` ❌ Allowance revoke failed for ${quoteName}: Privy returned no signed transaction`); @@ -4166,7 +4166,7 @@ EXAMPLES: gas_limit: toHex(APPROVAL_GAS_LIMIT), max_fee_per_gas: toHex(approvalMaxFee), max_priority_fee_per_gas: toHex(approvalPriorityFee), - }); + }, { from: walletAddress, label: 'approval transaction' }); const signedApproval = approvalSignResult.data?.signed_transaction || approvalSignResult.signed_transaction; if (!signedApproval) { const revokedMsg = shouldRevoke @@ -4265,7 +4265,7 @@ EXAMPLES: gas_limit: toHex(finalGas), max_fee_per_gas: toHex(maxFee), max_priority_fee_per_gas: toHex(priorityFee), - }); + }, { from: walletAddress, label: 'swap transaction' }); signedTransaction = signResult.data?.signed_transaction || signResult.signed_transaction; } else if (chainType === 'solana') { diff --git a/src/transfer.js b/src/transfer.js index 961bd6c2..d5b9ef77 100644 --- a/src/transfer.js +++ b/src/transfer.js @@ -810,7 +810,7 @@ async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walle to, amount: amountRaw, amountStr: amount, token, fromAddress, }); - const signResult = await client.signSolanaTransaction(walletId, unsignedTransaction); + const signResult = await client.signSolanaTransaction(walletId, unsignedTransaction, { signer: fromAddress, label: 'transfer transaction' }); const signedTx = signResult.data?.signed_transaction || signResult.signed_transaction; const txHash = await broadcastTransaction(signedTx, chain, token); const confirmation = await waitForSolanaConfirmation(CHAIN_RPCS.solana, txHash); From e2f003df15b19766dd4c9f647ecff3d1aee8b944 Mon Sep 17 00:00:00 2001 From: Ko Date: Tue, 17 Nov 2026 15:13:22 +0800 Subject: [PATCH 3/5] test: match the Privy host exactly in the execute test harness Co-Authored-By: Claude Opus 5.5 --- src/__tests__/fixtures/execute-harness.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/__tests__/fixtures/execute-harness.js b/src/__tests__/fixtures/execute-harness.js index 8096a6d8..8b933af1 100644 --- a/src/__tests__/fixtures/execute-harness.js +++ b/src/__tests__/fixtures/execute-harness.js @@ -131,12 +131,13 @@ export function stubNetwork({ privyAddress, privySign } = {}) { let allowance = 0n; vi.stubGlobal('fetch', vi.fn().mockImplementation((url, opts) => { const u = String(url); + const isPrivy = URL.canParse(u) && new URL(u).hostname === 'api.privy.io'; let body = {}; try { body = typeof opts?.body === 'string' ? JSON.parse(opts.body) : {}; } catch { /* not JSON */ } - if (u.includes('privy.io') && opts?.method === 'GET') { + if (isPrivy && opts?.method === 'GET') { return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'w', address: privyAddress }) }); } - if (u.includes('privy.io') && opts?.method === 'POST') { + if (isPrivy && opts?.method === 'POST') { return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: { signed_transaction: privySign(body) } }) }); } if (u.includes('trading-api')) { From 38e2bda5fa26fb427266c1f77557fb6a6bf4c3b8 Mon Sep 17 00:00:00 2001 From: Ko Date: Tue, 17 Nov 2026 16:31:24 +0800 Subject: [PATCH 4/5] chore: run CI now that this PR targets main Co-Authored-By: Claude Opus 5.5 From e698797172d018931d1d8e000170cafb908af036 Mon Sep 17 00:00:00 2001 From: Ko Date: Tue, 17 Nov 2026 16:44:43 +0800 Subject: [PATCH 5/5] fix(walletconnect): check a signed transaction the wallet returns before broadcasting it When a WalletConnect wallet returns signed bytes instead of broadcasting itself, the CLI broadcast them as they came back, although every pre-sign check had run on the transaction it sent the wallet. The send functions now take the wallet address and refuse returned bytes that are not signed by it or differ from what was sent (EVM: chain, recipient, value, calldata and gas limit; the wallet still picks nonce and fees. Solana: the same message). A signature-only Solana reply must verify. The error is SIGNED_TX_MISMATCH and says the wallet may have sent the transaction itself. A reply carrying only a hash is unchanged. Covers swaps, approvals, allowance revokes, wallet send and limit orders. Co-Authored-By: Claude Opus 5.5 --- .changeset/walletconnect-signed-tx-binding.md | 5 + src/__tests__/trading.test.js | 8 +- src/__tests__/walletconnect-signed-tx.test.js | 140 ++++++++++++++++++ src/__tests__/walletconnect-trading.test.js | 135 +++++++++++++---- src/limit-order.js | 2 +- src/trading.js | 15 +- src/transfer.js | 2 +- src/walletconnect-trading.js | 79 ++++++++-- 8 files changed, 335 insertions(+), 51 deletions(-) create mode 100644 .changeset/walletconnect-signed-tx-binding.md create mode 100644 src/__tests__/walletconnect-signed-tx.test.js diff --git a/.changeset/walletconnect-signed-tx-binding.md b/.changeset/walletconnect-signed-tx-binding.md new file mode 100644 index 00000000..7922d68e --- /dev/null +++ b/.changeset/walletconnect-signed-tx-binding.md @@ -0,0 +1,5 @@ +--- +"nansen-cli": patch +--- + +WalletConnect signing now checks a signed transaction the wallet returns before the CLI broadcasts it. It must be signed by the connected wallet and carry the chain, recipient, value, calldata and gas limit the CLI sent (for Solana, the exact message); a signature-only Solana reply must verify. Otherwise the CLI stops with `SIGNED_TX_MISMATCH` and does not broadcast it. This covers `trade execute` (swaps, approvals and allowance revokes), `wallet send` on EVM chains and limit orders. diff --git a/src/__tests__/trading.test.js b/src/__tests__/trading.test.js index c5ef5eba..92b5e0cf 100644 --- a/src/__tests__/trading.test.js +++ b/src/__tests__/trading.test.js @@ -1860,7 +1860,7 @@ describe('WalletConnect execute support', () => { await cmds.execute([], screenApi, { 'no-verify-outcome': true }, { quote: quoteId }); - expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ gas: '31500' })); + expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ gas: '31500' }), undefined, { from: '0x742d35Cc6bF4F3f4e0e3a8DD7e37ff4e4Be4E4B4', label: 'swap transaction' }); expect(logs.some(l => l.includes('Using estimated gas 31500 (quote had no gas)'))).toBe(true); vi.unstubAllGlobals(); @@ -2328,7 +2328,7 @@ describe('EVM swap gas zero fallback (execute)', () => { await cmds.execute([], screenApi, { 'no-simulate': true, 'no-verify-outcome': true }, { quote: quoteId }); expect(approvalSpy).not.toHaveBeenCalled(); - expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ gas: '31500' })); + expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ gas: '31500' }), undefined, { from: '0x742d35Cc6bF4F3f4e0e3a8DD7e37ff4e4Be4E4B4', label: 'swap transaction' }); }); // The approval and allowance-revoke sends run BEFORE swapHandedOff is set, so @@ -2523,7 +2523,7 @@ describe('EVM swap gas zero fallback (execute)', () => { const cmds = buildTradingCommands({ log: () => {}, exit: () => {} }); await cmds.execute([], screenApi, { 'no-verify-outcome': true }, { quote: quoteId }); - expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ gas: '210000' })); + expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ gas: '210000' }), undefined, { from: '0x742d35Cc6bF4F3f4e0e3a8DD7e37ff4e4Be4E4B4', label: 'swap transaction' }); }); it('falls back to 210000 when eth_estimateGas fails (local wallet)', async () => { @@ -6165,7 +6165,7 @@ describe('ERC-20 excessive allowance handling', () => { 8453, 0n, undefined, - { allowZero: true }, + { allowZero: true, from: '0x742d35Cc6bF4F3f4e0e3a8DD7e37ff4e4Be4E4B4', label: 'allowance-revoke transaction' }, ); expect(sendSpy).not.toHaveBeenCalled(); expect(executeBodies).toHaveLength(0); diff --git a/src/__tests__/walletconnect-signed-tx.test.js b/src/__tests__/walletconnect-signed-tx.test.js new file mode 100644 index 00000000..32b2893c --- /dev/null +++ b/src/__tests__/walletconnect-signed-tx.test.js @@ -0,0 +1,140 @@ +/** + * `trade execute` with a WalletConnect wallet that hands back a transaction + * other than the one the CLI checked. Every pre-sign check (target, intent + * binding, value, fee cap, simulation) ran on the transaction sent for signing, + * so returned bytes must never reach the execute endpoint unless they encode + * that transaction, signed by the wallet. + */ +import { describe, it, expect, vi } from 'vitest'; + +// The walletconnect CLI is a subprocess; stub it so the real send functions +// (and their checks) run. +vi.mock('child_process', () => ({ execFile: vi.fn() })); +import { execFile } from 'child_process'; + +import { signEip1559Transaction } from '../trading.js'; +import { base58Decode, base58Encode } from '../wallet.js'; +import { + ATTACKER, + APPROVE_SELECTOR, + BASE_USDC, + OUT_TOKEN, + UNLIMITED_APPROVAL_TO_ATTACKER, + erc20SwapQuote, + evmIntent, + execute, + nativeSwapQuote, + saveQuote, + solIntent, + solanaQuote, + stubNetwork, + unsignedSolanaTx, + useExecuteEnv, +} from './fixtures/execute-harness.js'; +import { + TEST_EVM_ADDRESS, + TEST_EVM_KEY, + TEST_SOL_ADDRESS, + signSolanaSlot, +} from './fixtures/remote-signers.js'; + +useExecuteEnv(); + +/** + * Stub the walletconnect CLI: `whoami` reports the wallet, `send-transaction` + * answers with `reply(payload)`. + */ +function stubWalletConnect({ accounts, reply }) { + execFile.mockImplementation((cmd, args, opts, cb) => { + if (args[0] === 'whoami') return cb(null, JSON.stringify({ connected: true, accounts }), ''); + if (args[0] === 'send-transaction') return cb(null, JSON.stringify(reply(JSON.parse(args[1]))), ''); + return cb(new Error(`unexpected walletconnect call ${args[0]}`), '', ''); + }); +} + +const WC_EVM = [{ chain: 'eip155:8453', address: TEST_EVM_ADDRESS }]; +const WC_SOL = [{ chain: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', address: TEST_SOL_ADDRESS }]; + +// The wallet picks nonce and fees; `change` rewrites what it was asked to send. +const wcSignsEvm = (change = () => ({})) => (p) => ({ + signedTransaction: signEip1559Transaction({ + chainId: 8453, nonce: 7, maxPriorityFeePerGas: 1n, maxFeePerGas: 2n, gasLimit: BigInt(p.gas), + to: p.to, value: p.value, data: p.data, ...change(p), + }, TEST_EVM_KEY), +}); +const b58 = (base64) => base58Encode(Buffer.from(base64, 'base64')); +const asBase64 = (txBase58) => Buffer.from(base58Decode(txBase58)).toString('base64'); + +describe('WalletConnect: the signed transaction must be the one that was checked', () => { + it('broadcasts an EVM swap the wallet signed as sent (control)', async () => { + const executeBodies = stubNetwork(); + stubWalletConnect({ accounts: WC_EVM, reply: wcSignsEvm() }); + const quoteId = saveQuote(nativeSwapQuote(), 'base', 'walletconnect', null, null, { swapMode: 'exactIn', request: evmIntent(TEST_EVM_ADDRESS) }); + const { err } = await execute(quoteId); + expect(err).toBeNull(); + expect(executeBodies).toHaveLength(1); + }); + + it('refuses an EVM swap with a substituted recipient, keeping SIGNED_TX_MISMATCH', async () => { + const executeBodies = stubNetwork(); + stubWalletConnect({ accounts: WC_EVM, reply: wcSignsEvm(() => ({ to: ATTACKER })) }); + const quoteId = saveQuote(nativeSwapQuote(), 'base', 'walletconnect', null, null, { swapMode: 'exactIn', request: evmIntent(TEST_EVM_ADDRESS) }); + const { err, logs } = await execute(quoteId); + expect(err).toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/swap transaction.*to is 0x0+dead.*the wallet may have/) }); + expect(executeBodies).toHaveLength(0); + expect(logs.some(l => l.includes('Trying next quote'))).toBe(false); + }); + + it('refuses an approval with a substituted spender, keeping SIGNED_TX_MISMATCH', async () => { + const executeBodies = stubNetwork(); + stubWalletConnect({ + accounts: WC_EVM, + reply: (p) => wcSignsEvm(() => (p.data.startsWith(APPROVE_SELECTOR) ? { data: UNLIMITED_APPROVAL_TO_ATTACKER } : {}))(p), + }); + const quoteId = saveQuote(erc20SwapQuote(), 'base', 'walletconnect', null, null, { + swapMode: 'exactIn', request: evmIntent(TEST_EVM_ADDRESS, { fromToken: BASE_USDC, toToken: OUT_TOKEN, amount: '1000000' }), + }); + const { err } = await execute(quoteId); + expect(err).toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/approval transaction.*data differs/) }); + expect(executeBodies).toHaveLength(0); + }); + + it('broadcasts a Solana swap the wallet signed as sent (control)', async () => { + const executeBodies = stubNetwork(); + stubWalletConnect({ accounts: WC_SOL, reply: (p) => ({ signedTransaction: b58(signSolanaSlot(asBase64(p.transaction))) }) }); + const quoteId = saveQuote(solanaQuote(unsignedSolanaTx(TEST_SOL_ADDRESS)), 'solana', 'walletconnect', null, null, { swapMode: 'exactIn', request: solIntent(TEST_SOL_ADDRESS) }); + const { err } = await execute(quoteId); + expect(err).toBeNull(); + expect(executeBodies).toHaveLength(1); + }); + + it('refuses a Solana swap whose message was substituted', async () => { + const executeBodies = stubNetwork(); + stubWalletConnect({ accounts: WC_SOL, reply: () => ({ signedTransaction: b58(signSolanaSlot(unsignedSolanaTx(TEST_SOL_ADDRESS, 9))) }) }); + const quoteId = saveQuote(solanaQuote(unsignedSolanaTx(TEST_SOL_ADDRESS)), 'solana', 'walletconnect', null, null, { swapMode: 'exactIn', request: solIntent(TEST_SOL_ADDRESS) }); + const { err } = await execute(quoteId); + expect(err).toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/swap transaction.*message bytes differ/) }); + expect(executeBodies).toHaveLength(0); + }); + + it('refuses a signature-only reply whose signature does not verify', async () => { + const executeBodies = stubNetwork(); + stubWalletConnect({ accounts: WC_SOL, reply: () => ({ signature: base58Encode(Buffer.alloc(64, 7)) }) }); + const quoteId = saveQuote(solanaQuote(unsignedSolanaTx(TEST_SOL_ADDRESS)), 'solana', 'walletconnect', null, null, { swapMode: 'exactIn', request: solIntent(TEST_SOL_ADDRESS) }); + const { err } = await execute(quoteId); + expect(err).toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/no valid signature/) }); + expect(executeBodies).toHaveLength(0); + }); + + it('broadcasts a signature-only reply with the wallet\'s valid signature (control)', async () => { + const executeBodies = stubNetwork(); + stubWalletConnect({ + accounts: WC_SOL, + reply: (p) => ({ signature: base58Encode(Buffer.from(signSolanaSlot(asBase64(p.transaction)), 'base64').subarray(1, 65)) }), + }); + const quoteId = saveQuote(solanaQuote(unsignedSolanaTx(TEST_SOL_ADDRESS)), 'solana', 'walletconnect', null, null, { swapMode: 'exactIn', request: solIntent(TEST_SOL_ADDRESS) }); + const { err } = await execute(quoteId); + expect(err).toBeNull(); + expect(executeBodies).toHaveLength(1); + }); +}); diff --git a/src/__tests__/walletconnect-trading.test.js b/src/__tests__/walletconnect-trading.test.js index 8c8701ab..a2c624f2 100644 --- a/src/__tests__/walletconnect-trading.test.js +++ b/src/__tests__/walletconnect-trading.test.js @@ -15,11 +15,34 @@ vi.mock('child_process', () => ({ import { execFile } from 'child_process'; import { getWalletConnectAddress, - sendTransactionViaWalletConnect, - sendSolanaTransactionViaWalletConnect, - sendApprovalViaWalletConnect, + sendTransactionViaWalletConnect as sendTransactionRaw, + sendSolanaTransactionViaWalletConnect as sendSolanaRaw, + sendApprovalViaWalletConnect as sendApprovalRaw, parseWcJson, } from '../walletconnect-trading.js'; +import { signEip1559Transaction } from '../trading.js'; +import { base58Encode } from '../wallet.js'; +import { TEST_EVM_ADDRESS, TEST_EVM_KEY, TEST_SOL_ADDRESS, TEST_SOL_PUBKEY_BYTES, signSolanaSlot } from './fixtures/remote-signers.js'; + +// The send functions check signed bytes against the connected wallet, so they +// take its address. Most tests here are about the subprocess call, not that +// check, so these wrappers supply the test wallet. +const sendTransactionViaWalletConnect = (txData, timeoutMs, opts = { from: TEST_EVM_ADDRESS }) => sendTransactionRaw(txData, timeoutMs, opts); +const sendSolanaTransactionViaWalletConnect = (txBase58, timeoutMs, opts = { signer: TEST_SOL_ADDRESS }) => sendSolanaRaw(txBase58, timeoutMs, opts); +const sendApprovalViaWalletConnect = (token, spender, chainId, amount, maxAllowance, opts = {}) => + sendApprovalRaw(token, spender, chainId, amount, maxAllowance, { from: TEST_EVM_ADDRESS, ...opts }); + +// An unsigned one-instruction Solana transaction (fee payer = test wallet), and +// the same transaction signed by the test wallet, both base58 as WalletConnect +// carries them. +function solanaTxBase64(blockhashByte = 3) { + return Buffer.concat([ + Buffer.from([1]), Buffer.alloc(64), + Buffer.from([1, 0, 1, 2]), TEST_SOL_PUBKEY_BYTES, Buffer.alloc(32, 2), Buffer.alloc(32, blockhashByte), Buffer.from([1, 1, 1, 0, 1, 0]), + ]).toString('base64'); +} +const TX_B58 = base58Encode(Buffer.from(solanaTxBase64(), 'base64')); +const SIGNED_B58 = base58Encode(Buffer.from(signSolanaSlot(solanaTxBase64()), 'base64')); function mockExecFile(stdout, err = null) { execFile.mockImplementation((cmd, args, opts, cb) => { @@ -287,16 +310,60 @@ describe('sendTransactionViaWalletConnect', () => { expect(payload.chainId).toBe('eip155:10'); }); + // The wallet chooses nonce and fees (and gas when none is sent); the rest must be what was sent. + const signedByWallet = (overrides = {}, key = TEST_EVM_KEY) => signEip1559Transaction({ + chainId: 1, nonce: '0x9', maxPriorityFeePerGas: '0x1', maxFeePerGas: '0x2', gasLimit: '0x5208', + to: '0x1234567890123456789012345678901234567890', value: '0x0', data: '0x', ...overrides, + }, key); + const sentTx = { to: '0x1234567890123456789012345678901234567890', value: '0', chainId: 1 }; + it('handles signedTransaction response', async () => { - mockExecFile(JSON.stringify({ signedTransaction: '0xf86c...' })); + const signed = signedByWallet(); + mockExecFile(JSON.stringify({ signedTransaction: signed })); - const result = await sendTransactionViaWalletConnect({ - to: '0x1234567890123456789012345678901234567890', - value: '0', - chainId: 1, - }); + const result = await sendTransactionViaWalletConnect(sentTx); + + expect(result).toEqual({ signedTransaction: signed }); + }); + + it.each([ + ['a different recipient', { to: '0x000000000000000000000000000000000000dead' }, /to is 0x0+dead/], + ['a different value', { value: '0x1' }, /value is 1, expected 0/], + ['calldata added', { data: '0xa9059cbb' }, /data differs/], + ['a different chain', { chainId: 8453 }, /chainId is 8453, expected 1/], + ])('refuses a signedTransaction with %s, keeping its own error code', async (_name, change, message) => { + mockExecFile(JSON.stringify({ signedTransaction: signedByWallet(change) })); + + const err = await sendTransactionViaWalletConnect(sentTx, undefined, { from: TEST_EVM_ADDRESS, label: 'swap transaction' }).catch(e => e); + + expect(err).toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(message) }); + expect(err.message).toMatch(/the wallet may have; check the wallet's activity before retrying/); + }); + + it('refuses a signedTransaction whose gas limit differs from the gas sent', async () => { + mockExecFile(JSON.stringify({ signedTransaction: signedByWallet({ gasLimit: '0x7530' }) })); - expect(result).toEqual({ signedTransaction: '0xf86c...' }); + await expect(sendTransactionViaWalletConnect({ ...sentTx, gas: 210000 })) + .rejects.toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/gasLimit is 30000, expected 210000/) }); + }); + + it('accepts any gas limit when no gas was sent', async () => { + const signed = signedByWallet({ gasLimit: '0x7530' }); + mockExecFile(JSON.stringify({ signedTransaction: signed })); + + await expect(sendTransactionViaWalletConnect(sentTx)).resolves.toEqual({ signedTransaction: signed }); + }); + + it('refuses a signedTransaction from another key', async () => { + mockExecFile(JSON.stringify({ signedTransaction: signedByWallet({}, '22'.repeat(32)) })); + + await expect(sendTransactionViaWalletConnect(sentTx)).rejects.toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/signed by 0x/) }); + }); + + it('requires the wallet address it checks signed bytes against', async () => { + await expect(sendTransactionRaw(sentTx)).rejects.toThrow(/wallet address \(from\) is required/); + await expect(sendSolanaRaw(TX_B58)).rejects.toThrow(/wallet address \(signer\) is required/); + expect(execFile).not.toHaveBeenCalled(); }); it('handles status messages before JSON output', async () => { @@ -440,11 +507,11 @@ describe('sendApprovalViaWalletConnect', () => { describe('sendSolanaTransactionViaWalletConnect', () => { it('sends correct payload and returns signedTransaction', async () => { - mockExecFile(JSON.stringify({ signedTransaction: '5K4Ld...' })); + mockExecFile(JSON.stringify({ signedTransaction: SIGNED_B58 })); - const result = await sendSolanaTransactionViaWalletConnect('3Bxs3z...'); + const result = await sendSolanaTransactionViaWalletConnect(TX_B58); - expect(result).toEqual({ signedTransaction: '5K4Ld...' }); + expect(result).toEqual({ signedTransaction: SIGNED_B58 }); // Verify the command arguments expect(execFile).toHaveBeenCalledWith( @@ -456,56 +523,70 @@ describe('sendSolanaTransactionViaWalletConnect', () => { // Verify the JSON payload const payload = JSON.parse(execFile.mock.calls[0][1][1]); - expect(payload.transaction).toBe('3Bxs3z...'); + expect(payload.transaction).toBe(TX_B58); expect(payload.chainId).toBe('solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp'); }); + it('refuses a signed transaction whose message differs from the one sent', async () => { + const other = base58Encode(Buffer.from(signSolanaSlot(solanaTxBase64(9)), 'base64')); + mockExecFile(JSON.stringify({ signedTransaction: other })); + + await expect(sendSolanaTransactionViaWalletConnect(TX_B58, undefined, { signer: TEST_SOL_ADDRESS, label: 'swap transaction' })) + .rejects.toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/swap transaction.*message bytes differ/) }); + }); + + it('refuses the sent transaction returned without a valid wallet signature', async () => { + mockExecFile(JSON.stringify({ transaction: TX_B58 })); + + await expect(sendSolanaTransactionViaWalletConnect(TX_B58)).rejects.toMatchObject({ code: 'SIGNED_TX_MISMATCH', message: expect.stringMatching(/no valid signature/) }); + }); + it('returns signature when wallet returns signature only', async () => { mockExecFile(JSON.stringify({ signature: '4vJ9...' })); - const result = await sendSolanaTransactionViaWalletConnect('3Bxs3z...'); + const result = await sendSolanaTransactionViaWalletConnect(TX_B58); expect(result).toEqual({ signature: '4vJ9...' }); }); it('returns signedTransaction when wallet returns transaction field', async () => { - mockExecFile(JSON.stringify({ transaction: '5abc...' })); + mockExecFile(JSON.stringify({ transaction: SIGNED_B58 })); - const result = await sendSolanaTransactionViaWalletConnect('3Bxs3z...'); + const result = await sendSolanaTransactionViaWalletConnect(TX_B58); - expect(result).toEqual({ signedTransaction: '5abc...' }); + expect(result).toEqual({ signedTransaction: SIGNED_B58 }); }); it('throws on timeout', async () => { mockExecFile('', new Error('Command timed out')); - await expect(sendSolanaTransactionViaWalletConnect('3Bxs3z...')).rejects.toThrow('Command timed out'); + await expect(sendSolanaTransactionViaWalletConnect(TX_B58)).rejects.toThrow('Command timed out'); }); it('throws when no JSON output', async () => { mockExecFile('Some non-JSON output'); - await expect(sendSolanaTransactionViaWalletConnect('3Bxs3z...')).rejects.toThrow('No JSON output'); + await expect(sendSolanaTransactionViaWalletConnect(TX_B58)).rejects.toThrow('No JSON output'); }); it('parses multi-line JSON output from walletconnect', async () => { - const multiLineJson = 'Connecting to wallet...\n{\n "signedTransaction": "5K4Ld..."\n}'; + const multiLineJson = `Connecting to wallet...\n{\n "signedTransaction": "${SIGNED_B58}"\n}`; mockExecFile(multiLineJson); - const result = await sendSolanaTransactionViaWalletConnect('3Bxs3z...'); - expect(result).toEqual({ signedTransaction: '5K4Ld...' }); + const result = await sendSolanaTransactionViaWalletConnect(TX_B58); + expect(result).toEqual({ signedTransaction: SIGNED_B58 }); }); it('throws when unexpected response', async () => { mockExecFile(JSON.stringify({ unexpected: true })); - await expect(sendSolanaTransactionViaWalletConnect('3Bxs3z...')).rejects.toThrow('Unexpected response'); + await expect(sendSolanaTransactionViaWalletConnect(TX_B58)).rejects.toThrow('Unexpected response'); }); it('uses custom timeout', async () => { - mockExecFile(JSON.stringify({ signedTransaction: '5K4Ld...' })); + mockExecFile(JSON.stringify({ signedTransaction: SIGNED_B58 })); - await sendSolanaTransactionViaWalletConnect('3Bxs3z...', 60000); + await sendSolanaTransactionViaWalletConnect(TX_B58, 60000); expect(execFile).toHaveBeenCalledWith( 'walletconnect', @@ -527,7 +608,7 @@ describe('WalletConnect sends mark every failure as an ambiguous handoff', () => const sends = [ ['sendTransactionViaWalletConnect', () => sendTransactionViaWalletConnect({ to: '0xabc', data: '0x', value: '0', gas: '21000', chainId: 8453 })], - ['sendSolanaTransactionViaWalletConnect', () => sendSolanaTransactionViaWalletConnect('3Bxs3z...')], + ['sendSolanaTransactionViaWalletConnect', () => sendSolanaTransactionViaWalletConnect(TX_B58)], ['sendApprovalViaWalletConnect', () => sendApprovalViaWalletConnect('0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', '0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae', 8453, 1000n)], ]; diff --git a/src/limit-order.js b/src/limit-order.js index 53df2ab3..67a0775b 100644 --- a/src/limit-order.js +++ b/src/limit-order.js @@ -405,7 +405,7 @@ export async function signTransaction(txBase64, walletType, walletInfo, { signer // WC expects base58 for Solana transactions const txBytes = Buffer.from(txBase64, 'base64'); const txBase58 = base58Encode(txBytes); - const result = await sendSolanaTransactionViaWalletConnect(txBase58); + const result = await sendSolanaTransactionViaWalletConnect(txBase58, undefined, { signer, label }); if (result.signedTransaction) { // WC returns base58; convert to base64 const signedBytes = base58Decode(result.signedTransaction); diff --git a/src/trading.js b/src/trading.js index c61e8174..9859286a 100644 --- a/src/trading.js +++ b/src/trading.js @@ -18,6 +18,7 @@ import { getWalletConnectAddress, sendTransactionViaWalletConnect, sendSolanaTra import { retrievePassword } from './keychain.js'; import { validateQuoteInput, validateBalance, resolvePercentAmount, validateGasBalance, encodeApproveCalldata, assertValidApprovalSpender, assertQuoteMatchesRequest, assertSwapCalldataNotBareTransfer, assertSwapOutcome, assertSolanaInstructionsSafe, checkSolanaFeeBalance, assertSolanaSwapOutcome, approvalAmountForSwap, needsAllowanceRevoke, OVERSIZED_ALLOWANCE_MULTIPLIER, EVM_BRIDGE_NATIVE_FEE_SLACK, isBridgeRequest, nativeValueMismatch, quoteInputAmountRaw } from './trade-validation.js'; import { readCompactU16 } from './solana-tx.js'; +import { assertSolanaSignedMatches } from './signed-tx-binding.js'; import { formatPlan, guardExecution, resolveExecuteGuard } from './execute-guard.js'; export { readCompactU16 }; import { CHAIN_RPCS } from './rpc-urls.js'; @@ -4348,7 +4349,7 @@ EXAMPLES: throw new Error(`Failed to encode transaction for WalletConnect: ${err.message}`, { cause: err }); } swapHandedOff = true; - const wcResult = await sendSolanaTransactionViaWalletConnect(txBase58); + const wcResult = await sendSolanaTransactionViaWalletConnect(txBase58, undefined, { signer: solanaWalletAddress, label: 'swap transaction' }); if (wcResult.signedTransaction) { signedTransaction = base58Decode(wcResult.signedTransaction).toString('base64'); @@ -4375,6 +4376,9 @@ EXAMPLES: // Inject into the first signature slot (feePayer) sigBytes.copy(txBytes, sigCountSize); signedTransaction = txBytes.toString('base64'); + // The message is ours by construction; the signature is the + // wallet's claim. Refuse one that does not verify. + assertSolanaSignedMatches(txBase64, signedTransaction, { signer: solanaWalletAddress, label: 'swap transaction' }); } else { throw new Error('WalletConnect returned neither signedTransaction nor signature'); } @@ -4491,7 +4495,7 @@ EXAMPLES: chainConfig.chainId, 0n, undefined, - { allowZero: true }, + { allowZero: true, from: wcAddress, label: 'allowance-revoke transaction' }, ); revokeTxHash = revokeResult.txHash; if (revokeTxHash) ancillaryHandedOff = true; @@ -4559,6 +4563,7 @@ EXAMPLES: chainConfig.chainId, approveAmt, approvalCapForQuote(quoteData), + { from: wcAddress, label: 'approval transaction' }, ); approvalTxHash = approvalResult.txHash; if (approvalTxHash) ancillaryHandedOff = true; @@ -4679,8 +4684,12 @@ EXAMPLES: value: txData.value || '0', gas: String(finalGas), chainId: chainConfig.chainId, - }); + }, undefined, { from: wcAddress, label: 'swap transaction' }); } catch (wcErr) { + // The wallet returned a transaction other than the one checked: + // keep that error (already terminal, and it says the wallet may + // have sent it) instead of the generic ambiguous one below. + if (wcErr?.code === 'SIGNED_TX_MISMATCH') throw wcErr; // The wallet was already asked to send, and wcExec rejects with a // bare Error(err.message) for EVERY failure — a user rejection, a // 120s approval timeout and a spawn failure are indistinguishable diff --git a/src/transfer.js b/src/transfer.js index d5b9ef77..e0e82940 100644 --- a/src/transfer.js +++ b/src/transfer.js @@ -1113,7 +1113,7 @@ async function sendTokensViaWalletConnect({ to, amount, chain, token, max, dryRu value: txValue, gas: gasLimit, chainId, - }); + }, undefined, { from: wcAddress, label: 'transfer transaction' }); const txHash = await (async () => { if (wcResult.txHash) return wcResult.txHash; diff --git a/src/walletconnect-trading.js b/src/walletconnect-trading.js index 175b989c..32870255 100644 --- a/src/walletconnect-trading.js +++ b/src/walletconnect-trading.js @@ -9,11 +9,15 @@ */ import { wcExec } from './walletconnect-exec.js'; -import { base58Encode } from './wallet.js'; +import { base58Decode, base58Encode } from './wallet.js'; import { encodeApproveCalldata } from './trade-validation.js'; +import { assertEvmSignedMatches, assertSolanaSignedMatches } from './signed-tx-binding.js'; const SOLANA_MAINNET_CHAIN = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp'; +// A wallet asked to send-transaction may also have broadcast what it returned. +const WALLET_MAY_HAVE_SENT = 'The CLI did not broadcast it, but the wallet may have; check the wallet\'s activity before retrying.'; + /** * Extract the first JSON object from walletconnect CLI output. * The CLI may print status messages before the JSON result, and may @@ -140,11 +144,21 @@ async function markBroadcastAmbiguous(fn) { * The connected wallet signs and may broadcast the transaction. * Returns either { txHash } (wallet broadcast) or { signedTransaction } (we broadcast). * + * Signed bytes are checked before they are returned: sender, chain id, `to`, + * `value`, `data` and, when `gas` was sent, the gas limit must be what was + * sent (the wallet chooses nonce and fees). Otherwise throws + * SIGNED_TX_MISMATCH, so a caller never broadcasts a + * transaction other than the one it checked. + * * @param {object} txData - Transaction data: { to, data, value, gas, chainId } * @param {number} [timeoutMs=120000] - Timeout for user approval + * @param {object} opts + * @param {string} opts.from - the connected wallet's address + * @param {string} [opts.label] - what the transaction is, for errors * @returns {{ txHash?: string, signedTransaction?: string }} */ -export async function sendTransactionViaWalletConnect(txData, timeoutMs = 120000) { +export async function sendTransactionViaWalletConnect(txData, timeoutMs = 120000, { from, label } = {}) { + if (!from) throw new Error('sendTransactionViaWalletConnect: the wallet address (from) is required to check a signed transaction'); // The walletconnect CLI expects chainId as "eip155:" string format const chainId = txData.chainId ? (String(txData.chainId).startsWith('eip155:') ? txData.chainId : `eip155:${txData.chainId}`) @@ -158,16 +172,28 @@ export async function sendTransactionViaWalletConnect(txData, timeoutMs = 120000 chainId, }; - return markBroadcastAmbiguous(async () => { + const result = await markBroadcastAmbiguous(async () => { const output = await wcExec('walletconnect', ['send-transaction', JSON.stringify(payload)], timeoutMs); - const result = parseWcJson(output); + const parsed = parseWcJson(output); - if (result.transactionHash) return { txHash: result.transactionHash }; - if (result.txHash) return { txHash: result.txHash }; - if (result.signedTransaction) return { signedTransaction: result.signedTransaction }; + if (parsed.transactionHash) return { txHash: parsed.transactionHash }; + if (parsed.txHash) return { txHash: parsed.txHash }; + if (parsed.signedTransaction) return { signedTransaction: parsed.signedTransaction }; throw new Error('Unexpected response from walletconnect send-transaction'); }); + + // Checked outside markBroadcastAmbiguous so the error keeps its own code. + if (result.signedTransaction) { + assertEvmSignedMatches(result.signedTransaction, { + chainId: String(chainId ?? '').replace(/^eip155:/, '') || undefined, + to: payload.to, + value: payload.value, + data: payload.data, + ...(payload.gas !== undefined && { gasLimit: payload.gas }), + }, { from, label, note: WALLET_MAY_HAVE_SENT }); + } + return result; } /** @@ -184,9 +210,11 @@ export async function sendTransactionViaWalletConnect(txData, timeoutMs = 120000 * @param {bigint|string|number} [maxAllowance] - Hard cap from persisted request intent * @param {object} [opts] * @param {boolean} [opts.allowZero=false] - Allow a zero-amount revoke approval + * @param {string} opts.from - the connected wallet's address (see sendTransactionViaWalletConnect) + * @param {string} [opts.label] - what the transaction is, for errors * @returns {{ txHash?: string, signedTransaction?: string }} */ -export async function sendApprovalViaWalletConnect(tokenAddress, spenderAddress, chainId, amount, maxAllowance, { allowZero = false } = {}) { +export async function sendApprovalViaWalletConnect(tokenAddress, spenderAddress, chainId, amount, maxAllowance, { allowZero = false, from, label = 'approval transaction' } = {}) { // encodeApproveCalldata enforces a valid 20-byte spender, a bounded (< MAX) // amount within the request cap, and exactly-68-byte calldata — so a // malformed or tampered spender/amount can't reshape the ABI word layout. @@ -198,7 +226,7 @@ export async function sendApprovalViaWalletConnect(tokenAddress, spenderAddress, value: '0', gas: '100000', chainId, - }); + }, undefined, { from, label }); } /** @@ -208,11 +236,20 @@ export async function sendApprovalViaWalletConnect(tokenAddress, spenderAddress, * - { signedTransaction: "" } — full signed transaction * - { signature: "" } — raw Ed25519 signature only * + * A full signed transaction is checked before it is returned: same message, + * valid signature from `signer`. Otherwise throws SIGNED_TX_MISMATCH. A bare + * signature is returned as is; the caller places it in the transaction it + * sent and checks the result. + * * @param {string} txBase58 - Base58-encoded Solana transaction * @param {number} [timeoutMs=120000] - Timeout for user approval + * @param {object} opts + * @param {string} opts.signer - the connected wallet's base58 address + * @param {string} [opts.label] - what the transaction is, for errors * @returns {{ signedTransaction?: string, signature?: string }} */ -export async function sendSolanaTransactionViaWalletConnect(txBase58, timeoutMs = 120000) { +export async function sendSolanaTransactionViaWalletConnect(txBase58, timeoutMs = 120000, { signer, label } = {}) { + if (!signer) throw new Error('sendSolanaTransactionViaWalletConnect: the wallet address (signer) is required to check a signed transaction'); const payload = { transaction: txBase58, chainId: SOLANA_MAINNET_CHAIN, @@ -221,17 +258,29 @@ export async function sendSolanaTransactionViaWalletConnect(txBase58, timeoutMs // Marked ambiguous for the same reason as the EVM send: this goes out over the // CLI's `send-transaction` verb, so a wallet that signs-and-sends has already // broadcast by the time a timeout or an unreadable reply reaches us. - return markBroadcastAmbiguous(async () => { + const result = await markBroadcastAmbiguous(async () => { const output = await wcExec('walletconnect', ['send-transaction', JSON.stringify(payload)], timeoutMs); - const result = parseWcJson(output); + const parsed = parseWcJson(output); - if (result.signedTransaction) return { signedTransaction: result.signedTransaction }; - if (result.signature) return { signature: result.signature }; + if (parsed.signedTransaction) return { signedTransaction: parsed.signedTransaction }; + if (parsed.signature) return { signature: parsed.signature }; // Some wallets (e.g. Phantom) return 'transaction' instead of 'signedTransaction' - if (result.transaction) return { signedTransaction: result.transaction }; + if (parsed.transaction) return { signedTransaction: parsed.transaction }; throw new Error('Unexpected response from walletconnect Solana sign'); }); + + // Checked outside markBroadcastAmbiguous so the error keeps its own code. + if (result.signedTransaction) { + let signedBase64; + try { + signedBase64 = base58Decode(result.signedTransaction).toString('base64'); + } catch { + signedBase64 = ''; + } + assertSolanaSignedMatches(base58Decode(txBase58).toString('base64'), signedBase64, { signer, label, note: WALLET_MAY_HAVE_SENT }); + } + return result; } /**