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.

fix(erc8004): target the ValidationRegistry that is actually deployed

nirholas7cbd8dc1e3a4
diff --git a/api/_lib/erc8004-chains.js b/api/_lib/erc8004-chains.js
index 9adc24e26..4753d9764 100644
--- a/api/_lib/erc8004-chains.js
+++ b/api/_lib/erc8004-chains.js
@@ -10,26 +10,41 @@
export const IDENTITY_REGISTRY_MAINNET = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';
export const IDENTITY_REGISTRY_TESTNET = '0x8004A818BFB912233c491871b3d84c89A494BD9e';
-// ValidationRegistry — CREATE2-deterministic, one address per network class.
-// Testnet is live (Base Sepolia and siblings). Mainnet is pending task 01
-// (contracts/script/DeployValidationMainnet.s.sol); leave '' until bytecode is
-// confirmed on every chain, then fill it here AND in src/erc8004/abi.js +
-// sdk/src/erc8004/abi.js (task 05 parity). Never list an address with no code.
+// ValidationRegistry: the canonical ERC-8004 reference deployment
+// (`ValidationRegistryUpgradeable` behind an ERC-1967 proxy), the same family of
+// 0x8004-vanity addresses as the Identity Registry above, one address per
+// network class. Live on the testnet class (bytecode probed 2026-08-06 on Base
+// Sepolia, Sepolia, Arbitrum Sepolia and OP Sepolia). No mainnet deployment
+// exists yet, so mainnet stays '' and the badge renders nothing there.
+//
+// This is NOT contracts/src/ValidationRegistry.sol. That contract is ours and is
+// deployed nowhere; the address below answers a different, standard interface
+// (request/response, no validator allow-list), which is what the ABI below and
+// api/_lib/validation-attest.js target. Never point these constants at an
+// address without first probing its bytecode for the selectors we call.
export const VALIDATION_REGISTRY_MAINNET = '';
export const VALIDATION_REGISTRY_TESTNET = '0x8004Cb1BF31DAf7788923b405b754f57acEB4272';
/**
* Minimal human-readable ValidationRegistry ABI for server reads + attestations.
- * Mirrors contracts/src/ValidationRegistry.sol. The Validation tuple order is
- * load-bearing — keep it in lockstep with the struct.
+ * Mirrors the deployed `ValidationRegistryUpgradeable`.
+ *
+ * The model is two-legged and deliberate: the agent's ERC-721 owner (or an
+ * approved operator) opens a request naming a validator, and only that validator
+ * can answer it. `response` is a 0..100 score, and `responseURI` is emitted in
+ * the event but NOT stored, so the pinned report URL cannot be read back from
+ * storage. `tag` is stored and is where our validation kind lives.
*/
export const VALIDATION_REGISTRY_ABI = [
- 'function recordValidation(uint256 agentId, bool passed, bytes32 proofHash, string proofURI, string kind) external',
- 'function isValidator(address) external view returns (bool)',
- 'function owner() external view returns (address)',
- 'function getValidationCount(uint256 agentId) external view returns (uint256)',
- 'function getLatestByKind(uint256 agentId, string kind) external view returns (tuple(address validator, bool passed, bytes32 proofHash, string proofURI, uint64 timestamp, string kind))',
- 'event ValidationRecorded(uint256 indexed agentId, address indexed validator, bool passed, bytes32 proofHash, string kind)',
+ 'function validationRequest(address validatorAddress, uint256 agentId, string requestURI, bytes32 requestHash) external',
+ 'function validationResponse(bytes32 requestHash, uint8 response, string responseURI, bytes32 responseHash, string tag) external',
+ 'function getValidationStatus(bytes32 requestHash) external view returns (address validatorAddress, uint256 agentId, uint8 response, bytes32 responseHash, string tag, uint256 lastUpdate)',
+ 'function getAgentValidations(uint256 agentId) external view returns (bytes32[])',
+ 'function getValidatorRequests(address validatorAddress) external view returns (bytes32[])',
+ 'function getSummary(uint256 agentId, address[] validatorAddresses, string tag) external view returns (uint64 count, uint8 avgResponse)',
+ 'function getIdentityRegistry() external view returns (address)',
+ 'event ValidationRequest(address indexed validatorAddress, uint256 indexed agentId, string requestURI, bytes32 indexed requestHash)',
+ 'event ValidationResponse(address indexed validatorAddress, uint256 indexed agentId, bytes32 indexed requestHash, uint8 response, string responseURI, bytes32 responseHash, string tag)',
];
/**
@@ -305,7 +320,7 @@ export const CHAINS = [
];
// Decorate each chain with its ValidationRegistry address (deterministic by
-// network class). Mainnet entries carry '' until task 01 confirms bytecode.
+// network class). Mainnet entries carry '' until a mainnet deployment exists.
for (const c of CHAINS) {
c.validationRegistry = c.testnet ? VALIDATION_REGISTRY_TESTNET : VALIDATION_REGISTRY_MAINNET;
}
diff --git a/api/_lib/migrations/20260806120000_erc8004_validation_request_hash.sql b/api/_lib/migrations/20260806120000_erc8004_validation_request_hash.sql
new file mode 100644
index 000000000..1d006d9e9
--- /dev/null
+++ b/api/_lib/migrations/20260806120000_erc8004_validation_request_hash.sql
@@ -0,0 +1,10 @@
+-- ERC-8004 validation: remember which on-chain request an attestation answered.
+--
+-- The deployed ValidationRegistry is request/response based: the agent's owner
+-- opens a request (a bytes32 id) naming a validator, and the validator answers
+-- that id. Storing the id lets ops (and a re-validation) find the exact request a
+-- verdict belongs to without re-deriving it from the GLB bytes, and lets the
+-- badge match an index row to the on-chain record it came from.
+
+ALTER TABLE erc8004_agents_index
+ ADD COLUMN IF NOT EXISTS validation_request_hash text;
diff --git a/api/_lib/onchain.js b/api/_lib/onchain.js
index 110285072..08f748cc2 100644
--- a/api/_lib/onchain.js
+++ b/api/_lib/onchain.js
@@ -18,7 +18,7 @@ import {
VALIDATION_REGISTRY_ABI,
validationRegistryFor,
} from './erc8004-chains.js';
-import { KIND_GLB_SCHEMA } from '../../src/erc8004/validation-report.js';
+import { KIND_GLB_SCHEMA, responsePassed } from '../../src/erc8004/validation-report.js';
import { fetchSafePublicUrlPinned } from './ssrf-guard.js';
const IDENTITY_ABI = [
@@ -437,16 +437,29 @@ function _withTimeout(promise, ms) {
const VALIDATION_CACHE_TTL_S = 60;
+// How many of an agent's most recent request hashes to inspect. Requests are
+// appended, so the tail is the newest; an agent with a long re-validation history
+// never turns one badge into an unbounded fan-out of RPC reads.
+const VALIDATION_SCAN_LIMIT = 12;
+
/**
* Read the latest on-chain validation attestation for an agent — no wallet
* required, so any surface can render the "Validated" badge straight from the
* server. Authoritative source is the on-chain ValidationRegistry; this layers a
* 60s cache on top (validation is re-runnable, so the badge stays fresh).
*
+ * The registry indexes validations by request hash, and stores the validator's
+ * `tag` only once the request has been answered, so an unanswered request is
+ * distinguishable from a verdict: we read the agent's recent request hashes, keep
+ * the ones answered with our kind, and take the most recently updated. The pinned
+ * report URL is NOT in registry storage (the contract only emits it), so callers
+ * that want the proof link merge it from the index cache and check it against
+ * `proofHash`.
+ *
* Always resolves (never throws) so a badge fetch can't break a page:
* - { available: false } registry not deployed on this chain
- * - { available: true, exists:false } deployed, but no attestation yet
- * - { available: true, exists:true, passed, proofHash, proofURI, … }
+ * - { available: true, exists:false, openRequests } deployed, no verdict yet
+ * - { available: true, exists:true, passed, score, proofHash, requestHash, … }
*
* @param {{ chainId: number, agentId: string|number, kind?: string }} p
*/
@@ -481,32 +494,69 @@ export async function resolveLatestValidation({ chainId, agentId, kind = KIND_GL
}
const registry = new Contract(registryAddr, VALIDATION_REGISTRY_ABI, provider);
- let v;
+ let hashes;
try {
- v = await _withTimeout(registry.getLatestByKind(BigInt(agentId), kind), 4000);
+ hashes = await _withTimeout(registry.getAgentValidations(BigInt(agentId)), 4000);
} catch (err) {
- // getLatestByKind reverts with "no validation" when none exists — that's a
- // normal empty result, not an error.
+ // An agent nobody has ever requested validation for reads as empty, and a
+ // chain whose registry predates this agent reverts — both are "no verdict",
+ // not an error worth surfacing on a badge.
const msg = String(err?.shortMessage || err?.reason || err?.message || '');
- if (/no validation/i.test(msg) || err?.code === 'CALL_EXCEPTION') {
+ if (err?.code === 'CALL_EXCEPTION' || err?.code === 'BAD_DATA') {
await cacheSet(cacheKey, base, VALIDATION_CACHE_TTL_S);
return base;
}
return { ...base, error: `chain_read: ${msg}` };
}
- const timestamp = Number(v.timestamp);
+ const recent = Array.from(hashes || []).slice(-VALIDATION_SCAN_LIMIT).reverse();
+ if (!recent.length) {
+ const empty = { ...base, openRequests: 0 };
+ await cacheSet(cacheKey, empty, VALIDATION_CACHE_TTL_S);
+ return empty;
+ }
+
+ const statuses = await Promise.all(
+ recent.map((hash) =>
+ _withTimeout(registry.getValidationStatus(hash), 4000)
+ .then((s) => ({
+ requestHash: hash,
+ validator: s[0],
+ response: Number(s[2]),
+ responseHash: s[3],
+ tag: s[4],
+ lastUpdate: Number(s[5]),
+ }))
+ .catch(() => null),
+ ),
+ );
+
+ const answered = statuses.filter((s) => s && s.tag === kind);
+ if (!answered.length) {
+ // Requests exist but none is answered for this kind: an attestation is
+ // outstanding, which the badge shows as pending rather than "not validated".
+ const openRequests = statuses.filter((s) => s && !s.tag).length;
+ const empty = { ...base, openRequests };
+ await cacheSet(cacheKey, empty, VALIDATION_CACHE_TTL_S);
+ return empty;
+ }
+
+ const latest = answered.reduce((a, b) => (b.lastUpdate > a.lastUpdate ? b : a));
const result = {
...base,
exists: true,
- passed: Boolean(v.passed),
- proofHash: v.proofHash,
- proofURI: v.proofURI || null,
- proofUrlResolved: v.proofURI ? resolveURI(v.proofURI) : null,
- validator: _safeAddress(v.validator),
- validatorExplorer: explorer && v.validator ? `${explorer}/address/${v.validator}` : null,
- timestamp,
- validatedAt: timestamp ? new Date(timestamp * 1000).toISOString() : null,
+ passed: responsePassed(latest.response),
+ score: latest.response,
+ requestHash: latest.requestHash,
+ proofHash: latest.responseHash,
+ // The registry emits responseURI but never stores it, so the pinned report
+ // link is merged from the index cache (guarded by proofHash) by the caller.
+ proofURI: null,
+ proofUrlResolved: null,
+ validator: _safeAddress(latest.validator),
+ validatorExplorer: explorer && latest.validator ? `${explorer}/address/${latest.validator}` : null,
+ timestamp: latest.lastUpdate,
+ validatedAt: latest.lastUpdate ? new Date(latest.lastUpdate * 1000).toISOString() : null,
};
await cacheSet(cacheKey, result, VALIDATION_CACHE_TTL_S);
return result;
diff --git a/api/_lib/validation-attest.js b/api/_lib/validation-attest.js
index 1e78ff66b..db8850798 100644
--- a/api/_lib/validation-attest.js
+++ b/api/_lib/validation-attest.js
@@ -8,14 +8,17 @@
* ⇒ structurally valid; parse-failure ⇒ a hard error in the report.
* 2. Independently sha256 the exact bytes (byte-check, surfaced separately —
* a passing schema validation never overrides byte identity, per spec).
- * 3. Build the canonical report, pin it to R2, keccak256-hash the pinned bytes.
- * 4. Sign + send recordValidation(agentId, passed, proofHash, proofURI, kind)
- * from the platform validator key, which must be allow-listed on the chain.
+ * 3. Build the canonical report and pin it to R2. `hashReport()` keccaks the
+ * report's compact JSON, so a verifier fetches the pinned file, re-stringifies
+ * it without indentation, re-hashes, and compares against the chain.
+ * 4. Answer the agent's on-chain validation request from the platform validator
+ * key with validationResponse(requestHash, score, proofURI, proofHash, kind),
+ * opening the request first when the platform is allowed to.
*
* Best-effort by contract: callers wrap this in try/catch — a validation failure
- * (or missing key / undeployed registry / not-allow-listed validator) must never
- * block or revert the registration itself. Errors carry a machine-readable
- * `.code` so the caller can surface a clear ops state instead of a silent skip.
+ * (or missing key / undeployed registry / no open request) must never block or
+ * revert the registration itself. Errors carry a machine-readable `.code` so the
+ * caller can surface a clear ops state instead of a silent skip.
*/
import { createHash } from 'node:crypto';
@@ -27,7 +30,23 @@ import { evmRpcEndpoints } from './evm/rpc.js';
import { putObject, publicUrl } from './r2.js';
import { assertSafePublicUrl, SsrfBlockedError } from './ssrf-guard.js';
import { inspectModel, suggestOptimizations } from './model-inspect.js';
-import { buildGlbReport, hashReport, reportPassed, KIND_GLB_SCHEMA } from '../../src/erc8004/validation-report.js';
+import {
+ buildGlbReport,
+ hashReport,
+ reportPassed,
+ responseForPassed,
+ validationRequestHash,
+ KIND_GLB_SCHEMA,
+} from '../../src/erc8004/validation-report.js';
+
+// Just the ERC-721 authority reads the registry itself checks before accepting a
+// validationRequest — enough to tell "we can open this request" from "the owner
+// has to".
+const IDENTITY_AUTH_ABI = [
+ 'function ownerOf(uint256 tokenId) external view returns (address)',
+ 'function getApproved(uint256 tokenId) external view returns (address)',
+ 'function isApprovedForAll(address owner, address operator) external view returns (bool)',
+];
const MAX_FETCH_BYTES = 16 * 1024 * 1024;
const FETCH_TIMEOUT_MS = 20_000;
@@ -121,21 +140,81 @@ async function pinReport(report, chainId, agentId) {
return publicUrl(key);
}
+/** Read a request's on-chain status. Returns null when no such request exists. */
+async function readRequest(registry, requestHash) {
+ try {
+ const s = await registry.getValidationStatus(requestHash);
+ return {
+ validator: s[0],
+ agentId: s[1],
+ response: Number(s[2]),
+ responseHash: s[3],
+ tag: s[4],
+ lastUpdate: Number(s[5]),
+ };
+ } catch (err) {
+ // The registry reverts require("unknown") for a hash it has never seen.
+ if (err?.code === 'CALL_EXCEPTION' || /unknown/i.test(String(err?.shortMessage || err?.message))) {
+ return null;
+ }
+ throw new AttestError('registry_read_failed', `could not read validation status: ${err.message}`);
+ }
+}
+
+/**
+ * Can `validator` open a validation request for this agent? The registry allows
+ * the agent's ERC-721 owner, a per-token approved operator, or an operator
+ * approved for all of the owner's tokens.
+ */
+async function canOpenRequest({ identityAddr, provider, agentId, validator }) {
+ if (!identityAddr) return false;
+ const identity = new Contract(identityAddr, IDENTITY_AUTH_ABI, provider);
+ const id = BigInt(agentId);
+ let owner;
+ try {
+ owner = await identity.ownerOf(id);
+ } catch {
+ return false;
+ }
+ if (owner.toLowerCase() === validator.toLowerCase()) return true;
+ const [approved, forAll] = await Promise.all([
+ identity.getApproved(id).catch(() => null),
+ identity.isApprovedForAll(owner, validator).catch(() => false),
+ ]);
+ return Boolean(forAll) || (approved && approved.toLowerCase() === validator.toLowerCase());
+}
+
/**
- * Full attestation: validate the GLB, pin the report, sign + record on-chain.
+ * Full attestation: validate the GLB, pin the report, answer on-chain.
+ *
+ * The deployed ValidationRegistry is two-legged: the agent's owner (or an
+ * approved operator) opens a request naming a validator, and only that validator
+ * may answer it. So this runs one of three ways:
+ *
+ * - a request for our validator already exists → answer it (this is also the
+ * re-validation path: answering again updates the record in place);
+ * - no request, but the platform validator is the owner/an approved operator
+ * → open the request itself, then answer it;
+ * - no request and no authority → throw `validation_request_required` carrying
+ * the exact call the owner's wallet must submit, so the UI can prompt for it.
+ *
+ * Best-effort by contract: callers wrap this in try/catch and registration is
+ * never blocked by the outcome.
*
* @param {object} p
* @param {number} p.chainId
* @param {string|number} p.agentId
* @param {string} p.glbUrl
* @param {string} p.validatedAt ISO timestamp (caller-supplied; deterministic hashing).
+ * @param {string} [p.requestHash] Answer this exact request (the owner just opened it).
* @returns {Promise<{
* passed: boolean, proofHash: string, proofURI: string, txHash: string,
+ * requestHash: string, requestTxHash: string|null, score: number,
* sha256: string, validatedAt: string, kind: string, chainId: number,
* agentId: string, validator: string, report: object,
* }>}
*/
-export async function attestValidation({ chainId, agentId, glbUrl, validatedAt }) {
+export async function attestValidation({ chainId, agentId, glbUrl, validatedAt, requestHash: pinnedHash }) {
const chain = CHAIN_BY_ID[chainId];
if (!chain) throw new AttestError('unsupported_chain', `unsupported chain ${chainId}`);
@@ -151,7 +230,7 @@ export async function attestValidation({ chainId, agentId, glbUrl, validatedAt }
if (!pk) {
throw new AttestError(
'validator_key_not_configured',
- 'VALIDATOR_PRIVATE_KEY is not set — cannot sign attestations.',
+ 'VALIDATOR_PRIVATE_KEY is not set, so no attestation can be signed.',
);
}
@@ -167,39 +246,80 @@ export async function attestValidation({ chainId, agentId, glbUrl, validatedAt }
const wallet = new Wallet(pk, provider);
const registry = new Contract(registryAddr, VALIDATION_REGISTRY_ABI, wallet);
- // 3. The platform key must be allow-listed on THIS chain — surface a clear
- // ops error rather than letting the tx revert with NotValidator().
- let allowed;
- try {
- allowed = await registry.isValidator(wallet.address);
- } catch (err) {
- throw new AttestError('registry_read_failed', `could not read validator allow-list: ${err.message}`);
+ // 3. Find (or open) the request this attestation answers.
+ const requestHash = pinnedHash || validationRequestHash({ chainId, agentId, seed: `0x${sha256}` });
+ const existing = await readRequest(registry, requestHash);
+
+ if (existing && existing.validator.toLowerCase() !== wallet.address.toLowerCase()) {
+ throw new AttestError(
+ 'request_not_for_validator',
+ `Request ${requestHash} names validator ${existing.validator}, not the platform validator ${wallet.address}.`,
+ );
}
- if (!allowed) {
+ if (existing && String(existing.agentId) !== String(agentId)) {
throw new AttestError(
- 'validator_not_allowlisted',
- `Validator ${wallet.address} is not allow-listed on ${chain.name}. ` +
- `Run addValidator(${wallet.address}) as the registry owner (task 01 step 6).`,
+ 'request_agent_mismatch',
+ `Request ${requestHash} belongs to agent ${existing.agentId}, not ${agentId}.`,
);
}
- // 4. Pin the report, hash the pinned bytes, record on-chain.
+ let requestTxHash = null;
+ if (!existing) {
+ const authorized = await canOpenRequest({
+ identityAddr: chain.registry,
+ provider,
+ agentId,
+ validator: wallet.address,
+ });
+ if (!authorized) {
+ const err = new AttestError(
+ 'validation_request_required',
+ `Agent ${agentId} has no open validation request for ${wallet.address}. The agent owner must call ` +
+ `validationRequest(${wallet.address}, ${agentId}, <glbUrl>, ${requestHash}) on ${registryAddr}, then retry.`,
+ );
+ err.request = {
+ chainId,
+ agentId: String(agentId),
+ registry: registryAddr,
+ validatorAddress: wallet.address,
+ requestURI: glbUrl,
+ requestHash,
+ };
+ throw err;
+ }
+ let reqTx;
+ try {
+ reqTx = await registry.validationRequest(wallet.address, BigInt(agentId), glbUrl, requestHash);
+ } catch (err) {
+ throw new AttestError('request_failed', `validationRequest reverted: ${err.shortMessage || err.message}`);
+ }
+ await reqTx.wait();
+ requestTxHash = reqTx.hash;
+ }
+
+ // 4. Pin the report, then answer the request. `responseURI` is emitted but not
+ // stored by the registry, so the pinned URL is recovered from the event (or
+ // our index cache); `responseHash` is the integrity check that binds them.
const proofURI = await pinReport(report, chainId, agentId);
const proofHash = hashReport(report);
+ const score = responseForPassed(passed);
let tx;
try {
- tx = await registry.recordValidation(BigInt(agentId), passed, proofHash, proofURI, KIND_GLB_SCHEMA);
+ tx = await registry.validationResponse(requestHash, score, proofURI, proofHash, KIND_GLB_SCHEMA);
} catch (err) {
- throw new AttestError('record_failed', `recordValidation reverted: ${err.shortMessage || err.message}`);
+ throw new AttestError('response_failed', `validationResponse reverted: ${err.shortMessage || err.message}`);
}
await tx.wait();
return {
passed,
+ score,
proofHash,
proofURI,
txHash: tx.hash,
+ requestHash,
+ requestTxHash,
sha256,
validatedAt,
kind: KIND_GLB_SCHEMA,
diff --git a/api/erc8004/[action].js b/api/erc8004/[action].js
index 6e8311f60..cfb8163e1 100644
--- a/api/erc8004/[action].js
+++ b/api/erc8004/[action].js
@@ -20,6 +20,7 @@ import {
resolveOnChainAgent,
resolveLatestValidation,
invalidateValidationCache,
+ resolveURI,
SERVER_CHAIN_META,
} from '../_lib/onchain.js';
import { r2, publicUrl } from '../_lib/r2.js';
@@ -236,21 +237,31 @@ const validateBodySchema = z.object({
agentId: agentIdSchema,
// Optional — when omitted we resolve the GLB from the index / on-chain manifest.
glbUrl: z.string().url().max(2048).optional(),
+ // Set on the retry after the owner's wallet opened the validation request
+ // returned by a previous validation_request_required response.
+ requestHash: z
+ .string()
+ .regex(/^0x[0-9a-fA-F]{64}$/)
+ .optional(),
});
// AttestError.code → HTTP status. Config/precondition problems are 503 (the
-// platform must be wired), model/transport problems are 422/502.
+// platform must be wired), model/transport problems are 422/502, and a missing
+// validation request is 409: the owner has to act before we can answer.
const ATTEST_STATUS = {
validator_key_not_configured: 503,
validation_registry_not_deployed: 503,
- validator_not_allowlisted: 503,
no_rpc: 503,
unsupported_chain: 400,
invalid_glb_url: 422,
glb_fetch_failed: 502,
glb_too_large: 413,
registry_read_failed: 502,
- record_failed: 502,
+ validation_request_required: 409,
+ request_not_for_validator: 409,
+ request_agent_mismatch: 409,
+ request_failed: 502,
+ response_failed: 502,
};
async function handleValidate(req, res) {
@@ -300,6 +311,7 @@ async function handleValidate(req, res) {
agentId: body.agentId,
glbUrl,
validatedAt,
+ requestHash: body.requestHash,
});
} catch (err) {
const code = err instanceof AttestError ? err.code : 'attest_failed';
@@ -310,7 +322,10 @@ async function handleValidate(req, res) {
SET validation_error = ${code}, validation_at = now()
WHERE chain_id = ${body.chainId} AND agent_id = ${body.agentId}
`.catch(() => {});
- return error(res, status, code, err.message);
+ // validation_request_required carries the exact owner-signed call that
+ // unblocks the attestation, so the client can prompt for it instead of
+ // showing a dead end.
+ return error(res, status, code, err.message, err.request ? { request: err.request } : {});
}
// Persist the latest attestation to the index cache (best-effort) and bust the
@@ -321,6 +336,7 @@ async function handleValidate(req, res) {
validation_kind = ${result.kind},
validation_proof_hash = ${result.proofHash},
validation_proof_uri = ${result.proofURI},
+ validation_request_hash = ${result.requestHash},
validation_tx = ${result.txHash},
validator_address = ${result.validator.toLowerCase()},
validation_at = ${validatedAt},
@@ -336,9 +352,13 @@ async function handleValidate(req, res) {
chainId: body.chainId,
agentId: body.agentId,
passed: result.passed,
+ score: result.score,
kind: result.kind,
proofHash: result.proofHash,
proofURI: result.proofURI,
+ requestHash: result.requestHash,
+ requestTxHash: result.requestTxHash,
+ requestTxExplorer: result.requestTxHash ? `${chainMeta.explorer}/tx/${result.requestTxHash}` : null,
txHash: result.txHash,
txExplorer: explorerTx,
validator: result.validator,
@@ -370,6 +390,25 @@ async function handleValidationRead(req, res) {
}
const validation = await resolveLatestValidation({ chainId, agentId });
+
+ // The registry emits the pinned report URL but never stores it, so the proof
+ // link comes from the index row and is only attached when its hash matches the
+ // on-chain responseHash. A stale row (an older GLB's report) is dropped rather
+ // than linked, so the badge never points at a report the chain didn't attest.
+ if (validation.exists && validation.proofHash) {
+ const [row] = await sql`
+ SELECT validation_proof_uri, validation_proof_hash, validation_tx
+ FROM erc8004_agents_index
+ WHERE chain_id = ${chainId} AND agent_id = ${agentId}
+ `.catch(() => []);
+ if (row?.validation_proof_uri && row.validation_proof_hash?.toLowerCase() === validation.proofHash.toLowerCase()) {
+ validation.proofURI = row.validation_proof_uri;
+ validation.proofUrlResolved = resolveURI(row.validation_proof_uri);
+ validation.txHash = row.validation_tx || null;
+ validation.txExplorer = row.validation_tx ? `${SERVER_CHAIN_META[chainId]?.explorer}/tx/${row.validation_tx}` : null;
+ }
+ }
+
res.setHeader('cache-control', 'public, max-age=30, s-maxage=60');
return json(res, 200, { validation });
}
diff --git a/src/erc8004/abi.js b/src/erc8004/abi.js
index eb10a0638..4d3f226bb 100644
--- a/src/erc8004/abi.js
+++ b/src/erc8004/abi.js
@@ -5,9 +5,11 @@
* shared across every EVM chain (deployed via CREATE2). Source:
* https://github.com/nirholas/erc8004-agents
*
- * ValidationRegistry mainnet deployment is pending. After running
- * contracts/script/deploy-validation-registry.sh, fill in the address
- * produced by computeAddress(DEPLOYER_ADDRESS) in MAINNET.validationRegistry.
+ * ValidationRegistry exists on the testnet class only; MAINNET.validationRegistry
+ * stays empty until a reference deployment lands on mainnet. Fill it in only after
+ * probing the address's bytecode for the selectors in VALIDATION_REGISTRY_ABI: a
+ * 0x8004-vanity address is not by itself proof that the contract behind it is the
+ * one this ABI describes.
*/
export const IDENTITY_REGISTRY_ABI = [
@@ -79,21 +81,23 @@ export const REPUTATION_REGISTRY_ABI = [
];
/**
- * Validation Registry ABI — mirrors contracts/src/ValidationRegistry.sol and the
- * canonical SDK ABI (sdk/src/erc8004/abi.js). The `getValidation*` read fragments
- * are required by getLatestValidation() in validation-recorder.js; without them
- * ethers cannot encode the call. Mainnet has no Validation Registry deployed yet.
+ * Validation Registry ABI — mirrors the deployed ERC-8004
+ * `ValidationRegistryUpgradeable` (and the canonical SDK ABI in
+ * sdk/src/erc8004/abi.js). Two-legged by design: the agent's owner (or an
+ * approved operator) opens a request naming a validator, and only that validator
+ * can answer it with a 0..100 score. `responseURI` is emitted, never stored, so
+ * the pinned report link has to come from the event or an index. Mainnet has no
+ * Validation Registry deployed yet.
*/
-const VALIDATION_RECORD_TUPLE =
- 'tuple(address validator, bool passed, bytes32 proofHash, string proofURI, uint64 timestamp, string kind)';
-
export const VALIDATION_REGISTRY_ABI = [
- 'function recordValidation(uint256 agentId, bool passed, bytes32 proofHash, string proofURI, string kind) external',
- 'function getValidationCount(uint256 agentId) external view returns (uint256)',
- `function getValidation(uint256 agentId, uint256 index) external view returns (${VALIDATION_RECORD_TUPLE})`,
- `function getLatestByKind(uint256 agentId, string kind) external view returns (${VALIDATION_RECORD_TUPLE})`,
- `function getValidationRange(uint256 agentId, uint256 offset, uint256 limit) external view returns (${VALIDATION_RECORD_TUPLE}[])`,
- 'event ValidationRecorded(uint256 indexed agentId, address indexed validator, bool passed, bytes32 proofHash, string kind)',
+ 'function validationRequest(address validatorAddress, uint256 agentId, string requestURI, bytes32 requestHash) external',
+ 'function validationResponse(bytes32 requestHash, uint8 response, string responseURI, bytes32 responseHash, string tag) external',
+ 'function getValidationStatus(bytes32 requestHash) external view returns (address validatorAddress, uint256 agentId, uint8 response, bytes32 responseHash, string tag, uint256 lastUpdate)',
+ 'function getAgentValidations(uint256 agentId) external view returns (bytes32[])',
+ 'function getValidatorRequests(address validatorAddress) external view returns (bytes32[])',
+ 'function getSummary(uint256 agentId, address[] validatorAddresses, string tag) external view returns (uint64 count, uint8 avgResponse)',
+ 'event ValidationRequest(address indexed validatorAddress, uint256 indexed agentId, string requestURI, bytes32 indexed requestHash)',
+ 'event ValidationResponse(address indexed validatorAddress, uint256 indexed agentId, bytes32 indexed requestHash, uint8 response, string responseURI, bytes32 responseHash, string tag)',
];
// ---------------------------------------------------------------------------
diff --git a/src/erc8004/validation-recorder.js b/src/erc8004/validation-recorder.js
index d47cfd78a..50ac18b54 100644
--- a/src/erc8004/validation-recorder.js
+++ b/src/erc8004/validation-recorder.js
@@ -10,7 +10,14 @@
import { Contract } from 'ethers';
import { REGISTRY_DEPLOYMENTS, VALIDATION_REGISTRY_ABI } from './abi.js';
import { pinFile } from './agent-registry.js';
-import { KIND_GLB_SCHEMA, reportPassed, hashReport } from './validation-report.js';
+import {
+ KIND_GLB_SCHEMA,
+ reportPassed,
+ hashReport,
+ responseForPassed,
+ responsePassed,
+ validationRequestHash,
+} from './validation-report.js';
// Re-export the pure report helpers so existing importers of this module keep
// working. The canonical implementations live in validation-report.js — a
@@ -22,15 +29,22 @@ export { reportPassed, hashReport, buildGlbReport, failureReason } from './valid
* Record a validation result on-chain. Optionally pin the full report to IPFS
* first so verifiers can fetch the details behind the hash.
*
+ * The registry is request/response based, so this drives both legs from the one
+ * connected wallet: it opens the request (which the registry only lets the agent's
+ * owner or an approved operator do) naming that same wallet as the validator, then
+ * answers it. When a request for this wallet already exists, only the answer is
+ * sent, which is also how a re-validation updates the record in place.
+ *
* @param {object} opts
* @param {number|bigint} opts.agentId
* @param {object} opts.report glTF-Validator report
- * @param {import('ethers').Signer} opts.signer Must be an allow-listed validator
+ * @param {import('ethers').Signer} opts.signer The agent's owner or an approved operator
* @param {number} [opts.chainId] Defaults to signer's network
* @param {string} [opts.apiToken] IPFS pinning token (optional)
* @param {boolean} [opts.pin=true] Pin report to IPFS before recording
* @param {string} [opts.kind='glb-schema']
- * @returns {Promise<{txHash: string, proofHash: string, proofURI: string, passed: boolean}>}
+ * @returns {Promise<{txHash: string, requestTxHash: string|null, requestHash: string,
+ * proofHash: string, proofURI: string, passed: boolean, score: number}>}
*/
export async function recordValidation({
agentId,
@@ -52,6 +66,7 @@ export async function recordValidation({
const proofHash = hashReport(report);
const passed = reportPassed(report);
+ const score = responseForPassed(passed);
let proofURI = '';
if (pin && apiToken) {
@@ -61,25 +76,77 @@ export async function recordValidation({
}
const contract = new Contract(deployment.validationRegistry, VALIDATION_REGISTRY_ABI, signer);
- const tx = await contract.recordValidation(agentId, passed, proofHash, proofURI, kind);
+ const validator = await signer.getAddress();
+ const requestHash = validationRequestHash({ chainId: resolvedChainId, agentId, seed: proofHash, kind });
+
+ const existing = await readValidationStatus(contract, requestHash);
+ if (existing && existing.validator.toLowerCase() !== validator.toLowerCase()) {
+ throw new Error(`This report is already registered to validator ${existing.validator}.`);
+ }
+
+ let requestTxHash = null;
+ if (!existing) {
+ const reqTx = await contract.validationRequest(validator, agentId, proofURI || `report:${proofHash}`, requestHash);
+ await reqTx.wait();
+ requestTxHash = reqTx.hash;
+ }
+
+ const tx = await contract.validationResponse(requestHash, score, proofURI, proofHash, kind);
await tx.wait();
- return { txHash: tx.hash, proofHash, proofURI, passed };
+ return { txHash: tx.hash, requestTxHash, requestHash, proofHash, proofURI, passed, score };
+}
+
+/** Read one request's status, or null when the registry has never seen that id. */
+async function readValidationStatus(contract, requestHash) {
+ try {
+ const s = await contract.getValidationStatus(requestHash);
+ return {
+ validator: s[0],
+ agentId: s[1],
+ response: Number(s[2]),
+ responseHash: s[3],
+ tag: s[4],
+ lastUpdate: Number(s[5]),
+ };
+ } catch {
+ return null;
+ }
}
/**
- * Read the most recent validation of a given kind.
+ * Read an agent's validations of a given kind, newest first. Unanswered requests
+ * carry an empty tag on chain and are skipped: they are pending, not verdicts.
+ *
* @param {object} opts
* @param {number|bigint} opts.agentId
* @param {import('ethers').Provider | import('ethers').Signer} opts.runner
* @param {number} opts.chainId
* @param {string} [opts.kind='glb-schema']
+ * @param {number} [opts.limit=20] How many of the most recent requests to inspect.
+ * @returns {Promise<Array<{requestHash: string, validator: string, response: number,
+ * responseHash: string, tag: string, lastUpdate: number, passed: boolean}>>}
*/
-export async function getLatestValidation({ agentId, runner, chainId, kind = KIND_GLB_SCHEMA }) {
+export async function getValidations({ agentId, runner, chainId, kind = KIND_GLB_SCHEMA, limit = 20 }) {
const deployment = REGISTRY_DEPLOYMENTS[chainId];
if (!deployment || !deployment.validationRegistry) {
throw new Error(`No Validation Registry deployed on chain ${chainId}.`);
}
const contract = new Contract(deployment.validationRegistry, VALIDATION_REGISTRY_ABI, runner);
- return contract.getLatestByKind(agentId, kind);
+ const hashes = await contract.getAgentValidations(agentId);
+ const recent = Array.from(hashes || []).slice(-limit).reverse();
+ const statuses = await Promise.all(recent.map((hash) => readValidationStatus(contract, hash).then((s) => (s ? { ...s, requestHash: hash } : null))));
+ return statuses
+ .filter((s) => s && s.tag === kind)
+ .map((s) => ({ ...s, passed: responsePassed(s.response) }))
+ .sort((a, b) => b.lastUpdate - a.lastUpdate);
+}
+
+/**
+ * The most recent answered validation of a kind, or null when there is none.
+ * @param {object} opts Same shape as getValidations().
+ */
+export async function getLatestValidation(opts) {
+ const all = await getValidations(opts);
+ return all[0] || null;
}
diff --git a/src/erc8004/validation-report.js b/src/erc8004/validation-report.js
index b085a7d61..344360456 100644
--- a/src/erc8004/validation-report.js
+++ b/src/erc8004/validation-report.js
@@ -15,10 +15,69 @@
* `proofURI`, re-stringifies, re-hashes, and compares.
*/
-import { keccak256, toUtf8Bytes } from 'ethers';
+import { AbiCoder, keccak256, toUtf8Bytes } from 'ethers';
export const KIND_GLB_SCHEMA = 'glb-schema';
+/**
+ * The deployed ERC-8004 ValidationRegistry stores a 0..100 `response` score, not
+ * a boolean. A glTF schema check is binary, so we write the two extremes and read
+ * back through a midpoint threshold. Three-way state, because the registry keeps
+ * an unanswered request on chain too:
+ *
+ * tag === '' → requested, no response yet (pending)
+ * response >= threshold → passed
+ * response < threshold → failed
+ */
+export const VALIDATION_RESPONSE_PASS = 100;
+export const VALIDATION_RESPONSE_FAIL = 0;
+export const VALIDATION_RESPONSE_PASS_THRESHOLD = 50;
+
+/**
+ * Canonical id for a validation request on the ERC-8004 ValidationRegistry.
+ *
+ * The registry keys every validation by an opaque bytes32 the requester chooses,
+ * so deriving it instead of randomizing it makes the flow idempotent: the same
+ * (chain, agent, kind, subject) always maps to the same request, so answering
+ * again updates that record in place rather than piling up duplicates, and a
+ * different subject always gets its own request.
+ *
+ * @param {object} p
+ * @param {number} p.chainId
+ * @param {string|number|bigint} p.agentId
+ * @param {string} p.seed 0x-prefixed 32-byte hex identifying what is validated
+ * (the GLB's sha256 for a model check, the report hash
+ * when the report itself is the subject).
+ * @param {string} [p.kind]
+ * @returns {string} 0x-prefixed 32-byte hex.
+ */
+export function validationRequestHash({ chainId, agentId, seed, kind = KIND_GLB_SCHEMA }) {
+ return keccak256(
+ AbiCoder.defaultAbiCoder().encode(
+ ['uint256', 'uint256', 'string', 'bytes32'],
+ [BigInt(chainId), BigInt(agentId), kind, seed],
+ ),
+ );
+}
+
+/**
+ * Map an on-chain `response` score to our boolean pass/fail.
+ * @param {number|bigint} response
+ * @returns {boolean}
+ */
+export function responsePassed(response) {
+ return Number(response) >= VALIDATION_RESPONSE_PASS_THRESHOLD;
+}
+
+/**
+ * Score to write for a report's outcome.
+ * @param {boolean} passed
+ * @returns {number}
+ */
+export function responseForPassed(passed) {
+ return passed ? VALIDATION_RESPONSE_PASS : VALIDATION_RESPONSE_FAIL;
+}
+
// glTF-Validator severity convention, reused so the report reads the same to any
// tool that already understands Khronos reports: 0=Error 1=Warning 2=Info 3=Hint.
export const SEVERITY = { ERROR: 0, WARNING: 1, INFO: 2, HINT: 3 };