Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@ Everything below runs offline, with no deployed contracts, except three fork sui
|---|---|---|
| Contracts: unit, fuzz, E2E, upgrade, deploy-script, handover and 21 invariants | 768 | `forge test` |
| Oracle | 1328 | `cd oracle && node --test` |
| SDK | 369 | `cd packages/sdk && npx vitest run` |
| SDK | 371 | `cd packages/sdk && npx vitest run` |

Counts are individual tests as measured on 5 November 2026, so each of the 21 invariants counts once. Without a fork URL, 756 of the contract tests run and 12 skip. Run after `npm run build`, 352 of the SDK's 361 pass and 9 skip: the 8 integration tests, which need a live deployment, and one check that runs only in CI. Without a build, the 9 built-package tests skip too. Vitest strips types without checking them, so `npm run typecheck` in `packages/sdk` checks the tests against the SDK's types as well as the sources. [`scripts/mutation`](scripts/mutation/README.md) holds the harnesses that measure whether these tests would catch a deliberate break in the contracts or deploy scripts.

Expand Down
2 changes: 1 addition & 1 deletion docs/adr/0009-payments-on-base.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,5 +280,5 @@ Open before it could go `on`, and none of it matters in shadow:
- **The SDK's evidence check.** The leaf is closed in 1.0.0-alpha.17: `evidenceLeaf` builds the six-word leaf and
`sigvara_verify_evidence` keeps `chainId`. Versions before it report a good root with a chain's payment in it as a
mismatch. In 1.0.0-alpha.17 the tool still fails on an agent with a long payment history, because it confirms up to
100 payments at a pace the public RPC refuses. The explorer's check does not.
100 payments at a pace the public RPC refuses. 1.0.0-alpha.18 confirms them in one read through Multicall3. The explorer's check does not.
- **Mainnet.** Its chain id, RPC and contracts are published at launch, and decision 1's testnet-only posture holds.
2 changes: 1 addition & 1 deletion docs/payment-backed-attestations.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ the published roots were made with (`oracle/merkle.js`). The explorer rebuilds b
SDK's `evidenceLeaf` and `sigvara_verify_evidence` in `sigvara-mcp`, from 1.0.0-alpha.17. Earlier
versions rebuild only the five-word leaf, so they report a good root with such a payment in it as
a mismatch. In 1.0.0-alpha.17 the tool can still fail on a long payment history, when the public
RPC refuses its calls.
RPC refuses its calls. 1.0.0-alpha.18 confirms them in one read through Multicall3.

Its payer can sign an outcome too, in the same typed data with that chain's id in the domain, and the
request names the chain as `payment.chainId` (ADR 0009, section 7). The outcome goes into the leaf as
Expand Down
2 changes: 1 addition & 1 deletion docs/simulation.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ The explorer's evidence check reads these payments: at 03:13 UTC it rebuilt all
served root. The SDK's `evidenceLeaf` builds the same leaf from 1.0.0-alpha.17, published that morning.
Before it, `sigvara_verify_evidence` reported this agent's served root as differing, read against the live
list at 03:13 UTC as one leaf of 61. In 1.0.0-alpha.17 that tool still fails on this agent, with `Could not
read the chain`: it confirms up to 100 payments at a pace the public RPC refuses. That says nothing about
read the chain`: it confirms up to 100 payments at a pace the public RPC refuses. 1.0.0-alpha.18 confirms them in one read through Multicall3. That says nothing about
the agent.

## Running it
Expand Down
2 changes: 1 addition & 1 deletion docs/whitepaper.md
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ apply to a fresh deployment, not to the testnet.

**Test coverage**, as of 6 November 2026: 768 contract tests across 34 Foundry test files
including fuzz and invariant tests (three fork suites need an RPC, and the twelve in
`SplitAuthorityFork` skip without `--fork-url`), 1328 oracle tests and 369 in the SDK (9 skip
`SplitAuthorityFork` skip without `--fork-url`), 1328 oracle tests and 371 in the SDK (9 skip
outside CI and without a live deployment; every test that runs passes). CI runs Foundry, the oracle and
SDK suites, and Slither static analysis on every push, plus a documentation check that
fails when the site states something the contracts do not.
Expand Down
13 changes: 13 additions & 0 deletions packages/sdk/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
# Changelog

## 1.0.0-alpha.18

### Fixed: `sigvara_verify_evidence` on an agent with a long payment history

The tool asked the reputation contract's `verifyEvidence` about each covered payment in a separate call, up to 100
of them, eight at a time. Arc's public RPC limits calls a second, and on 7 November 2026 it refused the 29th within a
second with "rate limit exceeded". One refusal failed the whole check, so the tool failed on every agent with a long
payment history, on both public RPCs.

It now asks once, through Multicall3's `aggregate3`, with the new `SigvaraVerifier.verifyEvidenceMany`. Where
Multicall3 has no code it asks one at a time, in turn. On the agent that failed every time, the check now
confirms all 70 covered payments in about a second.

## 1.0.0-alpha.17

### Fixed: the evidence check reads a payment that settled on a payment chain
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,7 @@ then finds which of them the finalized root on chain covers: all of them, those
came later, or with an outcome the payer signed afterwards read as not yet reported. The same readings are
tried by sigvara.xyz/agents. A payment that settled on a payment chain has a leaf with its chain first and enters
a root its delay after settling, and its row names the `chainId`. Up to the last 100 covered payments listed are confirmed with the contract's
`verifyEvidence`, and the root match covers the rest. The contract's answer is a consistency check: the proofs
`verifyEvidence`, in one read through Multicall3, and the root match covers the rest. The contract's answer is a consistency check: the proofs
come from a tree whose root was just read from it, so a refusal means the root changed in between.

A reproduced root shows the oracle scored on exactly the payments it lists, with the outcome each row gives as
Expand Down
4 changes: 2 additions & 2 deletions packages/sdk/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@sigvara/protocol-sdk",
"version": "1.0.0-alpha.17",
"version": "1.0.0-alpha.18",
"description": "TypeScript SDK for Sigvara. On-chain agent identity, reputation, and A2A challenge-response authentication.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
11 changes: 4 additions & 7 deletions packages/sdk/src/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ const MAX_EVIDENCE_RECORDS = 2_000;
* minute. A long list gets fewer cut-offs, the newest first, where a finalized root usually sits.
*/
const MATCH_BUDGET = 20_000;
/** Payments confirmed one by one with verifyEvidence, the last listed. The root match covers the rest. */
/** Payments confirmed with verifyEvidence, the last listed, in one read. The root match covers the rest. */
const MAX_CONFIRMED = 100;
/** Payments shown in the result, the last listed. Counts cover them all. */
const MAX_LISTED = 50;
Expand Down Expand Up @@ -716,13 +716,10 @@ export function createTrustServer(options: TrustServerOptions): TrustServer {
m.indexes.forEach((i) => covered.add(i));
if (m.unset) m.indexes.forEach((i) => { if (records[i].outcomeSource === 'payer_signed') readAsUnreported.add(i); });
const layers = evidenceLayers(m.leaves);
// The last listed, in waves of eight: the public Arc RPC refuses a batch of more than about ten.
// The last listed, in one read: the public Arc RPC refuses a burst of single calls.
const positions = m.indexes.map((_, p) => p).slice(-MAX_CONFIRMED);
for (let w = 0; w < positions.length; w += 8) {
const wave = positions.slice(w, w + 8);
const answers = await Promise.all(wave.map((p) => verifier.verifyEvidence(did, m.leaves[p], evidenceProof(layers, p))));
wave.forEach((p, k) => confirmed.set(m.indexes[p], answers[k]));
}
const answers = await verifier.verifyEvidenceMany(did, positions.map((p) => ({ leaf: m.leaves[p], proof: evidenceProof(layers, p) })));
positions.forEach((p, k) => confirmed.set(m.indexes[p], answers[k]));
const yes = [...confirmed.values()].filter(Boolean).length;
// A payment in the committed set twice was counted twice. Legs of one transaction share a txHash with
// different payers, so it is identical leaves that are flagged, not shared hashes.
Expand Down
39 changes: 39 additions & 0 deletions packages/sdk/src/verifier.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { ethers, FetchRequest } from 'ethers';
import { IDENTITY_ABI, REPUTATION_ABI, STAKING_ABI, ERC20_ABI } from './abis';

/** Multicall3, at the address it has on most EVM chains, Arc testnet among them. */
export const MULTICALL3 = '0xcA11bde05977b3631167028862bE2a173976CA11';
const MULTICALL3_ABI = [
'function aggregate3((address target, bool allowFailure, bytes callData)[] calls) payable returns ((bool success, bytes returnData)[] returnData)',
] as const;
import { parseDid, computeDidHash } from './did';
import { verifyChallenge, parseChallengePayload, isChallengeExpired } from './challenge';
import { bytes32ToPubKey, pubKeyToMultibase } from './keys';
Expand Down Expand Up @@ -192,6 +198,39 @@ export class SigvaraVerifier {
return this.reputation().verifyEvidence(didHash, leaf, proof) as Promise<boolean>;
}

/**
* verifyEvidence for many payments, in one read through Multicall3. A public RPC that limits calls a
* second refuses a burst of single ones: Arc's refused the 29th of them within a second, and one refusal
* failed the whole check. Where Multicall3 has no code, they are asked one at a time instead.
*/
async verifyEvidenceMany(did: string, items: { leaf: string; proof: string[] }[]): Promise<boolean[]> {
if (!items.length) return [];
const didHash = await this.didHashFromDid(did);
const reputation = this.reputation();
if (!(await this.hasMulticall3())) {
const answers: boolean[] = [];
for (const { leaf, proof } of items) answers.push(await reputation.verifyEvidence(didHash, leaf, proof));
return answers;
}
const target = await reputation.getAddress();
const calls = items.map(({ leaf, proof }) => ({
target,
allowFailure: false,
callData: reputation.interface.encodeFunctionData('verifyEvidence', [didHash, leaf, proof]),
}));
const results = await new ethers.Contract(MULTICALL3, MULTICALL3_ABI, this.provider).aggregate3.staticCall(calls);
return results.map((r: { returnData: string }) => reputation.interface.decodeFunctionResult('verifyEvidence', r.returnData)[0] === true);
}

private multicall3Present?: Promise<boolean>;
private hasMulticall3(): Promise<boolean> {
// A failed read is asked again next time rather than taken as an answer.
return (this.multicall3Present ??= this.provider.getCode(MULTICALL3).then(
(code) => code !== '0x',
(err) => { this.multicall3Present = undefined; throw err; },
));
}

/** The stake an agent must hold to be Active, as the staking contract asks it now. */
async getMinimumStake(): Promise<bigint> {
return BigInt(await this.staking().minimumStake());
Expand Down
122 changes: 122 additions & 0 deletions packages/sdk/test/evidence-confirm.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { describe, it, expect } from 'vitest';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { ethers } from 'ethers';
import { createTrustServer, ARC_TESTNET } from '../src/mcp';
import { SigvaraVerifier, MULTICALL3 } from '../src/verifier';
import { REPUTATION_ABI } from '../src/abis';
import { computeDidHash } from '../src/did';
import { evidenceLeaf, evidenceLayers, evidenceProof, evidenceRoot, hashPair } from '../src/evidence';

// sigvara_verify_evidence asked the reputation contract about each payment in a separate call. Arc's public RPC
// counts calls, and on 7 November 2026 it refused the 29th within a second with "rate limit exceeded", so the
// tool failed on every agent with a long payment history. This node refuses past 20 a second the same way.

const CHAIN = 5042002;
const AGENT = '0x9d7181c8676fd40e4b31510dc0e573a0c0c2fa11';
const DID_HASH = computeDidHash(AGENT, CHAIN);
const reputationAbi = new ethers.Interface(REPUTATION_ABI);
const multicallAbi = new ethers.Interface([
'function aggregate3((address target, bool allowFailure, bytes callData)[] calls) payable returns ((bool success, bytes returnData)[] returnData)',
]);

const payments = Array.from({ length: 60 }, (_, i) => ({
txHash: ethers.zeroPadValue(ethers.toBeHex(i + 1), 32),
payer: ethers.getAddress(ethers.zeroPadValue(ethers.toBeHex(0xd00 + i), 20)),
amount: String(BigInt(i + 1) * 10n ** 18n),
settledAt: 1_700_000_000 + i * 60,
success: true,
outcomeSource: 'credentialed',
}));
const ROOT = evidenceRoot(payments.map((p) => evidenceLeaf(p)));

/** A node holding one agent's finalized root, refusing more than `limit` eth_calls a second. */
async function node({ limit = 20, multicall = true } = {}) {
const seen = { ethCalls: 0, refused: 0, aggregate3: 0, single: 0 };
let windowStart = Date.now();
let inWindow = 0;
const verify = (data: string) => {
const [didHash, leaf, proof] = reputationAbi.decodeFunctionData('verifyEvidence', data);
const ok = didHash === DID_HASH && (proof as string[]).reduce((acc, s) => hashPair(acc, s), leaf as string) === ROOT;
return reputationAbi.encodeFunctionResult('verifyEvidence', [ok]);
};
const answer = (req: { id: unknown; method: string; params: any[] }) => {
if (req.method === 'eth_chainId') return { result: ethers.toQuantity(CHAIN) };
if (req.method === 'eth_getCode') {
return { result: multicall && req.params[0].toLowerCase() === MULTICALL3.toLowerCase() ? '0x6080604052' : '0x' };
}
if (req.method !== 'eth_call') return { error: { code: -32601, message: `no ${req.method}` } };
seen.ethCalls++;
if (Date.now() - windowStart >= 1000) { windowStart = Date.now(); inWindow = 0; }
if (++inWindow > limit) { seen.refused++; return { error: { code: -32005, message: 'rate limit exceeded' } }; }
const { to, data } = req.params[0];
if (to.toLowerCase() === MULTICALL3.toLowerCase()) {
seen.aggregate3++;
const [calls] = multicallAbi.decodeFunctionData('aggregate3', data);
return { result: multicallAbi.encodeFunctionResult('aggregate3', [calls.map((c: any) => [true, verify(c.callData)])]) };
}
const selector = data.slice(0, 10);
if (selector === reputationAbi.getFunction('evidenceRoots')!.selector) return { result: reputationAbi.encodeFunctionResult('evidenceRoots', [ROOT]) };
if (selector === reputationAbi.getFunction('verifyEvidence')!.selector) { seen.single++; return { result: verify(data) }; }
if (selector === reputationAbi.getFunction('getPendingScore')!.selector) {
return { result: reputationAbi.encodeFunctionResult('getPendingScore', [[[0, 0, 0, 0, 0, 0, 0n], 0n, false, ethers.ZeroHash, ethers.ZeroAddress, 0n]]) };
}
return { error: { code: 3, message: 'execution reverted' } };
};
const server = http.createServer((req, res) => {
let body = '';
req.on('data', (d) => { body += d; });
req.on('end', () => {
const parsed = JSON.parse(body);
const reply = (r: any) => ({ jsonrpc: '2.0', id: r.id, ...answer(r) });
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify(Array.isArray(parsed) ? parsed.map(reply) : reply(parsed)));
});
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
return { url, seen, close: () => { server.closeAllConnections(); server.close(); } };
}

describe('confirming a finalized root with the contract', () => {
it('confirms 60 payments against a node that refuses more than 20 calls a second', async () => {
const rpc = await node();
try {
const server = createTrustServer({
chainId: CHAIN, addresses: ARC_TESTNET.addresses, rpcUrl: rpc.url,
fetchEvidence: async () => ({ didHash: DID_HASH, evidence: payments.map((p) => ({ ...p, leaf: evidenceLeaf(p) })) }),
});
const r: any = await server.handle({
jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'sigvara_verify_evidence', arguments: { agent: AGENT } },
});
const text = r.result.content[0].text;
expect(r.result.isError, text).toBe(false);
const value = JSON.parse(text);
expect(value.finalized).toMatchObject({ reproduced: true, covers: 60, checkedWithContract: 60, confirmedByContract: 60 });
expect(rpc.seen.refused).toBe(0);
expect(rpc.seen.aggregate3).toBe(1);
expect(rpc.seen.single).toBe(0);
} finally {
rpc.close();
}
});

it('reads each answer from the batch, and asks one at a time where Multicall3 has no code', async () => {
const layers = evidenceLayers(payments.map((p) => evidenceLeaf(p)));
const good = { leaf: layers[0][3], proof: evidenceProof(layers, 3) };
const bad = { leaf: evidenceLeaf({ ...payments[3], amount: '1' }), proof: evidenceProof(layers, 3) };
const did = `did:sigvara:${CHAIN}:${AGENT}`;
for (const multicall of [true, false]) {
const rpc = await node({ multicall });
try {
const v = new SigvaraVerifier({ rpcUrl: rpc.url, addresses: ARC_TESTNET.addresses, chainId: CHAIN });
expect(await v.verifyEvidenceMany(did, [good, bad, good]), `multicall ${multicall}`).toEqual([true, false, true]);
expect(await v.verifyEvidenceMany(did, [])).toEqual([]);
expect(rpc.seen.aggregate3, `multicall ${multicall}`).toBe(multicall ? 1 : 0);
expect(rpc.seen.single, `multicall ${multicall}`).toBe(multicall ? 0 : 3);
} finally {
rpc.close();
}
}
});
});
Loading
Loading