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: implement reputation handling with ETH staking and update API routes

nirholasb8ed12b73e95
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 9b539349e..274a37376 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -123,6 +123,11 @@ export default wrap(async function handler(req, res) {
return mod.handlePayments(req, res, id);
}
+ if (sub === 'reputation') {
+ const mod = await import('./_id/reputation.js');
+ return mod.handleReputation(req, res, id);
+ }
+
if (sub === 'memory-seed') {
const mod = await import('./_id/memory-seed.js');
return mod.default(req, res, id);
diff --git a/api/agents/_id/reputation.js b/api/agents/_id/reputation.js
new file mode 100644
index 000000000..93b2d1f47
--- /dev/null
+++ b/api/agents/_id/reputation.js
@@ -0,0 +1,101 @@
+import { sql } from '../../_lib/db.js';
+import { cors, json, error, method, wrap } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { env } from '../../_lib/env.js';
+
+const CACHE_TTL_S = 300; // 5 minutes
+
+// Minimal public RPC map
+const RPC = {
+ 1: 'https://eth.llamarpc.com',
+ 10: 'https://optimism.llamarpc.com',
+ 8453: 'https://base.llamarpc.com',
+ 42161: 'https://arbitrum.llamarpc.com',
+ 137: 'https://polygon.llamarpc.com',
+ 11155111: 'https://ethereum-sepolia.publicnode.com',
+ 84532: 'https://base-sepolia.publicnode.com',
+};
+
+let _redis = null;
+async function getRedis() {
+ if (_redis) return _redis;
+ const url = env.UPSTASH_REDIS_REST_URL;
+ const token = env.UPSTASH_REDIS_REST_TOKEN;
+ if (!url || !token) return null;
+ const { Redis } = await import('@upstash/redis');
+ _redis = new Redis({ url, token });
+ return _redis;
+}
+
+export const handleReputation = wrap(async (req, res, agentId) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [agent] = await sql`
+ SELECT erc8004_agent_id, chain_id
+ FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const url = new URL(req.url, 'http://x');
+ const chainId = Number(url.searchParams.get('chain_id')) || agent.chain_id;
+
+ if (!chainId || !agent.erc8004_agent_id) {
+ return json(res, 200, { average: 0, count: 0, total_stake_wei: '0', chain_id: chainId });
+ }
+
+ const cacheKey = `rep:${agentId}:${chainId}`;
+ const redis = await getRedis();
+
+ if (redis) {
+ try {
+ const cached = await redis.get(cacheKey);
+ if (cached) {
+ res.setHeader('X-Cache', 'HIT');
+ return json(res, 200, cached);
+ }
+ } catch { /* cache miss */ }
+ }
+
+ const rpcUrl = RPC[chainId];
+ if (!rpcUrl) {
+ return json(res, 200, { average: 0, count: 0, total_stake_wei: '0', chain_id: chainId });
+ }
+
+ const { JsonRpcProvider, Contract } = await import('ethers');
+ const { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI } = await import('../../../src/erc8004/abi.js');
+
+ const deployment = REGISTRY_DEPLOYMENTS[chainId];
+ if (!deployment?.reputationRegistry) {
+ return json(res, 200, { average: 0, count: 0, total_stake_wei: '0', chain_id: chainId });
+ }
+
+ const provider = new JsonRpcProvider(rpcUrl, chainId, { staticNetwork: true });
+ const contract = new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, provider);
+
+ const erc8004Id = BigInt(agent.erc8004_agent_id);
+ const [[avgX100, count], totalStakeWei] = await Promise.all([
+ contract.getReputation(erc8004Id),
+ contract.getTotalStake(erc8004Id).catch(() => 0n),
+ ]);
+
+ const n = Number(count);
+ const result = {
+ average: n === 0 ? 0 : Number(avgX100) / 100,
+ count: n,
+ total_stake_wei: totalStakeWei.toString(),
+ chain_id: chainId,
+ };
+
+ if (redis) {
+ redis.set(cacheKey, result, { ex: CACHE_TTL_S }).catch(() => {});
+ }
+
+ res.setHeader('X-Cache', 'MISS');
+ return json(res, 200, result);
+});
diff --git a/src/erc8004/reputation-panel.js b/src/erc8004/reputation-panel.js
index 0f0574b5e..f8bf55cfa 100644
--- a/src/erc8004/reputation-panel.js
+++ b/src/erc8004/reputation-panel.js
@@ -18,12 +18,29 @@
import { JsonRpcProvider, BrowserProvider } from 'ethers';
import { CHAIN_META, switchChain, txExplorerUrl } from './chain-meta.js';
import { REGISTRY_DEPLOYMENTS } from './abi.js';
-import { submitReputation, getReputation, getRecentReviews } from './reputation.js';
+import { submitReputation, stakeReputation, getTotalStake, getReputation, getRecentReviews } from './reputation.js';
-// Look back ~50k blocks (~7 days on most L2s, ~7 days on Ethereum mainnet).
-// Some RPCs reject huge ranges; this is a conservative default that still
-// captures recent activity without a 429.
const REVIEWS_LOOKBACK_BLOCKS = 50_000;
+const MIN_STAKE_ETH = 0.001;
+
+let _ethPriceUsd = null;
+let _ethPriceFetchedAt = 0;
+
+async function fetchEthPriceUsd() {
+ const now = Date.now();
+ if (_ethPriceUsd && now - _ethPriceFetchedAt < 5 * 60 * 1000) return _ethPriceUsd;
+ try {
+ const res = await fetch(
+ 'https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd',
+ );
+ const data = await res.json();
+ _ethPriceUsd = data?.ethereum?.usd ?? null;
+ _ethPriceFetchedAt = now;
+ } catch {
+ /* best-effort */
+ }
+ return _ethPriceUsd;
+}
export class ReputationPanel {
/**
@@ -39,6 +56,7 @@ export class ReputationPanel {
this._viewer = viewer;
this._root = null;
this._stats = null;
+ this._totalStakeWei = 0n;
this._reviews = [];
}
@@ -72,11 +90,18 @@ export class ReputationPanel {
});
try {
- this._stats = await getReputation({
- agentId: this._agent.erc8004AgentId,
- runner: provider,
- chainId: this._agent.chainId,
- });
+ [this._stats, this._totalStakeWei] = await Promise.all([
+ getReputation({
+ agentId: this._agent.erc8004AgentId,
+ runner: provider,
+ chainId: this._agent.chainId,
+ }),
+ getTotalStake({
+ agentId: this._agent.erc8004AgentId,
+ runner: provider,
+ chainId: this._agent.chainId,
+ }).catch(() => 0n),
+ ]);
} catch (err) {
console.warn('[reputation-panel] getReputation failed:', err?.message);
this._renderEmpty('Could not read reputation from the chain.');
@@ -152,9 +177,16 @@ export class ReputationPanel {
</p>`
: '';
+ const stakeEth = Number(this._totalStakeWei) / 1e18;
+ const stakeHtml =
+ this._totalStakeWei > 0n
+ ? `<div class="agent-reputation__stake">Total staked: <strong>${stakeEth.toFixed(4)} ETH</strong></div>`
+ : '';
+
this._root.innerHTML = `
<h2 class="agent-reputation__heading" id="agent-reputation-heading">Reputation</h2>
<div class="agent-reputation__summary">${summary}</div>
+ ${stakeHtml}
<div class="agent-reputation__action">${vouchHtml}</div>
${reviewsHtml}
`;
@@ -213,6 +245,19 @@ 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">
+ <input type="checkbox" class="agent-vouch-modal__stake-check" />
+ Stake ETH (optional, makes reputation economically meaningful)
+ </label>
+ <div class="agent-vouch-modal__stake-inputs" style="display:none;margin-top:8px">
+ <label style="display:block;font-size:13px">
+ Amount ETH (min ${MIN_STAKE_ETH})
+ <input type="number" class="agent-vouch-modal__stake-amount"
+ value="0.01" min="${MIN_STAKE_ETH}" max="10" step="0.001"
+ 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 class="agent-vouch-modal__actions">
<button type="button" class="agent-vouch-modal__cancel">Cancel</button>
<button type="button" class="agent-vouch-modal__submit">Sign &amp; submit</button>
@@ -231,10 +276,32 @@ export class ReputationPanel {
const submitBtn = dialog.querySelector('.agent-vouch-modal__submit');
const statusEl = dialog.querySelector('.agent-vouch-modal__status');
+ const stakeCheck = dialog.querySelector('.agent-vouch-modal__stake-check');
+ const stakeInputs = dialog.querySelector('.agent-vouch-modal__stake-inputs');
+ 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);
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 stakeEth = useStake ? parseFloat(stakeAmountEl.value) || 0 : 0;
+
+ if (useStake && stakeEth < MIN_STAKE_ETH) {
+ statusEl.textContent = `Minimum stake is ${MIN_STAKE_ETH} ETH.`;
+ return;
+ }
submitBtn.disabled = true;
statusEl.textContent = 'Connecting wallet…';
@@ -254,13 +321,27 @@ export class ReputationPanel {
const signer = await provider.getSigner();
statusEl.textContent = 'Sign transaction in your wallet…';
- const txHash = await submitReputation({
- agentId: this._agent.erc8004AgentId,
- score,
- comment,
- signer,
- chainId: this._agent.chainId,
- });
+
+ let txHash;
+ if (useStake) {
+ const stakeWei = BigInt(Math.round(stakeEth * 1e18));
+ txHash = await stakeReputation({
+ agentId: this._agent.erc8004AgentId,
+ score,
+ comment,
+ stakeWei,
+ signer,
+ chainId: this._agent.chainId,
+ });
+ } else {
+ txHash = await submitReputation({
+ agentId: this._agent.erc8004AgentId,
+ score,
+ comment,
+ signer,
+ chainId: this._agent.chainId,
+ });
+ }
statusEl.innerHTML = `Submitted ✓ <a href="${_esc(
txExplorerUrl(this._agent.chainId, txHash),
diff --git a/src/erc8004/reputation.js b/src/erc8004/reputation.js
index 635752cbb..b70c9a831 100644
--- a/src/erc8004/reputation.js
+++ b/src/erc8004/reputation.js
@@ -58,6 +58,37 @@ export async function getReputation({ agentId, runner, chainId }) {
};
}
+/**
+ * Submit a reputation score backed by ETH stake.
+ * @param {object} opts
+ * @param {number|bigint} opts.agentId
+ * @param {number} opts.score 1-5
+ * @param {string} [opts.comment='']
+ * @param {bigint} opts.stakeWei Must be >= 0.001 ETH (1e15 wei)
+ * @param {import('ethers').Signer} opts.signer
+ * @param {number} [opts.chainId]
+ * @returns {Promise<string>} tx hash
+ */
+export async function stakeReputation({ agentId, score, comment = '', stakeWei, signer, chainId }) {
+ if (!Number.isInteger(score) || score < 1 || score > 5) {
+ throw new Error('score must be 1-5');
+ }
+ const resolvedChainId = chainId ?? Number((await signer.provider.getNetwork()).chainId);
+ const contract = getContract(resolvedChainId, signer);
+ const tx = await contract.stakeReputation(agentId, score, comment, { value: stakeWei });
+ await tx.wait();
+ return tx.hash;
+}
+
+/**
+ * Read total ETH staked on an agent.
+ * @returns {Promise<bigint>} wei
+ */
+export async function getTotalStake({ agentId, runner, chainId }) {
+ const contract = getContract(chainId, runner);
+ return await contract.getTotalStake(agentId);
+}
+
/**
* Enumerate past reviews by querying the ReputationSubmitted event log.
* Optional — only useful if an indexer/provider supports filtered log queries.
diff --git a/src/reputation-ui.js b/src/reputation-ui.js
index c1c82d975..99e1a6742 100644
--- a/src/reputation-ui.js
+++ b/src/reputation-ui.js
@@ -7,7 +7,7 @@
*/
import { JsonRpcProvider } from 'ethers';
-import { getReputation, getRecentReviews, submitReputation } from './erc8004/reputation.js';
+import { getReputation, getRecentReviews, submitReputation, getTotalStake } from './erc8004/reputation.js';
import { ensureWallet } from './erc8004/agent-registry.js';
import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';
@@ -73,6 +73,8 @@ export class ReputationDashboard {
this.chainId = chainId;
this.reviews = [];
this.reputation = { total: 0, count: 0, average: 0 };
+ this.totalStakeWei = 0n;
+ this.stakerEvents = [];
this.connectedAddress = null;
this.reviewListeners = [];
this.pollInterval = null;
@@ -104,21 +106,34 @@ export class ReputationDashboard {
const rpcUrl = this._getRpcUrl(this.chainId);
const provider = new JsonRpcProvider(rpcUrl);
- const reputation = await getReputation({
- agentId: this.agentId,
- runner: provider,
- chainId: this.chainId,
- });
-
- const reviews = await getRecentReviews({
- agentId: this.agentId,
- runner: provider,
- chainId: this.chainId,
- fromBlock: 0,
- });
+ const [reputation, reviews, totalStakeWei] = await Promise.all([
+ getReputation({ agentId: this.agentId, runner: provider, chainId: this.chainId }),
+ getRecentReviews({ agentId: this.agentId, runner: provider, chainId: this.chainId, fromBlock: 0 }),
+ getTotalStake({ agentId: this.agentId, runner: provider, chainId: this.chainId }).catch(() => 0n),
+ ]);
this.reputation = reputation;
this.reviews = reviews.sort((a, b) => b.blockNumber - a.blockNumber);
+ this.totalStakeWei = totalStakeWei;
+
+ // Fetch staker events for leaderboard (last 1000 blocks to avoid timeout).
+ if (totalStakeWei > 0n) {
+ try {
+ const { REGISTRY_DEPLOYMENTS: deps, REPUTATION_REGISTRY_ABI } = await import('./erc8004/abi.js');
+ const { Contract } = await import('ethers');
+ const contract = new Contract(deps[this.chainId].reputationRegistry, REPUTATION_REGISTRY_ABI, provider);
+ const head = await provider.getBlockNumber();
+ const fromBlock = Math.max(0, head - 1000);
+ const events = await contract.queryFilter(contract.filters.ReputationStaked(this.agentId), fromBlock, 'latest');
+ this.stakerEvents = events.map((ev) => ({
+ staker: ev.args.staker,
+ score: Number(ev.args.score),
+ value: ev.args.value,
+ }));
+ } catch {
+ this.stakerEvents = [];
+ }
+ }
}
_getRpcUrl(chainId) {
@@ -237,6 +252,7 @@ export class ReputationDashboard {
this.container.appendChild(this._createHeader());
this.container.appendChild(this._createStatsRow());
this.container.appendChild(this._createReviewList());
+ if (this.totalStakeWei > 0n) this.container.appendChild(this._createTopStakers());
this.container.appendChild(this._createSubmitForm());
}
@@ -274,6 +290,8 @@ export class ReputationDashboard {
const lastReviewTime = this._getLastReviewTime();
+ const stakeEth = (Number(this.totalStakeWei) / 1e18).toFixed(4);
+ const chainName = CHAIN_NAMES[this.chainId] || `Chain ${this.chainId}`;
div.innerHTML = `
<div class="rep-stat">
<span class="rep-stat-label">Reviews</span>
@@ -283,6 +301,11 @@ export class ReputationDashboard {
<span class="rep-stat-label">Rating</span>
<span class="rep-stat-value">${this.reputation.average.toFixed(1)}</span>
</div>
+ <div class="rep-stat">
+ <span class="rep-stat-label">Total Staked</span>
+ <span class="rep-stat-value">${stakeEth} ETH</span>
+ <span class="rep-stat-chain">${chainName}</span>
+ </div>
<div class="rep-stat">
<span class="rep-stat-label">Last Review</span>
<span class="rep-stat-value">${lastReviewTime}</span>
@@ -379,6 +402,43 @@ export class ReputationDashboard {
return `${addr.slice(0, 6)}…${addr.slice(-4)}`;
}
+ _createTopStakers() {
+ const div = document.createElement('div');
+ div.className = 'rep-top-stakers';
+
+ const title = document.createElement('h3');
+ title.textContent = 'Top Stakers';
+ div.appendChild(title);
+
+ if (!this.stakerEvents.length) {
+ const empty = document.createElement('p');
+ empty.className = 'rep-empty';
+ empty.textContent = 'No stakers found in recent blocks.';
+ div.appendChild(empty);
+ return div;
+ }
+
+ const sorted = [...this.stakerEvents]
+ .sort((a, b) => (b.value > a.value ? 1 : b.value < a.value ? -1 : 0))
+ .slice(0, 5);
+
+ const list = document.createElement('div');
+ list.className = 'rep-staker-list';
+ sorted.forEach((ev) => {
+ const row = document.createElement('div');
+ row.className = 'rep-staker-row';
+ const eth = (Number(ev.value) / 1e18).toFixed(4);
+ row.innerHTML = `
+ <span class="rep-staker-addr">${this._truncateAddress(ev.staker)}</span>
+ <span class="rep-staker-eth">${eth} ETH</span>
+ <span class="rep-staker-score">${this._renderStars(ev.score)}</span>
+ `;
+ list.appendChild(row);
+ });
+ div.appendChild(list);
+ return div;
+ }
+
_createSubmitForm() {
const div = document.createElement('div');
div.className = 'rep-submit-form';
diff --git a/vercel.json b/vercel.json
index 1159dc56b..1c78952d6 100644
--- a/vercel.json
+++ b/vercel.json
@@ -337,6 +337,10 @@
"src": "/api/agents/([^/]+)/payments",
"dest": "/api/agents/[id]"
},
+ {
+ "src": "/api/agents/([^/]+)/reputation",
+ "dest": "/api/agents/[id]"
+ },
{
"src": "/api/agents/([^/]+)/livekit-token",
"dest": "/api/agents/[id]"