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
feat: add Solana agent passport page and update routing for asset handling
nirholas33f725c162cf
diff --git a/api/_lib/migrations/2026-04-29-onchain-unified.sql b/api/_lib/migrations/2026-04-29-onchain-unified.sqlnew file mode 100644index 000000000..6479ad537--- /dev/null+++ b/api/_lib/migrations/2026-04-29-onchain-unified.sql@@ -0,0 +1,86 @@+-- Migration: unify on-chain deploy metadata across chain families.+--+-- Rationale: agent_identities.meta historically held EVM-specific fields+-- (chain_id, erc8004_agent_id) at the top level, while Solana deploys wrote+-- to meta.chain_type='solana' + meta.sol_mint_address. Frontend rehydration+-- forked on shape; new families would require more forks. This migration+-- introduces a single canonical block: meta.onchain (jsonb).+--+-- New writes: api/agents/onchain/confirm.js writes only meta.onchain.+-- Old writes: api/agents/{register-confirm,solana-register-confirm}.js+-- continue to write the legacy fields. The view below provides a unified read.+--+-- Apply manually via:+-- psql $DATABASE_URL -f api/_lib/migrations/2026-04-29-onchain-unified.sql+--+-- Idempotent: safe to re-run.++begin;++-- 1. Backfill legacy EVM rows into the unified shape. Only touches rows that+-- have legacy fields *and* don't already have meta.onchain set.+update agent_identities+set meta = jsonb_set(+ coalesce(meta, '{}'::jsonb),+ '{onchain}',+ jsonb_build_object(+ 'chain', 'eip155:' || (meta->>'chain_id'),+ 'family', 'evm',+ 'tx_hash', coalesce(meta->>'tx_hash', ''),+ 'onchain_id', meta->>'erc8004_agent_id',+ 'contract_or_mint', meta->>'erc8004_registry',+ 'wallet', wallet_address,+ 'metadata_uri', coalesce(meta->>'metadata_uri', ''),+ 'confirmed_at', coalesce(meta->>'confirmed_at', created_at::text)+ ),+ true+)+where deleted_at is null+ and meta ? 'chain_id'+ and not (meta ? 'onchain');++-- 2. Backfill legacy Solana rows.+update agent_identities+set meta = jsonb_set(+ coalesce(meta, '{}'::jsonb),+ '{onchain}',+ jsonb_build_object(+ 'chain', case+ when (meta->>'network') = 'devnet'+ then 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1'+ else 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp'+ end,+ 'family', 'solana',+ 'tx_hash', coalesce(meta->>'tx_signature', ''),+ 'onchain_id', null,+ 'contract_or_mint', meta->>'sol_mint_address',+ 'wallet', wallet_address,+ 'metadata_uri', coalesce(meta->>'metadata_uri', ''),+ 'confirmed_at', coalesce(meta->>'confirmed_at', created_at::text),+ 'cluster', coalesce(meta->>'network', 'mainnet')+ ),+ true+)+where deleted_at is null+ and (meta->>'chain_type') = 'solana'+ and not (meta ? 'onchain');++-- 3. Index the unified shape so queries by chain or tx are cheap.+create index if not exists agent_identities_onchain_chain+ on agent_identities ((meta->'onchain'->>'chain'))+ where deleted_at is null and (meta ? 'onchain');++create index if not exists agent_identities_onchain_tx+ on agent_identities ((meta->'onchain'->>'tx_hash'))+ where deleted_at is null and (meta ? 'onchain');++-- 4. Normalize onchain id type — used by backwards-compat queries that joined+-- on integer chain_id. The legacy column erc8004_agent_id is left intact+-- for now (zero-downtime); a follow-up migration can drop it once all+-- readers are on meta.onchain.+comment on column agent_identities.meta is+ 'jsonb. Canonical on-chain shape lives at meta.onchain '+ '({chain: caip2, family, tx_hash, onchain_id, contract_or_mint, wallet, metadata_uri, confirmed_at, ...}). '+ 'Legacy fields meta.chain_id, meta.erc8004_agent_id, meta.sol_mint_address are deprecated.';++commit;diff --git a/api/agents/onchain/confirm.js b/api/agents/onchain/confirm.jsnew file mode 100644index 000000000..d2c5eb382--- /dev/null+++ b/api/agents/onchain/confirm.js@@ -0,0 +1,254 @@+/**+ * POST /api/agents/onchain/confirm+ *+ * Unified confirm endpoint. Replaces:+ * • /api/agents/register-confirm (EVM)+ * • /api/agents/solana-register-confirm (Solana)+ *+ * Verifies the on-chain transaction and writes a *unified* `meta.onchain`+ * block to `agent_identities` so downstream queries don't need to fork on+ * chain family. Persists the wallet linkage as a side effect (it was already+ * pre-checked at prep, but we re-verify here using the tx as ownership proof).+ *+ * Unified onchain shape stored in agent_identities.meta:+ * {+ * onchain: {+ * chain: "eip155:8453" | "solana:5eyk...", // CAIP-2+ * family: "evm" | "solana",+ * tx_hash: "0xabc..." | "<base58 sig>",+ * onchain_id: "<EVM agentId>" | null, // null on Solana+ * contract_or_mint:"<EVM registry addr>" | "<Solana mint pubkey>",+ * wallet: "<owner address>",+ * metadata_uri: "ipfs://...",+ * confirmed_at: "<ISO timestamp>",+ * ... family-specific extras+ * }+ * }+ */++import { z } from 'zod';+import { Connection } from '@solana/web3.js';+import { JsonRpcProvider } from 'ethers';+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { parse } from '../../_lib/validate.js';+import { env } from '../../_lib/env.js';++const bodySchema = z.object({+ prep_id: z.string().min(8).max(80),+ tx_hash: z.string().min(8).max(120),+ onchain_id: z.string().nullable().optional(),+ wallet_address: z.string().min(20).max(80),+});++// ── Verifiers ────────────────────────────────────────────────────────────────++async function verifyEvm({ chainId, txHash, expectedContract, expectedOwner }) {+ const { CHAIN_BY_ID } = await import('../../_lib/erc8004-chains.js');+ const cfg = CHAIN_BY_ID[chainId];+ if (!cfg?.rpcUrl) throw new Error(`no RPC for chainId ${chainId}`);++ const provider = new JsonRpcProvider(cfg.rpcUrl);+ const receipt = await provider.getTransactionReceipt(txHash);+ if (!receipt) {+ const e = new Error('Transaction not found yet — try again in a few seconds.');+ e.code = 'tx_not_found';+ e.status = 422;+ throw e;+ }+ if (receipt.status !== 1) {+ const e = new Error('Transaction failed on-chain.');+ e.code = 'tx_failed';+ e.status = 422;+ throw e;+ }+ if (+ expectedContract &&+ receipt.to &&+ receipt.to.toLowerCase() !== expectedContract.toLowerCase()+ ) {+ const e = new Error('tx target does not match expected registry.');+ e.code = 'tx_wrong_target';+ e.status = 422;+ throw e;+ }+ if (receipt.from.toLowerCase() !== expectedOwner.toLowerCase()) {+ const e = new Error('tx sender does not match wallet_address.');+ e.code = 'tx_wrong_sender';+ e.status = 422;+ throw e;+ }+ return { blockNumber: receipt.blockNumber };+}++async function verifySolana({ cluster, txSig, expectedAsset, expectedOwner }) {+ const rpc =+ cluster === 'devnet'+ ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'+ : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+ const conn = new Connection(rpc, 'confirmed');++ // Bounded poll — RPC may not have indexed the tx yet, especially on devnet.+ const deadline = Date.now() + 20_000;+ let tx;+ while (Date.now() < deadline) {+ tx = await conn.getParsedTransaction(txSig, {+ maxSupportedTransactionVersion: 0,+ commitment: 'confirmed',+ });+ if (tx) break;+ await new Promise((r) => setTimeout(r, 1500));+ }+ if (!tx) {+ const e = new Error('Transaction not found on Solana RPC.');+ e.code = 'tx_not_found';+ e.status = 422;+ throw e;+ }+ if (tx.meta?.err) {+ const e = new Error('Transaction failed on-chain.');+ e.code = 'tx_failed';+ e.status = 422;+ throw e;+ }++ const accountKeys = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());+ if (expectedAsset && !accountKeys.includes(expectedAsset)) {+ const e = new Error('Asset pubkey not found in transaction.');+ e.code = 'asset_not_in_tx';+ e.status = 422;+ throw e;+ }+ if (!accountKeys.includes(expectedOwner)) {+ const e = new Error('Wallet address not in transaction signers.');+ e.code = 'wrong_signer';+ e.status = 422;+ throw e;+ }+ return { slot: tx.slot };+}++// ── Endpoint ─────────────────────────────────────────────────────────────────++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(bodySchema, await readJson(req));++ const [prep] = await sql`+ select id, payload, metadata_uri, cid+ from agent_registrations_pending+ where user_id = ${user.id}+ and payload->>'prep_id' = ${body.prep_id}+ and expires_at > now()+ limit 1+ `;+ if (!prep) return error(res, 404, 'not_found', 'prep record expired or not found');++ const p = prep.payload;+ if (p.wallet_address !== body.wallet_address) {+ return error(res, 400, 'validation_error', 'wallet_address mismatch with prep record');+ }++ // Verify on-chain+ try {+ if (p.chain_family === 'evm') {+ const chainId = Number(p.chain.split(':')[1]);+ await verifyEvm({+ chainId,+ txHash: body.tx_hash,+ expectedContract: p.contract_address,+ expectedOwner: body.wallet_address,+ });+ } else if (p.chain_family === 'solana') {+ await verifySolana({+ cluster: p.cluster,+ txSig: body.tx_hash,+ expectedAsset: p.asset_pubkey,+ expectedOwner: body.wallet_address,+ });+ } else {+ return error(res, 400, 'validation_error', `unknown chain family: ${p.chain_family}`);+ }+ } catch (e) {+ return error(res, e.status || 500, e.code || 'verify_failed', e.message);+ }++ // Link wallet to user (idempotent — confirm time, since tx is ownership proof).+ await sql`+ insert into user_wallets (user_id, address, chain_type, is_primary)+ values (${user.id}, ${body.wallet_address}, ${p.chain_family === 'solana' ? 'solana' : 'evm'}, false)+ on conflict do nothing+ `;++ // Build the unified onchain block.+ const onchain = {+ chain: p.chain,+ family: p.chain_family,+ tx_hash: body.tx_hash,+ onchain_id: body.onchain_id || null,+ contract_or_mint: p.contract_address || p.asset_pubkey || null,+ wallet: body.wallet_address,+ metadata_uri: prep.metadata_uri,+ confirmed_at: new Date().toISOString(),+ ...(p.chain_family === 'solana' ? { cluster: p.cluster } : {}),+ };++ // Upsert agent_identities. If a row already exists for (user, agent), we+ // merge the new onchain block in — supports redeploying across chains.+ const [existing] = await sql`+ select id, meta from agent_identities+ where user_id = ${user.id}+ and (id::text = ${p.agent_id} or name = ${p.name})+ and deleted_at is null+ limit 1+ `;++ let agent;+ if (existing) {+ const mergedMeta = { ...(existing.meta || {}), onchain };+ [agent] = await sql`+ update agent_identities+ set meta = ${JSON.stringify(mergedMeta)}::jsonb,+ wallet_address = ${body.wallet_address},+ updated_at = now()+ where id = ${existing.id}+ returning id, name, description, wallet_address, meta, created_at+ `;+ } else {+ [agent] = await sql`+ insert into agent_identities+ (user_id, name, description, avatar_id, wallet_address, meta)+ values (+ ${user.id},+ ${p.name},+ ${p.description},+ ${p.avatar_id},+ ${body.wallet_address},+ ${JSON.stringify({ onchain })}::jsonb+ )+ returning id, name, description, wallet_address, meta, created_at+ `;+ }++ // Cleanup prep+ await sql`delete from agent_registrations_pending where id = ${prep.id}`;++ return json(res, 201, {+ ok: true,+ agent: {+ ...agent,+ onchain,+ home_url: `${env.APP_ORIGIN}/agent/${agent.id}`,+ },+ });+});diff --git a/api/agents/onchain/prep.js b/api/agents/onchain/prep.jsindex bf18c2f0e..7d2c98d8c 100644--- a/api/agents/onchain/prep.js+++ b/api/agents/onchain/prep.js@@ -138,10 +138,9 @@ function buildManifest({ name, description, avatar_id, skills }) {async function prepEvm({ chainId, metadataUri }) {// EVM: client builds its own tx via ethers; we just hand back the metadata// URI and the registry address (looked up from the existing chain config).- const { REGISTRY_DEPLOYMENTS } = await import('../../_lib/erc8004-chains.js').catch(() => ({}));- const deployment = REGISTRY_DEPLOYMENTS?.[chainId];+ const { CHAIN_BY_ID } = await import('../../_lib/erc8004-chains.js');return {- contractAddress: deployment?.identityRegistry || null,+ contractAddress: CHAIN_BY_ID?.[chainId]?.registry || null,metadataUri,};}diff --git a/public/agent-passport.html b/public/agent-passport.htmlnew file mode 100644index 000000000..390f9395a--- /dev/null+++ b/public/agent-passport.html@@ -0,0 +1,162 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>Agent passport · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <style>+ * { box-sizing: border-box; }+ body { font: 14px/1.5 system-ui, sans-serif; max-width: 880px; margin: 2rem auto; padding: 0 1rem; color: #111; }+ h1 { font-size: 1.4rem; margin: 0 0 .25rem; }+ .muted { color: #666; }+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: .75rem; margin: 1rem 0; }+ .card { border: 1px solid #e5e5e5; border-radius: 8px; padding: .75rem 1rem; background: #fafafa; }+ .card .v { font-size: 1.6rem; font-weight: 600; }+ .card .l { font-size: .8rem; color: #666; }+ .row { display: flex; gap: 1rem; align-items: center; flex-wrap: wrap; margin: .5rem 0 1.5rem; }+ .pill { display: inline-block; padding: .15rem .55rem; border-radius: 999px; font-size: .75rem; }+ .ok { background: #e7f5e9; color: #1b5e20; }+ .warn { background: #fff3cd; color: #855008; }+ .bad { background: #fce8e8; color: #b71c1c; }+ .atts { border-top: 1px solid #eee; }+ .att { padding: .6rem 0; border-bottom: 1px solid #eee; display: grid; grid-template-columns: 80px 1fr auto; gap: .75rem; align-items: baseline; }+ .att code { font-size: .75rem; color: #555; }+ .kind-feedback { color: #1b5e20; }+ .kind-validation { color: #0d47a1; }+ .kind-task { color: #6a1b9a; }+ .kind-accept { color: #4527a0; }+ .kind-revoke { color: #b71c1c; }+ .kind-dispute { color: #ef6c00; }+ input { font: inherit; padding: .35rem .5rem; width: 100%; }+ button { font: inherit; padding: .35rem .75rem; border: 1px solid #ccc; background: #fff; border-radius: 6px; cursor: pointer; }+ details { margin-top: .25rem; }+ details pre { font-size: .75rem; background: #f4f4f4; padding: .4rem; border-radius: 4px; overflow: auto; }+ a { color: #0d47a1; }+ </style>+</head>+<body>+ <h1>Solana agent passport</h1>+ <p class="muted">ERC-8004-style identity, reputation, and validation — no deployed program. <a href="/.well-known/agent-attestation-schemas" target="_blank">View schemas</a></p>++ <div class="row">+ <input id="asset" placeholder="Metaplex Core asset pubkey…">+ <select id="network"><option value="devnet">devnet</option><option value="mainnet">mainnet</option></select>+ <button id="load">Load</button>+ </div>++ <div id="identity"></div>++ <h2 style="font-size: 1rem; margin: 1.5rem 0 .25rem;">Reputation</h2>+ <div id="reputation" class="grid"></div>++ <h2 style="font-size: 1rem; margin: 1.5rem 0 .25rem;">Recent attestations</h2>+ <div id="atts" class="atts"></div>++ <script type="module">+ const $ = (id) => document.getElementById(id);+ const params = new URLSearchParams(location.search);+ $('asset').value = params.get('asset') || '';+ $('network').value = params.get('network') || 'devnet';++ function pill(text, cls = '') { return `<span class="pill ${cls}">${text}</span>`; }+ function explorer(sig, net) {+ return `https://explorer.solana.com/tx/${sig}${net === 'devnet' ? '?cluster=devnet' : ''}`;+ }++ async function load() {+ const asset = $('asset').value.trim();+ const network = $('network').value;+ if (!asset) return;+ history.replaceState({}, '', `?asset=${asset}&network=${network}`);++ $('identity').innerHTML = '<p class="muted">loading…</p>';++ let card;+ try {+ card = await (await fetch(`/api/agents/solana-card?asset=${asset}`)).json();+ } catch {}++ let rep, atts;+ [rep, atts] = await Promise.all([+ fetch(`/api/agents/solana-reputation?asset=${asset}&network=${network}`).then((r) => r.json()),+ fetch(`/api/agents/solana-attestations?asset=${asset}&network=${network}&limit=25`).then((r) => r.json()),+ ]);++ renderIdentity(card, asset, network);+ renderReputation(rep);+ renderAttestations(atts.data || [], network);+ }++ function renderIdentity(card, asset, network) {+ const id = card?.identity || {};+ const name = card?.name || '(unindexed agent)';+ $('identity').innerHTML = `+ <div class="card" style="background:white;">+ <div style="font-size:1.2rem;font-weight:600">${name}</div>+ <div class="muted">${card?.description || ''}</div>+ <div class="muted" style="margin-top:.4rem;font-size:.8rem">+ <code>${asset}</code> · <span class="pill ${network === 'mainnet' ? 'ok' : 'warn'}">${network}</span>+ ${id.owner ? ` · owner <code>${id.owner.slice(0, 6)}…${id.owner.slice(-4)}</code>` : ''}+ </div>+ </div>`;+ }++ function renderReputation(r) {+ if (!r || r.error) { $('reputation').innerHTML = `<p class="muted">no data</p>`; return; }+ const f = r.feedback || {}, v = r.validation || {};+ const verifiedPct = f.total ? Math.round((f.verified / f.total) * 100) : 0;+ $('reputation').innerHTML = `+ <div class="card"><div class="v">${f.score_avg_weighted_verified?.toFixed(2) || '—'}</div><div class="l">verified weighted score (1–5)</div></div>+ <div class="card"><div class="v">${f.score_avg_weighted?.toFixed(2) || '—'}</div><div class="l">all weighted score</div></div>+ <div class="card"><div class="v">${f.unique_verified_attesters || 0}<span class="muted" style="font-size:1rem">/${f.unique_attesters || 0}</span></div><div class="l">verified attesters / unique</div></div>+ <div class="card"><div class="v">${f.verified || 0}<span class="muted" style="font-size:1rem">/${f.total || 0}</span></div><div class="l">verified / total feedback (${verifiedPct}%)</div></div>+ <div class="card"><div class="v">${v.passed || 0}<span class="muted" style="font-size:1rem">/${(v.passed||0)+(v.failed||0)}</span></div><div class="l">validation passed</div></div>+ <div class="card"><div class="v">${f.disputed || 0}</div><div class="l">disputed</div></div>+ <div class="card"><div class="v">${r.tasks?.accepted || 0}<span class="muted" style="font-size:1rem">/${r.tasks?.offered || 0}</span></div><div class="l">tasks accepted / offered</div></div>+ <div class="card"><div class="v">${r.revoked_count || 0}</div><div class="l">revoked</div></div>+ `;+ }++ function renderAttestations(rows, net) {+ if (!rows.length) { $('atts').innerHTML = `<p class="muted">no attestations yet</p>`; return; }+ $('atts').innerHTML = rows.map((row) => {+ const k = row.kind.split('.')[1];+ const flags = [];+ if (row.verified) flags.push(pill('verified', 'ok'));+ if (row.disputed) flags.push(pill('disputed', 'warn'));+ return `+ <div class="att">+ <div class="kind-${k}"><strong>${k}</strong></div>+ <div>+ <div>${describe(row)}</div>+ <div class="muted" style="font-size:.75rem">+ by <code>${row.attester?.slice(0,6)}…${row.attester?.slice(-4) || ''}</code>+ · slot ${row.slot}+ · <a href="${explorer(row.signature, net)}" target="_blank">tx</a>+ ${flags.join(' ')}+ </div>+ <details><summary class="muted" style="font-size:.75rem">payload</summary><pre>${JSON.stringify(row.payload, null, 2)}</pre></details>+ </div>+ <div></div>+ </div>`;+ }).join('');+ }++ function describe(row) {+ const p = row.payload || {};+ switch (row.kind) {+ case 'threews.feedback.v1': return `score ${p.score}/5${p.task_id ? ` for task ${p.task_id}` : ''}`;+ case 'threews.validation.v1': return `validation ${p.passed ? '✓ passed' : '✗ failed'} (task hash ${p.task_hash?.slice(0,12)}…)`;+ case 'threews.task.v1': return `task offered: ${p.task_id}`;+ case 'threews.accept.v1': return `task accepted: ${p.task_id}`;+ case 'threews.revoke.v1': return `revoked ${p.target_signature?.slice(0,12)}…`;+ case 'threews.dispute.v1': return `disputed ${p.target_signature?.slice(0,12)}…${p.reason ? ` — ${p.reason}` : ''}`;+ default: return row.kind;+ }+ }++ $('load').onclick = load;+ if ($('asset').value) load();+ </script>+</body>+</html>diff --git a/vercel.json b/vercel.jsonindex 850adba96..baf0363a0 100644--- a/vercel.json+++ b/vercel.json@@ -238,6 +238,7 @@"dest": "/a-embed.html"},{ "src": "/a/(\\d+)/(\\d+)", "dest": "/api/a-page?chain=$1&id=$2" },+ { "src": "/a/sol/([^/]+)", "dest": "/agent-passport.html?asset=$1" },{ "src": "/a/(.*)", "dest": "/app.html" },{ "src": "/(.*)", "dest": "/$1" }],