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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(erc8004): read reputation in the dialect the canonical registries actually speak
nirholasbcca26d23f91
diff --git a/api/_lib/a2a/reputation-gate.js b/api/_lib/a2a/reputation-gate.jsindex 2f2017687..fb229acc7 100644--- a/api/_lib/a2a/reputation-gate.js+++ b/api/_lib/a2a/reputation-gate.js@@ -15,11 +15,11 @@// (`read` option) so tests run without RPC. The gate is a no-op when no// threshold is set; when a threshold IS set and the read fails, it fails closed.-import { Contract } from 'ethers';import { env } from '../env.js';import { evmFallbackProvider } from '../evm/rpc.js';-import { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI } from '../../../src/erc8004/abi.js';+import { REGISTRY_DEPLOYMENTS } from '../../../src/erc8004/abi.js';+import { readAgentReputation } from '../../../src/erc8004/reputation-read.js';export class ReputationError extends Error {constructor(code, message, status = 403) {@@ -31,11 +31,12 @@ export class ReputationError extends Error {}/**- * Read aggregated ERC-8004 reputation for an agent. getReputation returns- * (int256 avgX100, uint256 count): the average ALREADY multiplied by 100, signed- * so reputation can be negative. average = avgX100 / 100 — never divided by count- * again (the prior bug here divided the already-averaged value, understating- * every score by a factor of count and mis-decoding negatives as huge positives).+ * Read aggregated ERC-8004 reputation for an agent through the shared dialect-aware+ * reader (src/erc8004/reputation-read.js). The canonical registries run the ERC-8004+ * reference implementation, which has no getReputation(): reputation there is+ * getSummary over the reviewers returned by getClients. `average` is in the unit+ * reviewers submitted (0 to 100 by ERC-8004 convention on the canonical registries,+ * and signed, so it can be negative), so set `minAverage` in that same unit.** @param {object} opts* @param {number|bigint|string} opts.agentId@@ -55,10 +56,12 @@ export async function readReputationOnchain({ agentId, chainId, rpcUrl }) {const provider = await evmFallbackProvider(chainId, {primaryUrl: rpcUrl || env.A2A_REPUTATION_RPC_URL || null,});- const contract = new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, provider);- const [avgX100, count] = await contract.getReputation(agentId);- const n = Number(count);- return { average: n === 0 ? 0 : Number(avgX100) / 100, count: n };+ const { average, count } = await readAgentReputation({+ address: deployment.reputationRegistry,+ runner: provider,+ agentId,+ });+ return { average, count };}/**diff --git a/api/_lib/trust/subject-reputation.js b/api/_lib/trust/subject-reputation.jsindex 8be5fdb73..4bbb2d560 100644--- a/api/_lib/trust/subject-reputation.js+++ b/api/_lib/trust/subject-reputation.js@@ -361,7 +361,8 @@ async function scoreThreewsAgent(det, ts) {// ── ERC-8004 agent ───────────────────────────────────────────────────────────async function readErc8004(chainId, agentId) {- const { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI, IDENTITY_REGISTRY_ABI } = await import('../../../src/erc8004/abi.js');+ const { REGISTRY_DEPLOYMENTS, IDENTITY_REGISTRY_ABI } = await import('../../../src/erc8004/abi.js');+ const { readAgentReputation } = await import('../../../src/erc8004/reputation-read.js');const deployment = REGISTRY_DEPLOYMENTS[chainId];if (!deployment) throw Object.assign(new Error(`ERC-8004 not deployed on chain ${chainId}`), { code: 'no_deployment' });const { Contract } = await import('ethers');@@ -370,11 +371,10 @@ async function readErc8004(chainId, agentId) {const out = { average: null, count: 0, wallet: null };if (deployment.reputationRegistry) {- const rep = new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, provider);- const [avgX100, count] = await rep.getReputation(BigInt(agentId));- const n = Number(count);- out.count = n;- out.average = n === 0 ? null : Number(avgX100) / 100;+ const rep = await readAgentReputation({ address: deployment.reputationRegistry, runner: provider, agentId });+ out.count = rep.count;+ out.average = rep.count === 0 ? null : rep.average;+ out.dialect = rep.dialect;}if (deployment.identityRegistry) {try {diff --git a/api/_lib/trust/wallet-reputation.js b/api/_lib/trust/wallet-reputation.jsindex 017e55edc..333aa79d5 100644--- a/api/_lib/trust/wallet-reputation.js+++ b/api/_lib/trust/wallet-reputation.js@@ -340,8 +340,8 @@ export async function scoreAgentsLite(agentIds = [], { concurrency = 8 } = {}) {async function readErc8004Registry(agent) {if (!agent.erc8004_agent_id || !agent.chain_id) return { average: 0, count: 0 };- const { Contract } = await import('ethers');- const { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI } = await import('../../../src/erc8004/abi.js');+ const { REGISTRY_DEPLOYMENTS } = await import('../../../src/erc8004/abi.js');+ const { readAgentReputation } = await import('../../../src/erc8004/reputation-read.js');const deployment = REGISTRY_DEPLOYMENTS[agent.chain_id];if (!deployment?.reputationRegistry) return { average: 0, count: 0 };// Shared EVM failover provider (override → Alchemy → curated public lanes) instead@@ -349,10 +349,12 @@ async function readErc8004Registry(agent) {// bot-wall that 403s server-side reads, so the registry read always failed.const { evmFallbackProvider } = await import('../evm/rpc.js');const provider = await evmFallbackProvider(agent.chain_id);- const contract = new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, provider);- const [avgX100, count] = await contract.getReputation(BigInt(agent.erc8004_agent_id));- const n = Number(count);- return { average: n === 0 ? 0 : Number(avgX100) / 100, count: n };+ const rep = await readAgentReputation({+ address: deployment.reputationRegistry,+ runner: provider,+ agentId: agent.erc8004_agent_id,+ });+ return { average: rep.average, count: rep.count, dialect: rep.dialect };}function buildEvidence(agent, { solRep, registry, holdsThree }) {diff --git a/src/erc8004/abi.js b/src/erc8004/abi.jsindex 422765dff..0ecf9fce5 100644--- a/src/erc8004/abi.js+++ b/src/erc8004/abi.js@@ -64,19 +64,16 @@ export const IDENTITY_REGISTRY_ABI = ['event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)',];-// Mirrors contracts/src/ReputationRegistry.sol exactly. That source is deployed-// NOWHERE: an eth_call sweep on 2026-08-15 showed the canonical-// REGISTRY_DEPLOYMENTS[*].reputationRegistry addresses (Base 8453, Base Sepolia-// 84532) running the ERC-8004 reference implementation, whose interface is-// readFeedback/getClients and which reverts on every selector below. Use this ABI-// against your own deploy of contracts/src, not against the canonical addresses.-// Shape notes:-// submitFeedback(uint256, int8 score, string uri) — score is signed, [-100,100]-// getReputation(uint256) → (int256 avgX100, uint256 count) — pre-averaged ×100; divide for display-// FeedbackSubmitted(agentId, from, int8 score, string uri) — `from`, not `submitter`-// The earlier `submitReputation` / `(uint256 totalScore, uint256 count)` shape-// did NOT match the contract: ethers mis-decoded a signed average as a raw total-// and the write selector reverted. Kept byte-identical with sdk/src/erc8004/abi.js.+// LEGACY dialect. Mirrors contracts/src/ReputationRegistry.sol exactly. That source+// is deployed NOWHERE by us: the canonical REGISTRY_DEPLOYMENTS[*].reputationRegistry+// addresses run the ERC-8004 reference implementation (REPUTATION_REFERENCE_ABI+// below), which reverts on every selector here. This ABI only answers on an instance+// someone deployed from contracts/src themselves. Never read reputation with it+// directly: go through src/erc8004/reputation-read.js, which speaks both dialects.+// Shape notes: submitFeedback takes a signed int8 score in [-100, 100]; getReputation+// returns the average already multiplied by 100 alongside the count, so divide once+// for display and never by count; the FeedbackSubmitted event names the reviewer+// `from`, not `submitter`.export const REPUTATION_REGISTRY_ABI = ['function submitFeedback(uint256 agentId, int8 score, string uri) external','function getReputation(uint256 agentId) external view returns (int256 avgX100, uint256 count)',@@ -93,6 +90,25 @@ export const REPUTATION_REGISTRY_ABI = ['event StakeWithdrawn(uint256 indexed agentId, address indexed staker, uint256 value)',];+// REFERENCE dialect: the ERC-8004 `ReputationRegistryUpgradeable` that actually runs at+// the canonical addresses. Verified 2026-09-20 against the Basescan-verified+// implementation behind 0x8004BAa1... on Base and by eth_call. Two things differ from+// the legacy shape and both matter:+// - getSummary REVERTS with "clientAddresses required" on an empty list. The caller+// must say whose feedback it counts; pass getClients(agentId) to count everyone.+// - giveFeedback reverts with "Self-feedback not allowed" for the agent's owner and+// operators, and there is no staking at all.+export const REPUTATION_REFERENCE_ABI = [+ 'function giveFeedback(uint256 agentId, int128 value, uint8 valueDecimals, string tag1, string tag2, string endpoint, string feedbackURI, bytes32 feedbackHash) external',+ 'function revokeFeedback(uint256 agentId, uint64 feedbackIndex) external',+ 'function getSummary(uint256 agentId, address[] clientAddresses, string tag1, string tag2) external view returns (uint64 count, int128 summaryValue, uint8 summaryValueDecimals)',+ 'function getClients(uint256 agentId) external view returns (address[])',+ 'function getLastIndex(uint256 agentId, address clientAddress) external view returns (uint64)',+ 'function readFeedback(uint256 agentId, address clientAddress, uint64 feedbackIndex) external view returns (int128 value, uint8 valueDecimals, string tag1, string tag2, bool isRevoked)',+ 'function getIdentityRegistry() external view returns (address)',+ 'event NewFeedback(uint256 indexed agentId, address indexed clientAddress, uint64 feedbackIndex, int128 value, uint8 valueDecimals, string indexed indexedTag1, string tag1, string tag2, string endpoint, string feedbackURI, bytes32 feedbackHash)',+];+/*** Validation Registry ABI: mirrors the deployed ERC-8004* `ValidationRegistryUpgradeable` (and the canonical SDK ABI indiff --git a/src/erc8004/reputation-panel.js b/src/erc8004/reputation-panel.jsindex 17a975b06..20a7196ce 100644--- a/src/erc8004/reputation-panel.js+++ b/src/erc8004/reputation-panel.js@@ -18,7 +18,14 @@import { BrowserProvider } from 'ethers';import { CHAIN_META, switchChain, txExplorerUrl, readProvider } from './chain-meta.js';import { REGISTRY_DEPLOYMENTS } from './abi.js';-import { submitReputation, stakeReputation, getTotalStake, getReputation, getRecentReviews } from './reputation.js';+import {+ submitReputation,+ stakeReputation,+ getTotalStake,+ getReputation,+ getRecentReviews,+ supportsStaking,+} from './reputation.js';import { log } from '../shared/log.js';import { getEthPriceUsd } from '../shared/usd-price.js';@@ -58,6 +65,7 @@ export class ReputationPanel {this._root = null;this._stats = null;this._totalStakeWei = 0n;+ this._canStake = false;this._reviews = [];}@@ -89,7 +97,7 @@ export class ReputationPanel {const provider = readProvider(this._agent.chainId);try {- [this._stats, this._totalStakeWei] = await Promise.all([+ [this._stats, this._totalStakeWei, this._canStake] = await Promise.all([getReputation({agentId: this._agent.erc8004AgentId,runner: provider,@@ -100,6 +108,7 @@ export class ReputationPanel {runner: provider,chainId: this._agent.chainId,}).catch(() => 0n),+ supportsStaking({ chainId: this._agent.chainId, runner: provider }).catch(() => false),]);} catch (err) {log.warn('[reputation-panel] getReputation failed:', err?.message);@@ -162,10 +171,14 @@ export class ReputationPanel {<span class="agent-reputation__row-score">${_score(r.score)}</span><span class="agent-reputation__row-from" title="${_esc(r.from)}">${_shortAddr(r.from)}</span>${r.comment ? `<span class="agent-reputation__row-comment">${_esc(r.comment)}</span>` : ''}- <a class="agent-reputation__row-tx"+ ${+ r.txHash+ ? `<a class="agent-reputation__row-tx"href="${_esc(txExplorerUrl(this._agent.chainId, r.txHash))}"target="_blank" rel="noopener noreferrer"- aria-label="Open transaction in block explorer">↗</a>+ aria-label="Open transaction in block explorer">↗</a>`+ : ''+ }</li>`,).join('')}</ul>`@@ -244,7 +257,7 @@ export class ReputationPanel {<span>Comment (optional, public, on-chain)</span><input type="text" maxlength="280" placeholder="e.g. Great agent for X" /></label>- <label class="agent-vouch-modal__stake-toggle" style="display:flex;align-items:center;gap:8px;margin-top:12px;cursor:pointer">+ ${this._canStake ? `<label class="agent-vouch-modal__stake-toggle" style="display:flex;align-items:center;gap:8px;margin-top:12px;cursor:pointer"><input type="checkbox" class="agent-vouch-modal__stake-check" />Stake ETH (optional, makes reputation economically meaningful)</label>@@ -256,7 +269,7 @@ export class ReputationPanel {style="display:block;width:120px;margin-top:4px" /></label><div class="agent-vouch-modal__stake-usd" style="font-size:12px;color:#888;margin-top:4px"></div>- </div>+ </div>` : ''}<div class="agent-vouch-modal__actions"><button type="button" class="agent-vouch-modal__cancel">Cancel</button><button type="button" class="agent-vouch-modal__submit">Sign & submit</button>@@ -280,21 +293,22 @@ export class ReputationPanel {const stakeAmountEl = dialog.querySelector('.agent-vouch-modal__stake-amount');const stakeUsdEl = dialog.querySelector('.agent-vouch-modal__stake-usd');- stakeCheck.addEventListener('change', () => {- stakeInputs.style.display = stakeCheck.checked ? 'block' : 'none';- });-- const updateUsdEstimate = async () => {- const eth = parseFloat(stakeAmountEl.value) || 0;- const price = await fetchEthPriceUsd();- stakeUsdEl.textContent = price ? `≈ $${(eth * price).toFixed(2)} USD` : '';- };- stakeAmountEl.addEventListener('input', updateUsdEstimate);+ // The stake controls are only rendered where the registry supports staking.+ if (stakeCheck) {+ stakeCheck.addEventListener('change', () => {+ stakeInputs.style.display = stakeCheck.checked ? 'block' : 'none';+ });+ stakeAmountEl.addEventListener('input', async () => {+ const eth = parseFloat(stakeAmountEl.value) || 0;+ const price = await fetchEthPriceUsd();+ stakeUsdEl.textContent = price ? `≈ $${(eth * price).toFixed(2)} USD` : '';+ });+ }submitBtn.addEventListener('click', async () => {const score = Number(dialog.querySelector('input[name="score"]:checked')?.value || 0);const comment = dialog.querySelector('.agent-vouch-modal__comment input').value.trim();- const useStake = stakeCheck.checked;+ const useStake = Boolean(stakeCheck?.checked);const stakeEth = useStake ? parseFloat(stakeAmountEl.value) || 0 : 0;if (useStake && stakeEth < MIN_STAKE_ETH) {diff --git a/src/erc8004/reputation-read.js b/src/erc8004/reputation-read.jsnew file mode 100644index 000000000..ef3fd13aa--- /dev/null+++ b/src/erc8004/reputation-read.js@@ -0,0 +1,93 @@+/**+ * Dialect-aware ERC-8004 reputation reads. Pure ethers, no DOM, so the browser+ * helpers (reputation.js, the passport widget) and the server trust readers under+ * api/_lib all share this one implementation.+ *+ * Two registry dialects exist in the wild:+ *+ * reference The ERC-8004 reference implementation that runs at the canonical+ * 0x8004... addresses. Reputation is a per-reviewer ledger:+ * getSummary(agentId, clientAddresses, tag1, tag2) averages the feedback+ * of the reviewers you name and REVERTS on an empty list.+ * legacy contracts/src/ReputationRegistry.sol, for instances someone deployed+ * themselves: getReputation(agentId) returns (avgX100, count).+ *+ * The reference registry is an upgradeable proxy, so its interface is a moving part.+ * Detection is by behaviour (does getClients answer?) and never by address.+ */++import { Contract } from 'ethers';+import { REPUTATION_REGISTRY_ABI, REPUTATION_REFERENCE_ABI } from './abi.js';++// getSummary walks every feedback entry of every named reviewer inside one eth_call.+// Chunking keeps an agent with thousands of reviewers under node gas caps.+const REVIEWER_CHUNK = 100;+const WAD_DECIMALS = 18n;++/** @returns {Promise<'reference'|'legacy'>} */+export async function detectReputationDialect(address, runner) {+ const reference = new Contract(address, REPUTATION_REFERENCE_ABI, runner);+ try {+ await reference.getIdentityRegistry();+ return 'reference';+ } catch {+ return 'legacy';+ }+}++async function readReference(address, runner, agentId, { tag1 = '', tag2 = '', reviewers } = {}) {+ const registry = new Contract(address, REPUTATION_REFERENCE_ABI, runner);+ // ethers returns a frozen Result; copy it so it can be sliced and re-encoded.+ const clients = reviewers?.length ? reviewers : Array.from(await registry.getClients(agentId));+ if (clients.length === 0) return { average: 0, count: 0, reviewers: 0, dialect: 'reference' };++ // Count-weighted mean across chunks, carried at 18 decimals so chunks that report+ // different `summaryValueDecimals` still combine exactly.+ let weightedSum = 0n;+ let total = 0n;+ for (let i = 0; i < clients.length; i += REVIEWER_CHUNK) {+ const [count, value, decimals] = await registry.getSummary(+ agentId,+ clients.slice(i, i + REVIEWER_CHUNK),+ tag1,+ tag2,+ );+ if (count === 0n) continue;+ weightedSum += value * 10n ** (WAD_DECIMALS - BigInt(decimals)) * count;+ total += count;+ }+ const average = total === 0n ? 0 : Number(weightedSum / total) / 1e18;+ return { average, count: Number(total), reviewers: clients.length, dialect: 'reference' };+}++async function readLegacy(address, runner, agentId) {+ const registry = new Contract(address, REPUTATION_REGISTRY_ABI, runner);+ const [avgX100, count] = await registry.getReputation(agentId);+ const n = Number(count);+ return { average: n === 0 ? 0 : Number(avgX100) / 100, count: n, reviewers: n, dialect: 'legacy' };+}++/**+ * Read an agent's aggregate reputation from whichever dialect lives at `address`.+ *+ * `average` is in the unit reviewers submitted: three.ws star reviews are 1 to 5, and+ * other ERC-8004 clients commonly submit 0 to 100. The registry does not normalise+ * scales and neither does this function, so compare against a threshold in the same unit.+ *+ * @param {object} opts+ * @param {string} opts.address Reputation registry address.+ * @param {import('ethers').ContractRunner} opts.runner Provider or signer.+ * @param {number|bigint|string} opts.agentId+ * @param {string[]} [opts.reviewers] Count only these reviewers (reference dialect).+ * Default: everyone who has left feedback.+ * @param {string} [opts.tag1] ERC-8004 feedback tag filters (reference dialect).+ * @param {string} [opts.tag2]+ * @returns {Promise<{average:number, count:number, reviewers:number, dialect:'reference'|'legacy'}>}+ */+export async function readAgentReputation({ address, runner, agentId, reviewers, tag1, tag2 }) {+ const id = BigInt(agentId);+ const dialect = await detectReputationDialect(address, runner);+ return dialect === 'reference'+ ? readReference(address, runner, id, { reviewers, tag1, tag2 })+ : readLegacy(address, runner, id);+}diff --git a/src/erc8004/reputation.js b/src/erc8004/reputation.jsindex 99de8f442..70bd20d59 100644--- a/src/erc8004/reputation.js+++ b/src/erc8004/reputation.js@@ -1,72 +1,116 @@/**- * ReputationRegistry helpers — submit and query agent feedback.+ * ReputationRegistry helpers: submit and query agent feedback.*- * Matches the deployed ERC-8004 reputation contract- * (contracts/src/ReputationRegistry.sol) exactly:- * submitFeedback(uint256 agentId, int8 score, string uri)- * getReputation(uint256 agentId) → (int256 avgX100, uint256 count)- * getTotalStake(uint256 agentId) → uint256- * FeedbackSubmitted(agentId, from, int8 score, string uri)+ * Two registry dialects exist (see reputation-read.js). The canonical 0x8004...+ * addresses run the ERC-8004 reference implementation: feedback is+ * giveFeedback(agentId, value, decimals, tags..., uri, hash) on a 0 to 100 scale by+ * convention, read back with getSummary over a named reviewer set, and there is no+ * staking. A registry someone deployed from contracts/src speaks the legacy dialect:+ * submitFeedback / getReputation / stakeReputation.*- * `getReputation` returns the average already multiplied by 100 (so callers can- * divide client-side without precision loss). Never re-divide by `count` — that- * is what the contract already did. `score` is a signed int8 in [-100, 100]; the- * star UIs pass 1-5, which is a valid subset.+ * Everything exported here works on both. Ratings cross this boundary as 1 to 5+ * stars, which is what every three.ws surface shows: on the reference dialect a star+ * is 20 points, so 5 stars is written as 100 and an on-chain average of 82 reads 4.1.*/-import { Contract } from 'ethers';-import { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI } from './abi.js';+import { Contract, ZeroHash } from 'ethers';+import { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI, REPUTATION_REFERENCE_ABI } from './abi.js';+import { detectReputationDialect, readAgentReputation } from './reputation-read.js';-function getContract(chainId, runner) {+const POINTS_PER_STAR = 20;+// Recent reviews on the reference dialect are read reviewer by reviewer (no log+// scan, so it works on any RPC). Newest reviewers are last in getClients.+const RECENT_REVIEWERS = 20;++function registryAddress(chainId) {const deployment = REGISTRY_DEPLOYMENTS[chainId];if (!deployment || !deployment.reputationRegistry) {throw new Error(`No Reputation Registry deployed on chain ${chainId}.`);}- return new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, runner);+ return deployment.reputationRegistry;+}++const dialectCache = new Map();+function dialectOf(chainId, runner) {+ if (!dialectCache.has(chainId)) {+ const pending = detectReputationDialect(registryAddress(chainId), runner);+ dialectCache.set(chainId, pending);+ pending.catch(() => dialectCache.delete(chainId));+ }+ return dialectCache.get(chainId);+}++function toStars(points) {+ return Math.max(0, Math.min(5, points / POINTS_PER_STAR));+}++/** True when this chain's registry supports ETH-staked vouches (legacy dialect only). */+export async function supportsStaking({ chainId, runner }) {+ return (await dialectOf(chainId, runner)) === 'legacy';}/*** Submit reputation feedback about an agent.* @param {object} opts* @param {number|bigint} opts.agentId- * @param {number} opts.score Signed int8 in [-100, 100] (star UIs pass 1-5)+ * @param {number} opts.score 1 to 5 stars. (The legacy dialect also accepts any int8 in [-100, 100].)* @param {string} [opts.comment=''] Optional public on-chain comment / ipfs:// URI* @param {import('ethers').Signer} opts.signer* @param {number} [opts.chainId]* @returns {Promise<string>} tx hash*/export async function submitFeedback({ agentId, score, comment = '', signer, chainId }) {- if (!Number.isInteger(score) || score < -100 || score > 100) {- throw new Error('score must be an int8 in [-100, 100]');- }const resolvedChainId = chainId ?? Number((await signer.provider.getNetwork()).chainId);- const contract = getContract(resolvedChainId, signer);- const tx = await contract.submitFeedback(agentId, score, comment);+ const address = registryAddress(resolvedChainId);++ let tx;+ if ((await dialectOf(resolvedChainId, signer)) === 'reference') {+ if (!Number.isInteger(score) || score < 1 || score > 5) {+ throw new Error('score must be 1 to 5 stars');+ }+ const registry = new Contract(address, REPUTATION_REFERENCE_ABI, signer);+ try {+ tx = await registry.giveFeedback(agentId, score * POINTS_PER_STAR, 0, '', '', '', comment, ZeroHash);+ } catch (err) {+ if (/Self-feedback not allowed/i.test(err?.reason || err?.message || '')) {+ throw new Error("You can't review an agent you own or operate.");+ }+ throw err;+ }+ } else {+ if (!Number.isInteger(score) || score < -100 || score > 100) {+ throw new Error('score must be an int8 in [-100, 100]');+ }+ const registry = new Contract(address, REPUTATION_REGISTRY_ABI, signer);+ tx = await registry.submitFeedback(agentId, score, comment);+ }await tx.wait();return tx.hash;}-// Back-compat alias — the prior client API called this submitReputation.+// Back-compat alias: the prior client API called this submitReputation.export const submitReputation = submitFeedback;/*** Read aggregated reputation.- * @returns {Promise<{average: number, count: number}>}- * `average` is the on-chain avgX100 divided by 100 (so 4.2 reads as 4.2),- * 0 when no reviews have been submitted.+ * @returns {Promise<{average:number, count:number, reviewers:number, rawAverage:number, dialect:string}>}+ * `average` is in stars (0 to 5, 0 when nobody has reviewed). `rawAverage` is+ * the on-chain figure in the registry's own unit.*/export async function getReputation({ agentId, runner, chainId }) {- const contract = getContract(chainId, runner);- const [avgX100, count] = await contract.getReputation(agentId);- const n = Number(count);+ const rep = await readAgentReputation({ address: registryAddress(chainId), runner, agentId });return {- count: n,- average: n === 0 ? 0 : Number(avgX100) / 100,+ count: rep.count,+ reviewers: rep.reviewers,+ average: rep.dialect === 'reference' ? toStars(rep.average) : rep.average,+ rawAverage: rep.average,+ dialect: rep.dialect,};}/**- * Submit a reputation score backed by ETH stake.+ * Submit a reputation score backed by ETH stake. Legacy dialect only: the canonical+ * ERC-8004 registry has no staking, so check `supportsStaking` before offering it.* @param {object} opts* @param {number|bigint} opts.agentId* @param {number} opts.score 1-5@@ -81,27 +125,60 @@ export async function stakeReputation({ agentId, score, comment = '', stakeWei,throw new Error('score must be 1-5');}const resolvedChainId = chainId ?? Number((await signer.provider.getNetwork()).chainId);- const contract = getContract(resolvedChainId, signer);+ if (!(await supportsStaking({ chainId: resolvedChainId, runner: signer }))) {+ throw new Error('Staked vouches are not supported by the ERC-8004 registry on this chain.');+ }+ const contract = new Contract(registryAddress(resolvedChainId), REPUTATION_REGISTRY_ABI, signer);const tx = await contract.stakeReputation(agentId, score, comment, { value: stakeWei });await tx.wait();return tx.hash;}/**- * Read total ETH staked on an agent.+ * Read total ETH staked on an agent. Always 0 on the reference dialect.* @returns {Promise<bigint>} wei*/export async function getTotalStake({ agentId, runner, chainId }) {- const contract = getContract(chainId, runner);+ if (!(await supportsStaking({ chainId, runner }))) return 0n;+ const contract = new Contract(registryAddress(chainId), REPUTATION_REGISTRY_ABI, runner);return await contract.getTotalStake(agentId);}+async function recentReferenceReviews(address, runner, agentId) {+ const registry = new Contract(address, REPUTATION_REFERENCE_ABI, runner);+ const clients = Array.from(await registry.getClients(agentId)).slice(-RECENT_REVIEWERS);+ const reviews = await Promise.all(+ clients.map(async (from) => {+ const index = await registry.getLastIndex(agentId, from);+ if (index === 0n) return null;+ const [value, decimals, tag1, , isRevoked] = await registry.readFeedback(agentId, from, index);+ if (isRevoked) return null;+ return {+ agentId: Number(agentId),+ from,+ score: toStars(Number(value) / 10 ** Number(decimals)),+ comment: tag1,+ blockNumber: null,+ txHash: null,+ };+ }),+ );+ return reviews.filter(Boolean);+}+/**- * Enumerate past reviews by querying the FeedbackSubmitted event log.- * Optional — only useful if an indexer/provider supports filtered log queries.+ * Most recent reviews, oldest first (log order on both dialects). `score` is in stars. On the reference dialect+ * the list is read straight from registry state (each recent reviewer's latest+ * feedback), so there is no block number or tx hash and `comment` carries the+ * feedback's primary tag. On the legacy dialect it is a FeedbackSubmitted log scan,+ * which only works if the RPC allows filtered log queries over the range.*/export async function getRecentReviews({ agentId, runner, chainId, fromBlock = 0 }) {- const contract = getContract(chainId, runner);+ const address = registryAddress(chainId);+ if ((await dialectOf(chainId, runner)) === 'reference') {+ return recentReferenceReviews(address, runner, BigInt(agentId));+ }+ const contract = new Contract(address, REPUTATION_REGISTRY_ABI, runner);const filter = contract.filters.FeedbackSubmitted(agentId);const events = await contract.queryFilter(filter, fromBlock);return events.map((ev) => ({diff --git a/src/reputation-ui.js b/src/reputation-ui.jsindex 1294e6b66..20a08e1fd 100644--- a/src/reputation-ui.js+++ b/src/reputation-ui.js@@ -113,7 +113,12 @@ export class ReputationDashboard {]);this.reputation = reputation;- this.reviews = reviews.sort((a, b) => b.blockNumber - a.blockNumber);+ // Reviews arrive oldest-first. The reference registry has no block numbers to+ // sort by, so newest-first there is just the reverse.+ this.reviews =+ reviews[0]?.blockNumber == null+ ? reviews.slice().reverse()+ : reviews.sort((a, b) => b.blockNumber - a.blockNumber);this.totalStakeWei = totalStakeWei;// Fetch staker events for leaderboard (last 1000 blocks to avoid timeout).@@ -309,6 +314,7 @@ export class ReputationDashboard {_getLastReviewTime() {if (this.reviews.length === 0) return '—';const blockNum = this.reviews[0].blockNumber;+ if (blockNum == null) return 'Recently';if (blockNum < 0) return 'Just now';// Approximate: 12s per blockconst secondsAgo = Math.round(Date.now() / 1000) - Math.round(blockNum * 12);@@ -359,10 +365,10 @@ export class ReputationDashboard {div.className = `rep-review-item ${review.pending ? 'pending' : ''}`;const starHtml = this._renderStars(review.score);- const explorerUrl = getExplorerUrl(this.chainId, review.txHash);- const txLink = explorerUrl- ? `<a href="${explorerUrl}" target="_blank" rel="noopener">View tx</a>`- : `<span class="rep-tx-hash">${review.txHash.slice(0, 10)}…</span>`;+ const explorerUrl = review.txHash ? getExplorerUrl(this.chainId, review.txHash) : null;+ let txLink = '';+ if (explorerUrl) txLink = `<a href="${explorerUrl}" target="_blank" rel="noopener">View tx</a>`;+ else if (review.txHash) txLink = `<span class="rep-tx-hash">${review.txHash.slice(0, 10)}…</span>`;div.innerHTML = `<div class="rep-review-header">diff --git a/src/widgets/passport.js b/src/widgets/passport.jsindex 7898c6d5c..243d501a0 100644--- a/src/widgets/passport.js+++ b/src/widgets/passport.js@@ -6,19 +6,16 @@* IdentityRegistry.ownerOf(agentId) → wallet* IdentityRegistry.tokenURI(agentId) → registration JSON URL* IdentityRegistry.name()/symbol() → collection label- * ReputationRegistry.getReputation(id) → (total, count) → average- * ReputationRegistry event log → recent feedback (if enabled)+ * erc8004/reputation.js getReputation → star average + count, on either registry dialect+ * erc8004/reputation.js getRecentReviews → recent feedback (if enabled)* ValidationRegistry.getLatestValidation → optional proof row** No wallet connection, no writes, no feedback submission. That's a v2 task.*/import { Contract, JsonRpcProvider } from 'ethers';-import {- IDENTITY_REGISTRY_ABI,- REPUTATION_REGISTRY_ABI,- REGISTRY_DEPLOYMENTS,-} from '../erc8004/index.js';+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from '../erc8004/index.js';+import { getReputation, getRecentReviews } from '../erc8004/reputation.js';import {CHAIN_SLUGS,PUBLIC_RPCS,@@ -151,9 +148,7 @@ async function _refresh(state, panel) {try {const provider = new JsonRpcProvider(rpcURL, chainId, { staticNetwork: true });const identity = new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, provider);- const reputation = deployment.reputationRegistry- ? new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, provider)- : null;+ const hasReputation = Boolean(deployment.reputationRegistry);const agentId = BigInt(config.agentId);@@ -163,8 +158,8 @@ async function _refresh(state, panel) {identity.tokenURI(agentId),identity.name(),identity.symbol(),- reputation && config.showReputation- ? reputation.getReputation(agentId)+ hasReputation && config.showReputation+ ? getReputation({ agentId, runner: provider, chainId }): Promise.resolve(null),]);@@ -179,16 +174,12 @@ async function _refresh(state, panel) {const symbol = symbolRes.status === 'fulfilled' ? symbolRes.value : '';let reputationData = null;if (repRes.status === 'fulfilled' && repRes.value) {- // getReputation returns (avgX100, count) — already averaged ×100 on-chain.- // Divide for display; never re-divide by count.- const [avgX100, count] = repRes.value;- const n = Number(count);- reputationData = { count: n, average: n === 0 ? 0 : Number(avgX100) / 100 };+ reputationData = { count: repRes.value.count, average: repRes.value.average };}let feedback = [];- if (reputation && config.showRecentFeedback) {- feedback = await _fetchRecentFeedback(reputation, agentId, provider).catch(() => []);+ if (hasReputation && config.showRecentFeedback) {+ feedback = await _fetchRecentFeedback(agentId, provider, chainId).catch(() => []);}let manifest = null;@@ -220,20 +211,16 @@ async function _refresh(state, panel) {* Query the last N ReputationSubmitted events for this agent.* Scoped to the recent history to avoid full-log scans.*/-async function _fetchRecentFeedback(contract, agentId, provider) {- const latest = await provider.getBlockNumber();- const LOOKBACK = 200_000;- const fromBlock = Math.max(0, latest - LOOKBACK);- const filter = contract.filters.ReputationSubmitted(agentId);- const events = await contract.queryFilter(filter, fromBlock, latest);- return events+async function _fetchRecentFeedback(agentId, provider, chainId) {+ const reviews = await getRecentReviews({ agentId, runner: provider, chainId });+ return reviews.slice(-5).reverse()- .map((ev) => ({- from: ev.args.submitter,- score: Number(ev.args.score),- comment: _sanitizeText(ev.args.comment || ''),- txHash: ev.transactionHash,+ .map((r) => ({+ from: r.from,+ score: r.score,+ comment: _sanitizeText(r.comment || ''),+ txHash: r.txHash,}));}diff --git a/tests/erc8004-reputation-read.test.js b/tests/erc8004-reputation-read.test.jsnew file mode 100644index 000000000..9ba28b2a2--- /dev/null+++ b/tests/erc8004-reputation-read.test.js@@ -0,0 +1,112 @@+import { describe, it, expect } from 'vitest';+import { Interface } from 'ethers';+import { REPUTATION_REGISTRY_ABI, REPUTATION_REFERENCE_ABI } from '../src/erc8004/abi.js';+import { readAgentReputation, detectReputationDialect } from '../src/erc8004/reputation-read.js';++const ADDRESS = '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63';+const reference = new Interface(REPUTATION_REFERENCE_ABI);+const legacy = new Interface(REPUTATION_REGISTRY_ABI);++const reviewer = (i) => '0x' + (i + 1).toString(16).padStart(40, '0');++// An ethers ContractRunner that answers eth_call the way each registry dialect does:+// unknown selectors revert with no data, exactly like the live contracts.+function runnerFor(iface, handlers) {+ return {+ provider: null,+ async call(tx) {+ const fragment = iface.getFunction(tx.data.slice(0, 10));+ const handler = fragment && handlers[fragment.name];+ if (!handler) throw Object.assign(new Error('execution reverted'), { code: 'CALL_EXCEPTION' });+ const args = iface.decodeFunctionData(fragment, tx.data);+ return iface.encodeFunctionResult(fragment, handler(args));+ },+ };+}++describe('readAgentReputation', () => {+ it('reads the reference dialect through getClients + getSummary', async () => {+ const clients = [reviewer(0), reviewer(1)];+ const runner = runnerFor(reference, {+ getIdentityRegistry: () => ['0x8004A169FB4a3325136EB29fA0ceB6D2e539a432'],+ getClients: () => [clients],+ getSummary: ([, named]) => {+ expect(Array.from(named)).toEqual(clients);+ return [41n, 82n, 0];+ },+ });+ expect(await detectReputationDialect(ADDRESS, runner)).toBe('reference');+ expect(await readAgentReputation({ address: ADDRESS, runner, agentId: 1 })).toEqual({+ average: 82,+ count: 41,+ reviewers: 2,+ dialect: 'reference',+ });+ });++ it('never calls getSummary with an empty reviewer list, which the live registry rejects', async () => {+ const runner = runnerFor(reference, {+ getIdentityRegistry: () => ['0x8004A169FB4a3325136EB29fA0ceB6D2e539a432'],+ getClients: () => [[]],+ getSummary: () => {+ throw new Error('clientAddresses required');+ },+ });+ expect(await readAgentReputation({ address: ADDRESS, runner, agentId: 7 })).toEqual({+ average: 0,+ count: 0,+ reviewers: 0,+ dialect: 'reference',+ });+ });++ it('chunks large reviewer sets and combines chunks as a count-weighted mean across decimals', async () => {+ const clients = Array.from({ length: 150 }, (_, i) => reviewer(i));+ const chunkSizes = [];+ const runner = runnerFor(reference, {+ getIdentityRegistry: () => ['0x8004A169FB4a3325136EB29fA0ceB6D2e539a432'],+ getClients: () => [clients],+ getSummary: ([, named]) => {+ chunkSizes.push(named.length);+ // First chunk: 30 entries averaging 90 (0 decimals).+ // Second chunk: 10 entries averaging 50.00 (2 decimals).+ return named.length === 100 ? [30n, 90n, 0] : [10n, 5000n, 2];+ },+ });+ const rep = await readAgentReputation({ address: ADDRESS, runner, agentId: 1 });+ expect(chunkSizes).toEqual([100, 50]);+ expect(rep.count).toBe(40);+ expect(rep.average).toBe(80); // (30*90 + 10*50) / 40+ });++ it('honours an explicit reviewer set and tag filters', async () => {+ const trusted = [reviewer(9)];+ const runner = runnerFor(reference, {+ getIdentityRegistry: () => ['0x8004A169FB4a3325136EB29fA0ceB6D2e539a432'],+ getSummary: ([, named, tag1, tag2]) => {+ expect(Array.from(named, (a) => a.toLowerCase())).toEqual(trusted);+ expect([tag1, tag2]).toEqual(['uptime', '']);+ return [3n, -25n, 0];+ },+ });+ const rep = await readAgentReputation({+ address: ADDRESS,+ runner,+ agentId: 1,+ reviewers: trusted,+ tag1: 'uptime',+ });+ expect(rep).toMatchObject({ average: -25, count: 3, reviewers: 1 });+ });++ it('falls back to the legacy dialect on a registry deployed from contracts/src', async () => {+ const runner = runnerFor(legacy, { getReputation: () => [425n, 8n] });+ expect(await detectReputationDialect(ADDRESS, runner)).toBe('legacy');+ expect(await readAgentReputation({ address: ADDRESS, runner, agentId: 1 })).toEqual({+ average: 4.25,+ count: 8,+ reviewers: 8,+ dialect: 'legacy',+ });+ });+});