Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(reputation): open, read, and settle stake positions over the attested Solana rail

nirholas510eb703815c
diff --git a/api/_lib/solana-agent-events.js b/api/_lib/solana-agent-events.js
new file mode 100644
index 000000000..1058f2df5
--- /dev/null
+++ b/api/_lib/solana-agent-events.js
@@ -0,0 +1,360 @@
+// Solana leg of the agent event index: turn an agent account's transaction
+// history into typed lifecycle events in agent_onchain_events.
+//
+// Why this exists. Before it, the Solana side of the index stored exactly two
+// things: a static directory row per agent (solana_agents_index, written by the
+// registry crawl) and three.ws memo attestations (solana_attestations). A live
+// sample of eight indexed Metaplex Agent Registry agents on 2026-08-11 found
+// 1 to 6 on-chain signatures each and ZERO indexed events for all eight,
+// because the only Solana crawler recognized `threews.*` memo payloads and ran
+// solely over agent_identities rows (18 mainnet agents) rather than the 1,558
+// external agents in the directory.
+//
+// The transactions that were being dropped are exactly the classes the roadmap
+// asks for. Decoded from mainnet:
+// RegisterIdentityV1 (1DREG…) agent registration
+// SetAgentTokenV1 (1DREG…) the agent's token launch — an SPL mint bound
+// to the agent, the Solana analog of a coin launch
+// DelegateExecutionV1 (TLREG…) execution rights delegated to another account
+// TransferV1 (CoREEN…) Metaplex Core ownership transfer
+// UpdateV1 (CoREEN…) Core metadata update
+// SPL Memo threews.* reputation / validation attestations
+//
+// classifyAgentTx() is pure and is where every one of those mappings lives, so
+// the classification is unit-testable against captured mainnet transactions
+// without an RPC round trip.
+
+import { sql } from './db.js';
+import { solanaConnection } from './solana/connection.js';
+import { RPC } from './solana-attestations.js';
+import { recordEvents } from './onchain-events.js';
+
+/** Metaplex Agent Registry identity program. */
+export const MPL_AGENT_IDENTITY_PROGRAM = '1DREGFgysWYxLnRnKQnwrxnJQeSMk2HmGaC6whw2B2p';
+/** Metaplex Agent Registry execution-delegation program. */
+export const MPL_AGENT_DELEGATION_PROGRAM = 'TLREGni9ZEyGC3vnPZtqUh95xQ8oPqJSvNjvB7FGK8S';
+/** Metaplex Core, which owns the agent asset itself. */
+export const MPL_CORE_PROGRAM = 'CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d';
+/** SPL Token programs an agent-token launch touches. */
+export const SPL_TOKEN_PROGRAMS = Object.freeze([
+ 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',
+ 'TokExjvjJmhKaRBShsBAsbSvEWMA1AgUNK7ps4SAc2p',
+ 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',
+]);
+
+// Anchor instruction names, as they appear in `Program log: Instruction: <Name>`,
+// mapped to the index's event class. Names not listed here produce no event:
+// the index records agent lifecycle, not every compute-budget hop.
+const INSTRUCTION_EVENTS = Object.freeze({
+ RegisterIdentityV1: { eventClass: 'registration', program: MPL_AGENT_IDENTITY_PROGRAM },
+ UnregisterIdentityV1: { eventClass: 'registration', program: MPL_AGENT_IDENTITY_PROGRAM },
+ SetAgentTokenV1: { eventClass: 'token_launch', program: MPL_AGENT_IDENTITY_PROGRAM },
+ SetAgentUriV1: { eventClass: 'metadata', program: MPL_AGENT_IDENTITY_PROGRAM },
+ DelegateExecutionV1: { eventClass: 'delegation', program: MPL_AGENT_DELEGATION_PROGRAM },
+ RevokeExecutionV1: { eventClass: 'delegation', program: MPL_AGENT_DELEGATION_PROGRAM },
+ TransferV1: { eventClass: 'transfer', program: MPL_CORE_PROGRAM },
+ UpdateV1: { eventClass: 'metadata', program: MPL_CORE_PROGRAM },
+ BurnV1: { eventClass: 'transfer', program: MPL_CORE_PROGRAM },
+});
+
+const MEMO_KIND_CLASS = Object.freeze({
+ 'threews.feedback.v1': 'reputation',
+ 'threews.stake.v1': 'reputation',
+ 'threews.review.v1': 'reputation',
+ 'threews.task.v1': 'reputation',
+ 'threews.accept.v1': 'reputation',
+ 'threews.revoke.v1': 'reputation',
+ 'threews.dispute.v1': 'reputation',
+ 'threews.validation.v1': 'validation',
+});
+
+const INSTRUCTION_LOG = /^Program log: Instruction: (\w+)$/;
+
+/**
+ * Account keys of a confirmed transaction as base58 strings, whichever shape
+ * the RPC returned (jsonParsed puts objects in `accountKeys`, the default
+ * encoding puts PublicKeys in `staticAccountKeys`).
+ * @param {object} tx
+ * @returns {string[]}
+ */
+export function accountKeysOf(tx) {
+ const msg = tx?.transaction?.message;
+ const keys = msg?.staticAccountKeys || msg?.accountKeys || [];
+ return keys.map((k) => {
+ if (typeof k === 'string') return k;
+ if (typeof k?.toBase58 === 'function') return k.toBase58();
+ if (typeof k?.pubkey === 'string') return k.pubkey;
+ if (typeof k?.pubkey?.toBase58 === 'function') return k.pubkey.toBase58();
+ return String(k);
+ });
+}
+
+/**
+ * Extract the SPL Memo JSON payload from a transaction's logs, or null.
+ * @param {object} tx
+ * @returns {object|null}
+ */
+export function memoPayloadOf(tx) {
+ const line = (tx?.meta?.logMessages || []).find((l) => l.includes('Program log: Memo'));
+ if (!line) return null;
+ const start = line.indexOf('"');
+ const end = line.lastIndexOf('"');
+ if (start < 0 || end <= start) return null;
+ try {
+ return JSON.parse(line.slice(start + 1, end).replace(/\\"/g, '"'));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Classify one confirmed transaction touching an agent account into zero or
+ * more index events. Pure: no RPC, no DB, no clock.
+ *
+ * @param {object} args
+ * @param {string} args.agentRef the agent account this transaction was fetched for
+ * @param {string} args.signature transaction signature
+ * @param {number} args.slot
+ * @param {number|null} args.blockTime unix seconds from the RPC
+ * @param {string} args.network 'mainnet' | 'devnet'
+ * @param {object} args.tx confirmed transaction as returned by getTransactions
+ * @returns {object[]} events ready for recordEvents()
+ */
+export function classifyAgentTx({ agentRef, signature, slot, blockTime, network, tx }) {
+ if (!tx || tx?.meta?.err) return [];
+ const keys = accountKeysOf(tx);
+ const programs = new Set(keys);
+ const logs = tx?.meta?.logMessages || [];
+ const signer = keys[0] || null;
+ const events = [];
+ const seen = new Set();
+
+ let ordinal = 0;
+ for (const line of logs) {
+ const m = INSTRUCTION_LOG.exec(line);
+ if (!m) continue;
+ const name = m[1];
+ const spec = INSTRUCTION_EVENTS[name];
+ // Only trust an instruction name when the program that owns it is
+ // actually in the transaction: `UpdateV1` and `TransferV1` are common
+ // names and would otherwise match an unrelated program's log line.
+ if (!spec || !programs.has(spec.program)) continue;
+ if (seen.has(name)) continue;
+ seen.add(name);
+
+ const payload = { program: spec.program, instruction: name };
+ if (spec.eventClass === 'token_launch') {
+ const mint = agentTokenMintOf(tx, agentRef);
+ if (mint) payload.mint = mint;
+ }
+
+ events.push({
+ chain: 'solana',
+ network,
+ agentRef,
+ eventClass: spec.eventClass,
+ eventName: name,
+ tx: signature,
+ logIndex: ordinal++,
+ blockNumber: slot,
+ occurredAt: blockTime,
+ actor: signer,
+ counterparty: spec.eventClass === 'transfer' ? transferRecipientOf(tx, keys) : null,
+ payload,
+ });
+ }
+
+ const memo = memoPayloadOf(tx);
+ const memoClass = memo && typeof memo.kind === 'string' ? MEMO_KIND_CLASS[memo.kind] : null;
+ if (memoClass) {
+ events.push({
+ chain: 'solana',
+ network,
+ agentRef,
+ eventClass: memoClass,
+ eventName: memo.kind,
+ tx: signature,
+ logIndex: ordinal++,
+ blockNumber: slot,
+ occurredAt: blockTime,
+ actor: signer,
+ counterparty: null,
+ payload: memo,
+ });
+ }
+
+ return events;
+}
+
+/**
+ * Best-effort mint for a SetAgentTokenV1 transaction: the token balances the
+ * transaction touched name the mint directly, which beats guessing from the
+ * account list. Returns null when the tx moved no token balance.
+ * @param {object} tx
+ * @param {string} agentRef
+ * @returns {string|null}
+ */
+export function agentTokenMintOf(tx, agentRef) {
+ const balances = [...(tx?.meta?.postTokenBalances || []), ...(tx?.meta?.preTokenBalances || [])];
+ for (const b of balances) {
+ if (b?.mint && b.mint !== agentRef) return b.mint;
+ }
+ return null;
+}
+
+/**
+ * The account a Core transfer moved the asset to: the largest SOL-balance
+ * gainer that is not the fee payer. Null when the balances do not say.
+ * @param {object} tx
+ * @param {string[]} keys
+ * @returns {string|null}
+ */
+export function transferRecipientOf(tx, keys) {
+ const pre = tx?.meta?.preBalances;
+ const post = tx?.meta?.postBalances;
+ if (!Array.isArray(pre) || !Array.isArray(post)) return null;
+ let best = null;
+ let bestDelta = 0n;
+ for (let i = 1; i < Math.min(pre.length, post.length, keys.length); i++) {
+ const delta = BigInt(post[i] ?? 0) - BigInt(pre[i] ?? 0);
+ if (delta > bestDelta) {
+ bestDelta = delta;
+ best = keys[i];
+ }
+ }
+ return best;
+}
+
+const CHAIN = 'solana';
+
+/**
+ * Crawl one Solana agent account's recent signatures into the event index.
+ * Resumes from agent_event_cursor, so a steady-state run fetches only what
+ * landed since the last pass.
+ *
+ * @param {{ agentRef: string, network?: string, limit?: number }} args
+ * @returns {Promise<{ scanned: number, inserted: number, rejected: number }>}
+ */
+export async function crawlAgentEvents({ agentRef, network = 'mainnet', limit = 100 }) {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ const conn = solanaConnection({ url: RPC[net], commitment: 'confirmed' });
+
+ const [cursor] = await sql`
+ SELECT last_tx FROM agent_event_cursor
+ WHERE chain = ${CHAIN} AND chain_id = 0 AND agent_ref = ${agentRef}
+ LIMIT 1
+ `;
+
+ const sigs = await conn.getSignaturesForAddress(agentRef, {
+ limit,
+ until: cursor?.last_tx || undefined,
+ });
+
+ if (sigs.length === 0) {
+ await touchCursor({ agentRef, network: net, lastTx: cursor?.last_tx || null });
+ return { scanned: 0, inserted: 0, rejected: 0 };
+ }
+
+ const ok = sigs.filter((s) => !s.err);
+ const txs = ok.length
+ ? await conn.getTransactions(
+ ok.map((s) => s.signature),
+ { maxSupportedTransactionVersion: 0 },
+ )
+ : [];
+
+ const events = [];
+ for (let i = 0; i < ok.length; i++) {
+ events.push(
+ ...classifyAgentTx({
+ agentRef,
+ signature: ok[i].signature,
+ slot: ok[i].slot,
+ blockTime: ok[i].blockTime ?? null,
+ network: net,
+ tx: txs[i],
+ }),
+ );
+ }
+
+ const { inserted, rejected } = await recordEvents(events);
+
+ await touchCursor({
+ agentRef,
+ network: net,
+ lastTx: sigs[0].signature,
+ lastSlot: sigs[0].slot,
+ lastEventAt: sigs[0].blockTime ? new Date(sigs[0].blockTime * 1000).toISOString() : null,
+ scanned: sigs.length,
+ });
+
+ return { scanned: sigs.length, inserted, rejected };
+}
+
+async function touchCursor({ agentRef, network, lastTx, lastSlot = null, lastEventAt = null, scanned = 0 }) {
+ await sql`
+ INSERT INTO agent_event_cursor
+ (chain, chain_id, agent_ref, network, last_tx, last_slot, last_event_at, last_indexed_at, scanned)
+ VALUES
+ (${CHAIN}, 0, ${agentRef}, ${network}, ${lastTx}, ${lastSlot}, ${lastEventAt}, now(), ${scanned})
+ ON CONFLICT (chain, chain_id, agent_ref) DO UPDATE SET
+ network = excluded.network,
+ last_tx = COALESCE(excluded.last_tx, agent_event_cursor.last_tx),
+ last_slot = COALESCE(excluded.last_slot, agent_event_cursor.last_slot),
+ last_event_at = COALESCE(excluded.last_event_at, agent_event_cursor.last_event_at),
+ last_indexed_at = now(),
+ scanned = agent_event_cursor.scanned + excluded.scanned,
+ error = null
+ `;
+}
+
+/**
+ * Record a crawl failure against the cursor so a permanently failing agent is
+ * visible instead of silently starving the oldest-first queue forever.
+ * @param {{ agentRef: string, network?: string, error: string }} args
+ */
+export async function markAgentEventError({ agentRef, network = 'mainnet', error }) {
+ await sql`
+ INSERT INTO agent_event_cursor
+ (chain, chain_id, agent_ref, network, last_indexed_at, error)
+ VALUES (${CHAIN}, 0, ${agentRef}, ${network}, now(), ${String(error).slice(0, 500)})
+ ON CONFLICT (chain, chain_id, agent_ref) DO UPDATE SET
+ last_indexed_at = now(),
+ error = excluded.error
+ `;
+}
+
+/**
+ * The next batch of Solana agents to crawl, oldest cursor first, drawn from
+ * BOTH the platform's own agents and the external registry directory. The
+ * directory half is the coverage that was missing entirely.
+ * @param {{ limit?: number }} [opts]
+ * @returns {Promise<Array<{ agent_ref: string, network: string, source: string }>>}
+ */
+export async function nextAgentBatch({ limit = 40 } = {}) {
+ return sql`
+ WITH candidates AS (
+ SELECT
+ a.meta->>'sol_mint_address' AS agent_ref,
+ coalesce(a.meta->>'network', 'mainnet') AS network,
+ 'three.ws' AS source
+ FROM agent_identities a
+ WHERE a.deleted_at IS NULL
+ AND a.meta ? 'sol_mint_address'
+ UNION
+ SELECT
+ coalesce(s.asset, s.ref) AS agent_ref,
+ s.network AS network,
+ s.source AS source
+ FROM solana_agents_index s
+ WHERE s.active = true
+ )
+ SELECT c.agent_ref, c.network, c.source
+ FROM candidates c
+ LEFT JOIN agent_event_cursor cur
+ ON cur.chain = ${CHAIN} AND cur.chain_id = 0 AND cur.agent_ref = c.agent_ref
+ WHERE c.agent_ref IS NOT NULL
+ ORDER BY cur.last_indexed_at NULLS FIRST
+ LIMIT ${limit}
+ `;
+}
diff --git a/api/reputation/market-positions.js b/api/reputation/market-positions.js
new file mode 100644
index 000000000..a9c788dc3
--- /dev/null
+++ b/api/reputation/market-positions.js
@@ -0,0 +1,49 @@
+/**
+ * GET /api/reputation/market-positions?staker=<pubkey>&network=devnet
+ *
+ * Every reputation-market position a wallet holds, with earnings quoted against
+ * the live cohort and the per-epoch derivation attached so a staker can audit
+ * the number against src/shared/reputation-staking.js themselves.
+ *
+ * Read-only and walletless: a position's owner is the fee payer recorded
+ * on-chain, so there is nothing private to gate here.
+ *
+ * Contract: specs/REPUTATION_STAKING_MARKET.md §8.
+ */
+
+import { PublicKey } from '@solana/web3.js';
+
+import { cors, json, method, wrap, rateLimited, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isDbUnavailableError } from '../_lib/db.js';
+import { stakerView, MarketError } from '../_lib/reputation-market.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const p = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
+ const staker = (p.get('staker') || '').trim();
+ const network = p.get('network') === 'mainnet' ? 'mainnet' : 'devnet';
+
+ if (!staker) return error(res, 400, 'validation_error', 'staker query param required');
+ try {
+ new PublicKey(staker);
+ } catch {
+ return error(res, 400, 'validation_error', 'staker must be a base58 Solana pubkey');
+ }
+
+ try {
+ const body = await stakerView({ staker, network });
+ return json(res, 200, body, { 'cache-control': 'no-store' });
+ } catch (err) {
+ if (err instanceof MarketError) return error(res, err.status, err.code, err.message);
+ if (isDbUnavailableError(err)) {
+ return error(res, 503, 'db_unavailable', 'The market index is temporarily unavailable.');
+ }
+ throw err;
+ }
+});
diff --git a/api/reputation/market-stake.js b/api/reputation/market-stake.js
new file mode 100644
index 000000000..5ca7c65d1
--- /dev/null
+++ b/api/reputation/market-stake.js
@@ -0,0 +1,58 @@
+/**
+ * POST /api/reputation/market-stake { signature, network }
+ *
+ * Record a stake the staker ALREADY broadcast. This endpoint never signs and
+ * never moves funds: it reads the transaction back off Solana, checks it against
+ * the market envelope rules, and indexes the position it opens. The caller
+ * cannot assert a principal, an agent, or an owner; all three come from the
+ * chain (specs/REPUTATION_STAKING_MARKET.md §3.1).
+ *
+ * Idempotent on the stake signature.
+ */
+
+import { cors, json, method, wrap, rateLimited, error, readJson } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isDbUnavailableError } from '../_lib/db.js';
+import { recordStake, MarketError } from '../_lib/reputation-market.js';
+
+const SIGNATURE_RE = /^[1-9A-HJ-NP-Za-km-z]{64,88}$/;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = await readJson(req).catch(() => null);
+ const signature = String(body?.signature || '').trim();
+ const network = body?.network === 'mainnet' ? 'mainnet' : 'devnet';
+
+ if (!SIGNATURE_RE.test(signature)) {
+ return error(res, 400, 'validation_error', 'signature must be a base58 Solana transaction signature');
+ }
+
+ try {
+ const { position, created } = await recordStake({ signature, network });
+ return json(res, created ? 201 : 200, {
+ ok: true,
+ created,
+ position: {
+ signature: position.signature,
+ network: position.network,
+ agent_asset: position.agentAsset,
+ staker: position.staker,
+ principal_lamports: position.principalLamports.toString(),
+ score: position.score,
+ status: position.status,
+ opened_at: new Date(position.openedAt * 1000).toISOString(),
+ },
+ });
+ } catch (err) {
+ if (err instanceof MarketError) return error(res, err.status, err.code, err.message);
+ if (isDbUnavailableError(err)) {
+ return error(res, 503, 'db_unavailable', 'The market index is temporarily unavailable.');
+ }
+ throw err;
+ }
+});
diff --git a/api/reputation/market-withdraw.js b/api/reputation/market-withdraw.js
new file mode 100644
index 000000000..fd14633f1
--- /dev/null
+++ b/api/reputation/market-withdraw.js
@@ -0,0 +1,61 @@
+/**
+ * POST /api/reputation/market-withdraw { signature, network }
+ *
+ * Settle a reputation-market position: return the staker's principal in full
+ * plus whatever their conviction earned from the agent's attested action
+ * history, and write the `threews.unstake.v1` memo that retires the conviction
+ * on-chain.
+ *
+ * The payout always goes to the staker recorded in the stake transaction, never
+ * to the caller, so this endpoint is safe to leave open: the worst an attacker
+ * can do by calling it for someone else's position is pay that person their own
+ * money. Mainnet stays owner-gated (specs/REPUTATION_STAKING_MARKET.md §1).
+ */
+
+import { cors, json, method, wrap, rateLimited, error, readJson } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isDbUnavailableError } from '../_lib/db.js';
+import { withdrawPosition, MarketError } from '../_lib/reputation-market.js';
+
+const SIGNATURE_RE = /^[1-9A-HJ-NP-Za-km-z]{64,88}$/;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = await readJson(req).catch(() => null);
+ const signature = String(body?.signature || '').trim();
+ const network = body?.network === 'mainnet' ? 'mainnet' : 'devnet';
+
+ if (!SIGNATURE_RE.test(signature)) {
+ return error(res, 400, 'validation_error', 'signature must be a base58 Solana transaction signature');
+ }
+
+ try {
+ const result = await withdrawPosition({ signature, network });
+ return json(res, 200, {
+ ok: true,
+ status: result.status,
+ settlement: result.settlement,
+ position: {
+ signature: result.position.signature,
+ network: result.position.network,
+ agent_asset: result.position.agentAsset,
+ staker: result.position.staker,
+ principal_lamports: result.position.principalLamports.toString(),
+ status: result.position.status,
+ closed_at: result.position.closedAt ? new Date(result.position.closedAt * 1000).toISOString() : null,
+ settle_signature: result.position.settleSignature,
+ },
+ });
+ } catch (err) {
+ if (err instanceof MarketError) return error(res, err.status, err.code, err.message);
+ if (isDbUnavailableError(err)) {
+ return error(res, 503, 'db_unavailable', 'The market index is temporarily unavailable.');
+ }
+ throw err;
+ }
+});
diff --git a/contracts/test/ValidationRegistry.t.sol b/contracts/test/ValidationRegistry.t.sol
index 9f446c234..68f962a02 100644
--- a/contracts/test/ValidationRegistry.t.sol
+++ b/contracts/test/ValidationRegistry.t.sol
@@ -5,6 +5,9 @@ import {Test} from "forge-std/Test.sol";
import {IdentityRegistry} from "../src/IdentityRegistry.sol";
import {ValidationRegistry} from "../src/ValidationRegistry.sol";
+/// @dev Invariants under proof: VR-1 .. VR-6 of
+/// `specs/ECONOMY_CONTRACT_INVARIANTS.md`. The allow-list policy this
+/// contract enforces is documented in `specs/VALIDATORS.md`.
contract ValidationRegistryTest is Test {
IdentityRegistry identity;
ValidationRegistry validation;
@@ -84,4 +87,163 @@ contract ValidationRegistryTest is Test {
vm.expectRevert(ValidationRegistry.NotValidator.selector);
validation.recordValidation(1, true, bytes32(0), "", "glb-schema");
}
+
+ // ── VR-2: ownership can never be lost ────────────────────────────────────
+
+ function testConstructorRejectsZeroOwner() public {
+ vm.expectRevert(ValidationRegistry.ZeroAddress.selector);
+ new ValidationRegistry(address(identity), address(0));
+ }
+
+ function testConstructorRejectsZeroIdentityRegistry() public {
+ vm.expectRevert(ValidationRegistry.ZeroAddress.selector);
+ new ValidationRegistry(address(0), owner);
+ }
+
+ function testTransferOwnershipRejectsZero() public {
+ vm.expectRevert(ValidationRegistry.ZeroAddress.selector);
+ validation.transferOwnership(address(0));
+ assertEq(validation.owner(), owner, "VR-2: the allow-list must never become unmanageable");
+ }
+
+ function testTransferOwnershipOnlyOwner() public {
+ vm.prank(bob);
+ vm.expectRevert(ValidationRegistry.NotOwner.selector);
+ validation.transferOwnership(bob);
+ assertEq(validation.owner(), owner);
+ }
+
+ function testTransferOwnershipMovesEveryRight() public {
+ validation.transferOwnership(bob);
+ assertEq(validation.owner(), bob);
+
+ vm.expectRevert(ValidationRegistry.NotOwner.selector);
+ validation.addValidator(validator);
+
+ vm.prank(bob);
+ validation.addValidator(validator);
+ assertTrue(validation.isValidator(validator));
+ }
+
+ function testOnlyOwnerCanRemoveValidator() public {
+ validation.addValidator(validator);
+
+ vm.prank(bob);
+ vm.expectRevert(ValidationRegistry.NotOwner.selector);
+ validation.removeValidator(validator);
+
+ assertTrue(validation.isValidator(validator));
+ }
+
+ // ── VR-1: removal is immediate, re-adding restores ───────────────────────
+
+ function testReAddedValidatorCanRecordAgain() public {
+ validation.addValidator(validator);
+ validation.removeValidator(validator);
+ validation.addValidator(validator);
+
+ vm.prank(validator);
+ validation.recordValidation(1, true, keccak256("again"), "", "glb-schema");
+ assertEq(validation.getValidationCount(1), 1);
+ }
+
+ // ── VR-3: the history is append-only ─────────────────────────────────────
+
+ function testRemovingAValidatorDoesNotEraseItsHistory() public {
+ validation.addValidator(validator);
+ vm.prank(validator);
+ validation.recordValidation(1, true, keccak256("kept"), "ipfs://r", "glb-schema");
+
+ validation.removeValidator(validator);
+
+ assertEq(validation.getValidationCount(1), 1, "VR-3: attestations survive de-listing");
+ ValidationRegistry.Validation memory v = validation.getValidation(1, 0);
+ assertEq(v.validator, validator);
+ assertEq(v.proofHash, keccak256("kept"));
+ }
+
+ function testRecordsAccumulateInOrder() public {
+ validation.addValidator(validator);
+ address second = address(0x5EC0);
+ validation.addValidator(second);
+
+ vm.prank(validator);
+ validation.recordValidation(1, false, keccak256("first"), "", "glb-schema");
+ vm.prank(second);
+ validation.recordValidation(1, true, keccak256("second"), "", "glb-schema");
+
+ assertEq(validation.getValidationCount(1), 2);
+ assertEq(validation.getValidation(1, 0).proofHash, keccak256("first"));
+ assertEq(validation.getValidation(1, 1).proofHash, keccak256("second"));
+ assertEq(validation.getValidation(1, 1).validator, second);
+ }
+
+ function testRecordStampsTheBlockTimestamp() public {
+ validation.addValidator(validator);
+ vm.warp(1_800_000_000);
+ vm.prank(validator);
+ validation.recordValidation(1, true, keccak256("t"), "", "glb-schema");
+
+ assertEq(validation.getValidation(1, 0).timestamp, uint64(1_800_000_000));
+ }
+
+ function testValidationsArePerAgent() public {
+ vm.prank(bob);
+ identity.register("ipfs://bob");
+
+ validation.addValidator(validator);
+ vm.prank(validator);
+ validation.recordValidation(1, true, keccak256("a1"), "", "glb-schema");
+
+ assertEq(validation.getValidationCount(1), 1);
+ assertEq(validation.getValidationCount(2), 0);
+ }
+
+ // ── VR-4: kind lookup ────────────────────────────────────────────────────
+
+ function testLatestByKindRevertsWhenAbsent() public {
+ validation.addValidator(validator);
+ vm.prank(validator);
+ validation.recordValidation(1, true, keccak256("a"), "", "glb-schema");
+
+ vm.expectRevert(bytes("no validation"));
+ validation.getLatestByKind(1, "never-recorded");
+ }
+
+ function testLatestByKindIsExactStringMatch() public {
+ validation.addValidator(validator);
+ vm.startPrank(validator);
+ validation.recordValidation(1, true, keccak256("a"), "", "glb-schema");
+ vm.stopPrank();
+
+ vm.expectRevert(bytes("no validation"));
+ validation.getLatestByKind(1, "glb-schema ");
+ }
+
+ // ── VR-6: pagination never reverts on a large window ─────────────────────
+
+ function testValidationRangeClampsAndPaginates() public {
+ validation.addValidator(validator);
+ vm.startPrank(validator);
+ validation.recordValidation(1, true, keccak256("a"), "", "k");
+ validation.recordValidation(1, true, keccak256("b"), "", "k");
+ validation.recordValidation(1, true, keccak256("c"), "", "k");
+ vm.stopPrank();
+
+ ValidationRegistry.Validation[] memory all = validation.getValidationRange(1, 0, 100);
+ assertEq(all.length, 3, "VR-6: an oversized limit clamps to what exists");
+
+ ValidationRegistry.Validation[] memory page = validation.getValidationRange(1, 1, 1);
+ assertEq(page.length, 1);
+ assertEq(page[0].proofHash, keccak256("b"));
+
+ assertEq(validation.getValidationRange(1, 3, 10).length, 0);
+ assertEq(validation.getValidationRange(1, 0, 0).length, 0);
+ assertEq(validation.getValidationRange(999, 0, 10).length, 0);
+ }
+
+ function testGetValidationOutOfRangeReverts() public {
+ vm.expectRevert();
+ validation.getValidation(1, 0);
+ }
}