// End-to-end tests of SanarioMultisig in an in-process EVM (@ethereumjs/vm). // Signatures are produced with viem's signTypedData, i.e. exactly what a // browser wallet / Ledger / Trezor returns for the app's EIP-712 request. import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import { createVM } from '@ethereumjs/vm'; import { createAccount, createAddressFromString } from '@ethereumjs/util'; import { encodeFunctionData, decodeFunctionResult, encodeDeployData, hexToBytes, bytesToHex, parseEther, decodeErrorResult } from 'viem'; import { privateKeyToAccount, generatePrivateKey } from 'viem/accounts'; const artifact = JSON.parse(fs.readFileSync(new URL('../lib/eth/artifact.json', import.meta.url))); const { abi } = artifact; const CHAIN_ID = 1; const types = { Transaction: [ { name: 'to', type: 'address' }, { name: 'value', type: 'uint256' }, { name: 'data', type: 'bytes' }, { name: 'nonce', type: 'uint256' }, ], }; async function setup(n = 3, m = 2) { const vm = await createVM(); const owners = Array.from({ length: n }, () => privateKeyToAccount(generatePrivateKey())) .sort((a, b) => (a.address.toLowerCase() < b.address.toLowerCase() ? -1 : 1)); const relayer = privateKeyToAccount(generatePrivateKey()); for (const a of [...owners, relayer]) { await vm.stateManager.putAccount(createAddressFromString(a.address), createAccount({ balance: parseEther('100') })); } const call = async (from, to, data, value = 0n) => { const r = await vm.evm.runCall({ caller: createAddressFromString(from), to: to ? createAddressFromString(to) : undefined, data: hexToBytes(data), value, gasLimit: 10_000_000n, }); return { error: r.execResult.exceptionError, ret: bytesToHex(r.execResult.returnValue), created: r.createdAddress?.toString() }; }; const dep = await call(relayer.address, undefined, encodeDeployData({ abi, bytecode: artifact.bytecode, args: [owners.map((o) => o.address), BigInt(m)] })); assert.equal(dep.error, undefined, 'deploy failed'); const wallet = dep.created; const read = async (fn, args = []) => { const r = await call(relayer.address, wallet, encodeFunctionData({ abi, functionName: fn, args })); return decodeFunctionResult({ abi, functionName: fn, data: r.ret }); }; const sign = (owner, msg) => owner.signTypedData({ domain: { name: 'Sanario Multisig', version: '1', chainId: CHAIN_ID, verifyingContract: wallet }, types, primaryType: 'Transaction', message: msg, }); const execute = async (msg, signers, sigs, from = relayer.address) => { const r = await call(from, wallet, encodeFunctionData({ abi, functionName: 'execute', args: [msg.to, msg.value, msg.data, signers, sigs] })); let err; if (r.error) { try { err = decodeErrorResult({ abi, data: r.ret }).errorName; } catch { err = r.error.error || 'revert'; } } return err; }; const balance = async (addr) => (await vm.stateManager.getAccount(createAddressFromString(addr)))?.balance ?? 0n; return { vm, owners, relayer, wallet, call, read, sign, execute, balance }; } test('deploys with owners and threshold', async () => { const t = await setup(3, 2); assert.equal(await t.read('threshold'), 2n); assert.deepEqual((await t.read('getOwners')).map((a) => a.toLowerCase()), t.owners.map((o) => o.address.toLowerCase())); }); test('2-of-3: one signature is not enough, two move funds, replay fails', async () => { const t = await setup(3, 2); await t.call(t.relayer.address, t.wallet, '0x', parseEther('5')); // deposit assert.equal(await t.balance(t.wallet), parseEther('5')); const dest = privateKeyToAccount(generatePrivateKey()).address; const msg = { to: dest, value: parseEther('1'), data: '0x', nonce: 0n }; const [a, b] = t.owners; const sa = await t.sign(a, msg), sb = await t.sign(b, msg); assert.equal(await t.execute(msg, [a.address], [sa]), 'NotEnoughApprovals'); assert.equal(await t.execute(msg, [b.address, a.address], [sb, sa]), 'SignerOrder'); assert.equal(await t.execute(msg, [a.address, a.address], [sa, sa]), 'SignerOrder'); assert.equal(await t.execute(msg, [a.address, b.address], [sa, sb]), undefined); assert.equal(await t.balance(dest), parseEther('1')); assert.equal(await t.read('nonce'), 1n); assert.equal(await t.execute(msg, [a.address, b.address], [sa, sb]), 'InvalidSignature'); // nonce moved on }); test('non-owner signature and tampered amount are rejected', async () => { const t = await setup(3, 2); await t.call(t.relayer.address, t.wallet, '0x', parseEther('5')); const dest = t.relayer.address; const msg = { to: dest, value: parseEther('1'), data: '0x', nonce: 0n }; const outsider = privateKeyToAccount(generatePrivateKey()); const [a, b] = t.owners; const signers = [a.address, outsider.address].sort((x, y) => (x.toLowerCase() < y.toLowerCase() ? -1 : 1)); const sigs = await Promise.all(signers.map((s) => t.sign(s === a.address ? a : outsider, msg))); assert.equal(await t.execute(msg, signers, sigs), 'InvalidOwner'); const sa = await t.sign(a, msg), sb = await t.sign(b, msg); assert.equal(await t.execute({ ...msg, value: parseEther('4') }, [a.address, b.address], [sa, sb]), 'InvalidSignature'); }); test('on-chain approveHash and msg.sender count as approvals', async () => { const t = await setup(3, 2); await t.call(t.relayer.address, t.wallet, '0x', parseEther('5')); const msg = { to: t.relayer.address, value: parseEther('2'), data: '0x', nonce: 0n }; const [a, b] = t.owners; const hash = await t.read('getTransactionHash', [msg.to, msg.value, msg.data, msg.nonce]); await t.call(a.address, t.wallet, encodeFunctionData({ abi, functionName: 'approveHash', args: [hash] })); // b submits the tx itself, so needs no signature either assert.equal(await t.execute(msg, [a.address, b.address], ['0x', '0x'], b.address), undefined); assert.equal(await t.read('nonce'), 1n); }); test('owner management requires the multisig itself', async () => { const t = await setup(3, 2); const newOwner = privateKeyToAccount(generatePrivateKey()).address; const r = await t.call(t.owners[0].address, t.wallet, encodeFunctionData({ abi, functionName: 'addOwner', args: [newOwner, 2n] })); assert.ok(r.error, 'direct call must revert'); const data = encodeFunctionData({ abi, functionName: 'addOwner', args: [newOwner, 3n] }); const msg = { to: t.wallet, value: 0n, data, nonce: 0n }; const [a, , c] = t.owners; assert.equal(await t.execute(msg, [a.address, c.address], [await t.sign(a, msg), await t.sign(c, msg)]), undefined); assert.equal(await t.read('threshold'), 3n); assert.equal((await t.read('getOwners')).length, 4); assert.equal(await t.read('isOwner', [newOwner]), true); }); test('constructor rejects bad configs', async () => { const vm = await createVM(); const a = privateKeyToAccount(generatePrivateKey()).address; const deploy = async (owners, m) => (await vm.evm.runCall({ caller: createAddressFromString(a), data: hexToBytes(encodeDeployData({ abi, bytecode: artifact.bytecode, args: [owners, m] })), gasLimit: 10_000_000n, })).execResult.exceptionError; assert.ok(await deploy([a], 0n)); assert.ok(await deploy([a], 2n)); assert.ok(await deploy([a, a], 1n)); assert.ok(await deploy(['0x0000000000000000000000000000000000000000'], 1n)); assert.equal(await deploy([a], 1n), undefined); }); // ------------------------------------------------ signer / threshold changes import { planSignerChange, applyPlan } from '../lib/eth/signers.ts'; const byAddr = (a, b) => (a.address.toLowerCase() < b.address.toLowerCase() ? -1 : 1); /** Execute every planned op, each approved by exactly `threshold` of the owners in force at that moment. */ async function runPlan(t, accounts, plan) { let nonce = await t.read('nonce'); for (const op of plan) { const onchain = (await t.read('getOwners')).map((a) => a.toLowerCase()); const need = Number(await t.read('threshold')); const signers = accounts.filter((a) => onchain.includes(a.address.toLowerCase())).sort(byAddr).slice(0, need); const args = op.args.map((x) => (typeof x === 'number' ? BigInt(x) : x)); const msg = { to: t.wallet, value: 0n, data: encodeFunctionData({ abi, functionName: op.fn, args }), nonce }; // one approval short must fail if (need > 1) assert.equal(await t.execute(msg, signers.slice(1).map((s) => s.address), await Promise.all(signers.slice(1).map((s) => t.sign(s, msg)))), 'NotEnoughApprovals'); const err = await t.execute(msg, signers.map((s) => s.address), await Promise.all(signers.map((s) => t.sign(s, msg)))); assert.equal(err, undefined, `${op.fn}(${op.args}) failed: ${err}`); nonce++; } } const CASES = [ ['3-of-5 → 4-of-5 (threshold only)', 5, 3, { keep: 5, add: 0, m: 4 }, 1], ['5-of-5 → 3-of-5 (threshold only)', 5, 5, { keep: 5, add: 0, m: 3 }, 1], ['2-of-3 → 3-of-5 (add two)', 3, 2, { keep: 3, add: 2, m: 3 }, 2], ['3-of-5 → 2-of-3 (remove two)', 5, 3, { keep: 3, add: 0, m: 2 }, 2], ['5-of-5 → 2-of-2 (remove three, quorum must fall)', 5, 5, { keep: 2, add: 0, m: 2 }, 3], ['2-of-3 → 2-of-3 (replace a lost key)', 3, 2, { keep: 2, add: 1, m: 2 }, 1], ['2-of-3 → 4-of-6 (replace one, add three)', 3, 2, { keep: 2, add: 4, m: 4 }, 4], ['4-of-7 → 3-of-4 (replace two, remove three)', 7, 4, { keep: 2, add: 2, m: 3 }, 5], ]; for (const [label, n, m, target, steps] of CASES) { test(`signer change ${label}`, async () => { const t = await setup(n, m); const fresh = Array.from({ length: target.add }, () => privateKeyToAccount(generatePrivateKey())); const targetAccounts = [...t.owners.slice(0, target.keep), ...fresh]; const plan = planSignerChange(t.owners.map((o) => o.address), m, targetAccounts.map((a) => a.address), target.m); assert.equal(plan.length, steps, JSON.stringify(plan)); const expected = applyPlan(t.owners.map((o) => o.address), m, plan); assert.equal(expected.threshold, target.m); await runPlan(t, [...t.owners, ...fresh], plan); const onchain = (await t.read('getOwners')).map((a) => a.toLowerCase()).sort(); assert.deepEqual(onchain, targetAccounts.map((a) => a.address.toLowerCase()).sort()); assert.equal(await t.read('threshold'), BigInt(target.m)); // removed owners can no longer approve for (const gone of t.owners.slice(target.keep)) assert.equal(await t.read('isOwner', [gone.address]), false); }); } test('signer change: planner rejects bad targets', () => { const a = '0x' + '11'.repeat(20), b = '0x' + '22'.repeat(20); assert.throws(() => planSignerChange([a, b], 2, [a, b], 3), /between 1 and 2/); assert.throws(() => planSignerChange([a, b], 2, [a, a], 1), /twice/); assert.throws(() => planSignerChange([a, b], 2, [], 1), /at least one/); assert.throws(() => planSignerChange([a, b], 2, [a, '0x1234'], 1), /valid address/); assert.deepEqual(planSignerChange([a, b], 2, [b, a], 2), []); });