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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/privy-signed-tx-binding.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/walletconnect-signed-tx-binding.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions docs/error-codes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
175 changes: 175 additions & 0 deletions src/__tests__/fixtures/execute-harness.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
/**
* 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);
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 (isPrivy && opts?.method === 'GET') {
return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'w', address: privyAddress }) });
}
if (isPrivy && 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 <quoteId>`; 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 };
}
67 changes: 67 additions & 0 deletions src/__tests__/fixtures/remote-signers.js
Original file line number Diff line number Diff line change
@@ -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));
}
34 changes: 34 additions & 0 deletions src/__tests__/limit-order.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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', () => {
Expand Down
Loading
Loading