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(onchain): index registry events so an agent's on-chain history is readable without an RPC scan

nirholasbedb9534ef2c
diff --git a/api/_lib/erc8004-registry-events.js b/api/_lib/erc8004-registry-events.js
new file mode 100644
index 000000000..595c309c0
--- /dev/null
+++ b/api/_lib/erc8004-registry-events.js
@@ -0,0 +1,160 @@
+// Pure decoder for ERC-8004 Identity Registry logs.
+//
+// The crawler used to filter on the single `Registered` topic, which meant an
+// agent's indexed row froze at its registration block forever. A live census of
+// the registry contract on 2026-08-11 (4001 blocks on Base, 2001 on Ethereum
+// and Ethereum Sepolia) found four event classes in the logs and only one of
+// them indexed:
+//
+// Base 66 logs → 7 Registered indexed (28 MetadataUpdate, 24 MetadataSet,
+// 7 Transfer, 7 Registered — 10.6% coverage)
+// Ethereum 93 logs → 15 Registered indexed (48 MetadataSet, 15 Transfer,
+// 15 MetadataUpdate — 16.1% coverage)
+// Eth Sep 16 logs → 3 Registered indexed (5 MetadataUpdate, 3 Transfer,
+// 3 MetadataSet, 2 URIUpdated — 18.8%)
+//
+// The two topics that did not resolve against a local signature list were
+// confirmed against the openchain.xyz signature database and their raw log
+// shapes: MetadataSet(uint256,string,string,bytes) and URIUpdated(uint256,string,address).
+//
+// This module is deliberately free of DB and network access so the decode paths
+// are unit-testable against captured mainnet logs.
+
+import { id as keccakId, AbiCoder, getAddress } from 'ethers';
+
+const ABI_CODER = AbiCoder.defaultAbiCoder();
+
+/** Registered(uint256 indexed agentId, string tokenURI, address indexed owner) */
+export const TOPIC_REGISTERED = keccakId('Registered(uint256,string,address)');
+/** URIUpdated(uint256 indexed agentId, string tokenURI, address indexed owner) */
+export const TOPIC_URI_UPDATED = keccakId('URIUpdated(uint256,string,address)');
+/** MetadataSet(uint256 indexed agentId, string indexed key, string key, bytes value) */
+export const TOPIC_METADATA_SET = keccakId('MetadataSet(uint256,string,string,bytes)');
+/** Transfer(address indexed from, address indexed to, uint256 indexed tokenId) */
+export const TOPIC_TRANSFER = keccakId('Transfer(address,address,uint256)');
+
+/**
+ * Every topic0 the crawler asks the RPC for, as an eth_getLogs topic OR-set.
+ * EIP-4906 MetadataUpdate is deliberately absent: it is an unindexed
+ * "refresh your cache" ping that carries no state the index does not already
+ * get from URIUpdated / MetadataSet, and on Base it is the single noisiest
+ * topic on the contract.
+ */
+export const REGISTRY_TOPICS = [
+ TOPIC_REGISTERED,
+ TOPIC_URI_UPDATED,
+ TOPIC_METADATA_SET,
+ TOPIC_TRANSFER,
+];
+
+const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
+
+const addrFromTopic = (topic) => getAddress('0x' + topic.slice(-40)).toLowerCase();
+
+const hexToInt = (hex) => (hex == null ? null : Number.parseInt(hex, 16));
+
+/**
+ * Decode one registry log into a normalized event.
+ *
+ * @param {{ topics: string[], data: string, blockNumber: string,
+ * transactionHash: string, logIndex?: string }} log raw eth_getLogs entry
+ * @returns {null | {
+ * type: 'registered'|'uri_updated'|'metadata_set'|'transfer',
+ * eventName: string, eventClass: string, agentId: string,
+ * owner?: string, from?: string, to?: string, agentUri?: string,
+ * key?: string, value?: string, isMint?: boolean,
+ * blockNumber: number|null, logIndex: number, tx: string
+ * }} null when the topic is not one we index or the payload will not decode.
+ */
+export function decodeRegistryLog(log) {
+ if (!log || !Array.isArray(log.topics) || log.topics.length === 0) return null;
+ const base = {
+ blockNumber: hexToInt(log.blockNumber),
+ logIndex: hexToInt(log.logIndex) ?? 0,
+ tx: log.transactionHash,
+ };
+
+ switch (log.topics[0]) {
+ case TOPIC_REGISTERED:
+ case TOPIC_URI_UPDATED: {
+ if (log.topics.length < 3) return null;
+ const registered = log.topics[0] === TOPIC_REGISTERED;
+ const [agentUri] = ABI_CODER.decode(['string'], log.data);
+ return {
+ ...base,
+ type: registered ? 'registered' : 'uri_updated',
+ eventName: registered ? 'Registered' : 'URIUpdated',
+ eventClass: registered ? 'registration' : 'metadata',
+ agentId: BigInt(log.topics[1]).toString(),
+ owner: addrFromTopic(log.topics[2]),
+ agentUri: agentUri || null,
+ };
+ }
+
+ case TOPIC_METADATA_SET: {
+ if (log.topics.length < 2) return null;
+ const [key, value] = ABI_CODER.decode(['string', 'bytes'], log.data);
+ return {
+ ...base,
+ type: 'metadata_set',
+ eventName: 'MetadataSet',
+ eventClass: 'metadata',
+ agentId: BigInt(log.topics[1]).toString(),
+ key,
+ value: decodeMetadataValue(key, value),
+ };
+ }
+
+ case TOPIC_TRANSFER: {
+ // ERC-721 Transfer carries all three args indexed; a 3-topic log is the
+ // ERC-20 shape and cannot belong to this registry.
+ if (log.topics.length < 4) return null;
+ const from = addrFromTopic(log.topics[1]);
+ const to = addrFromTopic(log.topics[2]);
+ return {
+ ...base,
+ type: 'transfer',
+ eventName: 'Transfer',
+ eventClass: 'transfer',
+ agentId: BigInt(log.topics[3]).toString(),
+ from,
+ to,
+ // The mint leg of a registration duplicates the Registered event; the
+ // caller records it as ownership provenance but must not treat it as
+ // a change of hands.
+ isMint: from === ZERO_ADDRESS,
+ };
+ }
+
+ default:
+ return null;
+ }
+}
+
+/**
+ * Render a MetadataSet value for storage. Address-valued keys (agentWallet is
+ * the one the registry actually uses) are 20 raw bytes; everything else is
+ * rendered as UTF-8 when it decodes cleanly and left as hex when it does not,
+ * so a binary blob never lands in the index as replacement characters.
+ * @param {string} key
+ * @param {string} valueHex 0x-prefixed bytes from the log
+ * @returns {string|null}
+ */
+export function decodeMetadataValue(key, valueHex) {
+ if (typeof valueHex !== 'string' || !valueHex.startsWith('0x')) return null;
+ const body = valueHex.slice(2);
+ if (body.length === 0) return null;
+ if (body.length === 40) {
+ try {
+ return getAddress('0x' + body).toLowerCase();
+ } catch {
+ return valueHex;
+ }
+ }
+ const bytes = Uint8Array.from(body.match(/.{1,2}/g).map((b) => Number.parseInt(b, 16)));
+ try {
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
+ } catch {
+ return valueHex;
+ }
+}
diff --git a/api/_lib/migrations/20260811090000_agent_onchain_events.sql b/api/_lib/migrations/20260811090000_agent_onchain_events.sql
new file mode 100644
index 000000000..a1acca633
--- /dev/null
+++ b/api/_lib/migrations/20260811090000_agent_onchain_events.sql
@@ -0,0 +1,74 @@
+-- agent_onchain_events — the platform's own cross-chain index of agent
+-- lifecycle events, Solana first, EVM alongside it.
+--
+-- Before this table the indexers stored only the CURRENT state of an agent
+-- (one row per agent in erc8004_agents_index / solana_agents_index) plus the
+-- memo attestations in solana_attestations. Everything that HAPPENED to an
+-- agent after registration was dropped on the floor: a live census of the
+-- ERC-8004 Identity Registry on Base, Ethereum and Ethereum Sepolia (2026-08-11)
+-- showed the crawler indexing 7 of 66, 15 of 93 and 3 of 16 registry logs
+-- respectively, because it filtered on the single `Registered` topic. Ownership
+-- transfers, URI updates and metadata writes were invisible, which is also why
+-- an agent's indexed owner could never change.
+--
+-- One row per on-chain event, one table for every chain. `chain_id` is 0 on
+-- Solana so the uniqueness constraint below never sees a NULL (Postgres treats
+-- NULLs as distinct, which would let the same log be inserted twice).
+--
+-- occurred_at is the ABSOLUTE on-chain timestamp (EVM block timestamp / Solana
+-- blockTime), never an ingestion time; indexed_at is the ingestion time and is
+-- what the lag monitor on /status reads.
+--
+-- Apply: node scripts/apply-migrations.mjs --apply
+-- Idempotent.
+
+begin;
+
+create table if not exists agent_onchain_events (
+ id bigserial primary key,
+ chain text not null, -- 'solana' | 'evm'
+ chain_id integer not null default 0, -- EVM chain id; 0 on Solana
+ network text not null default 'mainnet', -- 'mainnet' | 'devnet' | 'testnet'
+ agent_ref text not null, -- EVM: '<chainId>:<agentId>'; Solana: asset/registry pubkey
+ event_class text not null, -- registration|metadata|transfer|token_launch|reputation|validation|delegation
+ event_name text not null, -- concrete on-chain name, e.g. 'Registered', 'SetAgentTokenV1'
+ tx text not null, -- tx hash (EVM) / signature (Solana)
+ log_index integer not null default 0, -- EVM log index; instruction ordinal on Solana
+ block_number bigint, -- EVM block number / Solana slot
+ occurred_at timestamptz not null, -- absolute on-chain timestamp
+ actor text, -- sender / attester / authority
+ counterparty text, -- transfer recipient, when the class has one
+ payload jsonb not null default '{}'::jsonb,
+ indexed_at timestamptz not null default now()
+);
+
+create unique index if not exists agent_onchain_events_uniq
+ on agent_onchain_events(chain, chain_id, tx, log_index);
+create index if not exists agent_onchain_events_agent_time
+ on agent_onchain_events(agent_ref, occurred_at desc);
+create index if not exists agent_onchain_events_class_time
+ on agent_onchain_events(event_class, occurred_at desc);
+create index if not exists agent_onchain_events_chain_indexed
+ on agent_onchain_events(chain, indexed_at desc);
+
+-- agent_event_cursor — per-agent crawl position for the Solana leg, which walks
+-- signatures per account rather than block ranges. Chain-agnostic on purpose so
+-- an account-scan leg on another chain reuses it.
+create table if not exists agent_event_cursor (
+ chain text not null,
+ chain_id integer not null default 0,
+ agent_ref text not null,
+ network text not null default 'mainnet',
+ last_tx text,
+ last_slot bigint,
+ last_event_at timestamptz,
+ last_indexed_at timestamptz not null default now(),
+ scanned integer not null default 0,
+ error text,
+ primary key (chain, chain_id, agent_ref)
+);
+
+create index if not exists agent_event_cursor_stale
+ on agent_event_cursor(last_indexed_at nulls first);
+
+commit;
diff --git a/api/_lib/onchain-events.js b/api/_lib/onchain-events.js
new file mode 100644
index 000000000..825885764
--- /dev/null
+++ b/api/_lib/onchain-events.js
@@ -0,0 +1,180 @@
+// Shared writer + reader for agent_onchain_events, the platform's own
+// cross-chain index of agent lifecycle events.
+//
+// Every indexer leg (EVM registry logs, Solana account signatures) normalizes
+// its raw event into the shape below and hands it here, so one table answers
+// "what has happened to this agent" regardless of chain. Solana leads: its
+// events carry chain 'solana' and chain_id 0; EVM events carry chain 'evm' and
+// the real chain id.
+//
+// occurred_at is always the ABSOLUTE on-chain timestamp (EVM block timestamp,
+// Solana blockTime). An event with no readable on-chain time is rejected rather
+// than stamped with now(), because a fabricated timestamp silently corrupts
+// every history render and every lag number computed from this table.
+
+import { sql } from './db.js';
+
+/**
+ * The event classes the index recognizes. A crawler emitting anything else is
+ * a bug, not a new feature: add the class here first so the API filters, the
+ * history UI and the lag monitor all learn about it at once.
+ */
+export const EVENT_CLASSES = Object.freeze([
+ 'registration', // agent minted / registered in a registry
+ 'metadata', // agentURI or a metadata key changed
+ 'transfer', // ownership moved between accounts
+ 'token_launch', // an SPL/ERC-20 token was bound to the agent
+ 'reputation', // feedback / stake / review attestation
+ 'validation', // validation request or response
+ 'delegation', // execution rights delegated to another account
+]);
+
+const CLASS_SET = new Set(EVENT_CLASSES);
+
+const MAX_TEXT = 256;
+
+const clip = (v) => {
+ if (v == null) return null;
+ const s = String(v).trim();
+ if (!s) return null;
+ return s.length > MAX_TEXT ? s.slice(0, MAX_TEXT) : s;
+};
+
+/**
+ * Compose the stable agent reference used as the index key.
+ * EVM agents are '<chainId>:<agentId>'; Solana agents are the account pubkey.
+ * @param {{ chain: string, chainId?: number, agentId?: string|number, ref?: string }} a
+ * @returns {string}
+ */
+export function agentRef({ chain, chainId, agentId, ref }) {
+ if (chain === 'evm') return `${chainId}:${agentId}`;
+ return String(ref ?? agentId);
+}
+
+/**
+ * Normalize one crawler event into the row shape, or return null when the
+ * event cannot be trusted (unknown class, missing tx, no on-chain timestamp).
+ * Pure: no DB, no clock. This is the seam the tests drive.
+ * @param {object} e
+ * @returns {object|null}
+ */
+export function normalizeEvent(e) {
+ if (!e || typeof e !== 'object') return null;
+ const chain = e.chain === 'evm' ? 'evm' : e.chain === 'solana' ? 'solana' : null;
+ if (!chain) return null;
+ if (!CLASS_SET.has(e.eventClass)) return null;
+
+ const tx = clip(e.tx);
+ const ref = clip(e.agentRef);
+ const name = clip(e.eventName);
+ if (!tx || !ref || !name) return null;
+
+ const occurredAt = toDate(e.occurredAt);
+ if (!occurredAt) return null;
+
+ const chainId = chain === 'evm' ? Number(e.chainId) : 0;
+ if (!Number.isInteger(chainId) || chainId < 0) return null;
+
+ const logIndex = Number.isInteger(e.logIndex) ? e.logIndex : 0;
+ const blockNumber =
+ e.blockNumber == null || !Number.isFinite(Number(e.blockNumber))
+ ? null
+ : Math.trunc(Number(e.blockNumber));
+
+ return {
+ chain,
+ chainId,
+ network: clip(e.network) || 'mainnet',
+ agentRef: ref,
+ eventClass: e.eventClass,
+ eventName: name,
+ tx,
+ logIndex,
+ blockNumber,
+ occurredAt,
+ actor: clip(e.actor),
+ counterparty: clip(e.counterparty),
+ payload: e.payload && typeof e.payload === 'object' ? e.payload : {},
+ };
+}
+
+/**
+ * Coerce an on-chain timestamp into a Date. Accepts a Date, an ISO string, a
+ * unix-seconds number (what both eth_getBlockByNumber and Solana blockTime
+ * hand back) and unix milliseconds. Returns null for anything unreadable or
+ * outside a sane range, so a bad value never lands as a real-looking row.
+ * @param {unknown} v
+ * @returns {Date|null}
+ */
+export function toDate(v) {
+ if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : v;
+ if (typeof v === 'string') {
+ const d = new Date(v);
+ return Number.isNaN(d.getTime()) ? null : d;
+ }
+ if (typeof v === 'number' && Number.isFinite(v)) {
+ // Below 1e12 the value is seconds (any ms timestamp since 2001 is larger).
+ const ms = v < 1e12 ? v * 1000 : v;
+ const d = new Date(ms);
+ if (Number.isNaN(d.getTime())) return null;
+ // Reject pre-2015 and far-future values: no agent registry predates them,
+ // so such a value is a decode bug, not history.
+ const year = d.getUTCFullYear();
+ if (year < 2015 || year > 2100) return null;
+ return d;
+ }
+ return null;
+}
+
+/**
+ * Persist a batch of events. Idempotent on (chain, chain_id, tx, log_index):
+ * a re-crawl of the same range inserts nothing. Invalid events are counted as
+ * `rejected` and reported rather than silently dropped.
+ * @param {object[]} events
+ * @returns {Promise<{ inserted: number, rejected: number }>}
+ */
+export async function recordEvents(events) {
+ let inserted = 0;
+ let rejected = 0;
+ for (const raw of events || []) {
+ const e = normalizeEvent(raw);
+ if (!e) {
+ rejected += 1;
+ continue;
+ }
+ const rows = await sql`
+ INSERT INTO agent_onchain_events
+ (chain, chain_id, network, agent_ref, event_class, event_name, tx,
+ log_index, block_number, occurred_at, actor, counterparty, payload)
+ VALUES
+ (${e.chain}, ${e.chainId}, ${e.network}, ${e.agentRef}, ${e.eventClass},
+ ${e.eventName}, ${e.tx}, ${e.logIndex}, ${e.blockNumber},
+ ${e.occurredAt.toISOString()}, ${e.actor}, ${e.counterparty},
+ ${JSON.stringify(e.payload)}::jsonb)
+ ON CONFLICT (chain, chain_id, tx, log_index) DO NOTHING
+ RETURNING id
+ `;
+ if (rows.length > 0) inserted += 1;
+ }
+ return { inserted, rejected };
+}
+
+/**
+ * Read one agent's event history, newest first.
+ * @param {{ agentRef: string, eventClass?: string|null, limit?: number }} q
+ * @returns {Promise<object[]>}
+ */
+export async function readAgentEvents({ agentRef: ref, eventClass = null, limit = 100 }) {
+ const cap = Math.min(Math.max(Number(limit) || 100, 1), 500);
+ const cls = eventClass && CLASS_SET.has(eventClass) ? eventClass : null;
+ return sql`
+ SELECT chain, chain_id, network, agent_ref, event_class, event_name, tx,
+ log_index, block_number, occurred_at, actor, counterparty, payload,
+ indexed_at
+ FROM agent_onchain_events
+ WHERE agent_ref = ${ref}
+ AND (${cls}::text IS NULL OR event_class = ${cls})
+ ORDER BY occurred_at DESC, log_index DESC
+ LIMIT ${cap}
+ `;
+}
diff --git a/contracts/test/IdentityRegistry.t.sol b/contracts/test/IdentityRegistry.t.sol
index 9f7d75732..1021a46e6 100644
--- a/contracts/test/IdentityRegistry.t.sol
+++ b/contracts/test/IdentityRegistry.t.sol
@@ -4,15 +4,85 @@ pragma solidity ^0.8.24;
import {Test} from "forge-std/Test.sol";
import {IdentityRegistry} from "../src/IdentityRegistry.sol";
+/// @notice Recipient with no `receive`, used to prove ID-9: an ETH payout that
+/// cannot be delivered reverts the whole call rather than debiting the
+/// agent's balance into nowhere.
+contract EthRejectingRecipient {}
+
+/// @notice Spender that re-enters `spend` from the payout callback. Proves the
+/// ID-10 guard, not merely that ordering happens to be safe.
+contract ReentrantSpender {
+ IdentityRegistry public immutable reg;
+ uint256 private _agentId;
+ uint256 private _amount;
+ bool private _armed;
+
+ bool public reentryAttempted;
+ bool public reentrySucceeded;
+
+ constructor(IdentityRegistry _reg) {
+ reg = _reg;
+ }
+
+ function drain(uint256 agentId, uint256 amount) external {
+ _agentId = agentId;
+ _amount = amount;
+ _armed = true;
+ reg.spend(agentId, payable(address(this)), amount, "first");
+ }
+
+ receive() external payable {
+ if (_armed) {
+ _armed = false;
+ reentryAttempted = true;
+ (bool ok,) = address(reg).call(
+ abi.encodeWithSelector(
+ IdentityRegistry.spend.selector, _agentId, payable(address(this)), _amount, "second"
+ )
+ );
+ reentrySucceeded = ok;
+ }
+ }
+}
+
+/// @dev Invariants under proof: ID-1 .. ID-11 of
+/// `specs/ECONOMY_CONTRACT_INVARIANTS.md`.
contract IdentityRegistryTest is Test {
IdentityRegistry reg;
address alice = address(0xA11CE);
address bob = address(0xB0B);
+ address carol = address(0xCA701);
+ address spender = address(0x5EED);
uint256 alicePk = 0xA11CE;
+ uint256 bobPk = 0xB0B;
function setUp() public {
reg = new IdentityRegistry();
alice = vm.addr(alicePk);
+ bob = vm.addr(bobPk);
+ vm.deal(alice, 100 ether);
+ vm.deal(bob, 100 ether);
+ vm.deal(carol, 100 ether);
+ }
+
+ /// @dev Build a valid EIP-712 `SetAgentWallet` signature for `pk`.
+ function _signSetWallet(uint256 pk, address signer, uint256 id, address delegate, uint256 deadline)
+ internal
+ view
+ returns (bytes memory)
+ {
+ bytes32 structHash = keccak256(
+ abi.encode(
+ keccak256("SetAgentWallet(uint256 agentId,address newWallet,uint256 nonce,uint256 deadline)"),
+ id,
+ delegate,
+ reg.nonces(signer),
+ deadline
+ )
+ );
+ bytes32 digest = keccak256(abi.encodePacked("\x19\x01", reg.DOMAIN_SEPARATOR(), structHash));
+ (uint8 v, bytes32 r, bytes32 s) = vm.sign(pk, digest);
+ return abi.encodePacked(r, s, v);
}
function testRegisterAssignsIncrementingIds() public {
@@ -137,4 +207,370 @@ contract IdentityRegistryTest is Test {
reg.register("ipfs://x");
assertTrue(reg.isAgent(1));
}
+
+ // ── ID-3: the delegation signature is owner-bound and single-use ─────────
+
+ function testSetAgentWalletRejectsNonOwnerSignature() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+
+ uint256 deadline = block.timestamp + 1 days;
+ // Bob signs over alice's nonce slot; the digest is well-formed but the
+ // recovered signer is not the agent owner.
+ bytes32 structHash = keccak256(
+ abi.encode(
+ keccak256("SetAgentWallet(uint256 agentId,address newWallet,uint256 nonce,uint256 deadline)"),
+ id,
+ address(0xDE1),
+ reg.nonces(alice),
+ deadline
+ )
+ );
+ bytes32 digest = keccak256(abi.encodePacked("\x19\x01", reg.DOMAIN_SEPARATOR(), structHash));
+ (uint8 v, bytes32 r, bytes32 s) = vm.sign(bobPk, digest);
+
+ vm.expectRevert(IdentityRegistry.InvalidSignature.selector);
+ reg.setAgentWallet(id, address(0xDE1), deadline, abi.encodePacked(r, s, v));
+ assertEq(reg.getAgentWallet(id), alice, "ID-3: a foreign signature must change nothing");
+ }
+
+ function testSetAgentWalletSignatureIsSingleUse() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+
+ uint256 deadline = block.timestamp + 1 days;
+ bytes memory sig = _signSetWallet(alicePk, alice, id, address(0xDE1), deadline);
+
+ reg.setAgentWallet(id, address(0xDE1), deadline, sig);
+
+ // Replaying the identical signature must fail: the nonce moved on.
+ vm.expectRevert(IdentityRegistry.InvalidSignature.selector);
+ reg.setAgentWallet(id, address(0xDE1), deadline, sig);
+ }
+
+ function testSetAgentWalletSignatureIsBoundToTheWallet() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+
+ uint256 deadline = block.timestamp + 1 days;
+ bytes memory sig = _signSetWallet(alicePk, alice, id, address(0xDE1), deadline);
+
+ // Same signature, different delegate: the struct hash no longer matches.
+ vm.expectRevert(IdentityRegistry.InvalidSignature.selector);
+ reg.setAgentWallet(id, address(0xBAD), deadline, sig);
+ }
+
+ function testSetAgentWalletAtExactDeadlineSucceeds() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+
+ vm.warp(1_000);
+ uint256 deadline = block.timestamp;
+ bytes memory sig = _signSetWallet(alicePk, alice, id, address(0xDE1), deadline);
+
+ reg.setAgentWallet(id, address(0xDE1), deadline, sig);
+ assertEq(reg.getAgentWallet(id), address(0xDE1));
+ }
+
+ function testUnsetAgentWalletOnlyOwner() public {
+ testSetAgentWalletWithValidSignature();
+
+ vm.prank(bob);
+ vm.expectRevert(IdentityRegistry.NotAgentOwner.selector);
+ reg.unsetAgentWallet(1);
+
+ assertEq(reg.getAgentWallet(1), address(0xDE1));
+ }
+
+ // ── ID-2: NFT transfer carries every right with it ───────────────────────
+
+ function testNftTransferMovesControl() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+
+ vm.prank(alice);
+ reg.transferFrom(alice, bob, id);
+
+ vm.prank(alice);
+ vm.expectRevert(IdentityRegistry.NotAgentOwner.selector);
+ reg.setAgentURI(id, "ipfs://stale-owner");
+
+ vm.prank(bob);
+ reg.setAgentURI(id, "ipfs://new-owner");
+ assertEq(reg.tokenURI(id), "ipfs://new-owner");
+ assertEq(reg.getAgentWallet(id), bob, "ID-4: the fallback follows the current owner");
+ }
+
+ // ── ID-5: ETH only enters through deposit ────────────────────────────────
+
+ function testBareEthTransferReverts() public {
+ vm.prank(alice);
+ (bool ok,) = address(reg).call{value: 1 ether}("");
+ assertFalse(ok, "ID-5: receive() must reject unattributed ETH");
+ assertEq(address(reg).balance, 0);
+ }
+
+ function testUnknownSelectorWithValueReverts() public {
+ vm.prank(alice);
+ (bool ok,) = address(reg).call{value: 1 ether}(abi.encodeWithSignature("nope()"));
+ assertFalse(ok, "ID-5: fallback() must reject unattributed ETH");
+ assertEq(address(reg).balance, 0);
+ }
+
+ function testDepositCreditsTheNamedAgent() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+
+ // Anyone may fund an agent, including a third party operator.
+ vm.prank(carol);
+ reg.deposit{value: 3 ether}(id);
+
+ assertEq(reg.agentBalance(id), 3 ether);
+ assertEq(address(reg).balance, 3 ether);
+ }
+
+ function testDepositToUnknownAgentReverts() public {
+ vm.prank(alice);
+ vm.expectRevert(IdentityRegistry.UnknownAgent.selector);
+ reg.deposit{value: 1 ether}(999);
+ }
+
+ function testZeroDepositReverts() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+
+ vm.prank(alice);
+ vm.expectRevert(IdentityRegistry.ZeroDeposit.selector);
+ reg.deposit{value: 0}(id);
+ }
+
+ // ── ID-6 / ID-8: per-agent balances are isolated ─────────────────────────
+
+ function testAgentBalancesAreIsolated() public {
+ vm.prank(alice);
+ uint256 a = reg.register("ipfs://a");
+ vm.prank(bob);
+ uint256 b = reg.register("ipfs://b");
+
+ vm.prank(alice);
+ reg.deposit{value: 5 ether}(a);
+ vm.prank(bob);
+ reg.deposit{value: 1 ether}(b);
+
+ // Alice authorizes a spender generously on HER agent only.
+ vm.prank(alice);
+ reg.setSpendAllowance(a, spender, 5 ether);
+
+ // That spender has no standing on bob's agent, whatever the allowance.
+ vm.prank(spender);
+ vm.expectRevert(bytes("allowance exceeded"));
+ reg.spend(b, payable(spender), 1 ether, "cross-agent drain");
+
+ assertEq(reg.agentBalance(b), 1 ether, "ID-8: another agent's balance is untouchable");
+ assertGe(address(reg).balance, reg.agentBalance(a) + reg.agentBalance(b), "ID-6: held ETH covers every agent");
+ }
+
+ function testSpendCannotExceedTheAgentsOwnBalance() public {
+ vm.prank(alice);
+ uint256 a = reg.register("ipfs://a");
+ vm.prank(bob);
+ uint256 b = reg.register("ipfs://b");
+
+ vm.prank(alice);
+ reg.deposit{value: 1 ether}(a);
+ vm.prank(bob);
+ reg.deposit{value: 9 ether}(b);
+
+ // Allowance is larger than the agent's own deposit; the deposit wins.
+ vm.prank(alice);
+ reg.setSpendAllowance(a, spender, 10 ether);
+
+ vm.prank(spender);
+ vm.expectRevert(IdentityRegistry.InsufficientAgentBalance.selector);
+ reg.spend(a, payable(spender), 2 ether, "over-draw");
+
+ assertEq(address(reg).balance, 10 ether);
+ }
+
+ // ── ID-7: allowance is a ceiling, not a mint ─────────────────────────────
+
+ function testSpendDebitsAllowanceAndBalanceTogether() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ vm.prank(alice);
+ reg.deposit{value: 4 ether}(id);
+ vm.prank(alice);
+ reg.setSpendAllowance(id, spender, 3 ether);
+
+ vm.prank(spender);
+ reg.spend(id, payable(carol), 1 ether, "invoice-1");
+
+ assertEq(reg.spendAllowance(id, spender), 2 ether);
+ assertEq(reg.agentBalance(id), 3 ether);
+ assertEq(carol.balance, 101 ether);
+
+ // Exhaust the allowance, then prove it is really exhausted.
+ vm.prank(spender);
+ reg.spend(id, payable(carol), 2 ether, "invoice-2");
+ assertEq(reg.spendAllowance(id, spender), 0);
+
+ vm.prank(spender);
+ vm.expectRevert(bytes("allowance exceeded"));
+ reg.spend(id, payable(carol), 1 wei, "invoice-3");
+ }
+
+ function testSpendWithoutAllowanceReverts() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ vm.prank(alice);
+ reg.deposit{value: 1 ether}(id);
+
+ vm.prank(bob);
+ vm.expectRevert(bytes("allowance exceeded"));
+ reg.spend(id, payable(bob), 1 wei, "unauthorized");
+ }
+
+ function testSetSpendAllowanceOnlyOwner() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+
+ vm.prank(bob);
+ vm.expectRevert(IdentityRegistry.NotAgentOwner.selector);
+ reg.setSpendAllowance(id, bob, 100 ether);
+
+ assertEq(reg.spendAllowance(id, bob), 0);
+ }
+
+ function testAllowanceCanBeRevokedToZero() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ vm.prank(alice);
+ reg.deposit{value: 1 ether}(id);
+ vm.prank(alice);
+ reg.setSpendAllowance(id, spender, 1 ether);
+
+ vm.prank(alice);
+ reg.setSpendAllowance(id, spender, 0);
+
+ vm.prank(spender);
+ vm.expectRevert(bytes("allowance exceeded"));
+ reg.spend(id, payable(spender), 1 wei, "revoked");
+ }
+
+ // ── ID-2 / ID-9 / ID-11: withdrawal guards ───────────────────────────────
+
+ function testWithdrawOnlyOwnerAndOnlyOwnBalance() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ vm.prank(alice);
+ reg.deposit{value: 2 ether}(id);
+
+ vm.prank(bob);
+ vm.expectRevert(IdentityRegistry.NotAgentOwner.selector);
+ reg.withdraw(id, payable(bob), 1 ether);
+
+ vm.prank(alice);
+ vm.expectRevert(IdentityRegistry.InsufficientAgentBalance.selector);
+ reg.withdraw(id, payable(alice), 3 ether);
+
+ uint256 before = alice.balance;
+ vm.prank(alice);
+ reg.withdraw(id, payable(alice), 2 ether);
+ assertEq(alice.balance - before, 2 ether);
+ assertEq(reg.agentBalance(id), 0);
+ }
+
+ function testWithdrawRejectsZeroRecipient() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ vm.prank(alice);
+ reg.deposit{value: 1 ether}(id);
+
+ vm.prank(alice);
+ vm.expectRevert(IdentityRegistry.ZeroRecipient.selector);
+ reg.withdraw(id, payable(address(0)), 1 ether);
+
+ assertEq(reg.agentBalance(id), 1 ether, "ID-11: the balance survives a rejected payout");
+ }
+
+ function testSpendRejectsZeroRecipient() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ vm.prank(alice);
+ reg.deposit{value: 1 ether}(id);
+ vm.prank(alice);
+ reg.setSpendAllowance(id, spender, 1 ether);
+
+ vm.prank(spender);
+ vm.expectRevert(IdentityRegistry.ZeroRecipient.selector);
+ reg.spend(id, payable(address(0)), 1 ether, "burn");
+
+ assertEq(reg.agentBalance(id), 1 ether);
+ assertEq(reg.spendAllowance(id, spender), 1 ether);
+ }
+
+ function testPayoutFailureRevertsTheWholeCall() public {
+ EthRejectingRecipient sink = new EthRejectingRecipient();
+
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ vm.prank(alice);
+ reg.deposit{value: 1 ether}(id);
+
+ vm.prank(alice);
+ vm.expectRevert(IdentityRegistry.EthTransferFailed.selector);
+ reg.withdraw(id, payable(address(sink)), 1 ether);
+
+ assertEq(reg.agentBalance(id), 1 ether, "ID-9: accounting must not drift from the ETH actually held");
+ assertEq(address(reg).balance, 1 ether);
+ }
+
+ // ── ID-10: reentrancy ────────────────────────────────────────────────────
+
+ function testReentrantSpendIsBlocked() public {
+ vm.prank(alice);
+ uint256 id = reg.register("ipfs://x");
+ vm.prank(alice);
+ reg.deposit{value: 4 ether}(id);
+
+ ReentrantSpender attacker = new ReentrantSpender(reg);
+ vm.prank(alice);
+ reg.setSpendAllowance(id, address(attacker), 4 ether);
+
+ attacker.drain(id, 1 ether);
+
+ assertTrue(attacker.reentryAttempted(), "the attack must actually have been attempted");
+ assertFalse(attacker.reentrySucceeded(), "ID-10: nonReentrant must reject the second entry");
+ assertEq(address(attacker).balance, 1 ether, "only one payout may land");
+ assertEq(reg.agentBalance(id), 3 ether);
+ assertEq(reg.spendAllowance(id, address(attacker)), 3 ether);
+ }
+
+ // ── ID-1: id assignment ──────────────────────────────────────────────────
+
+ function testAgentIdsNeverRepeatAcrossOwners() public {
+ vm.prank(alice);
+ uint256 first = reg.register("a");
+ vm.prank(alice);
+ uint256 second = reg.register("b");
+ vm.prank(bob);
+ uint256 third = reg.register("c");
+
+ assertEq(first, 1);
+ assertEq(second, 2);
+ assertEq(third, 3);
+ assertFalse(reg.isAgent(4));
+ assertEq(reg.balanceOf(alice), 2);
+ assertEq(reg.totalSupply(), 3);
+ }
+
+ function testGetMetadataOnUnknownAgentReverts() public {
+ vm.expectRevert();
+ reg.getMetadata(999, "k");
+ }
+
+ function testGetAgentWalletOnUnknownAgentReverts() public {
+ vm.expectRevert();
+ reg.getAgentWallet(999);
+ }
}
diff --git a/contracts/test/ReputationRegistry.t.sol b/contracts/test/ReputationRegistry.t.sol
index fec688f15..6af589c41 100644
--- a/contracts/test/ReputationRegistry.t.sol
+++ b/contracts/test/ReputationRegistry.t.sol
@@ -75,6 +75,7 @@ contract ReputationRegistryTest is Test {
vm.prank(alice);
identity.register("ipfs://alice");
+ vm.deal(alice, 10 ether);
vm.deal(bob, 10 ether);
vm.deal(carol, 10 ether);
vm.deal(dave, 10 ether);
@@ -413,7 +414,9 @@ contract ReputationRegistryTest is Test {
assertTrue(attacker.reentryAttempted(), "the attack must actually have been attempted");
assertFalse(attacker.reentrySucceeded(), "REP-10: nonReentrant must reject the second entry");
- assertEq(address(attacker).balance, 1 ether - 0.2 ether + 0.2 ether);
+ // The 0.2 ETH stake came from this test contract, so the attacker keeps
+ // its dealt balance plus exactly one refund, never two.
+ assertEq(address(attacker).balance, 1 ether + 0.2 ether);
assertEq(rep.getStake(1, address(attacker)), 0);
assertEq(rep.getStake(1, carol), 0.5 ether, "REP-10: the other staker's escrow is untouched");
}