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(register): unblock ERC-8004 prep and bind confirm onto the agent it deployed
nirholas02bd839c9f12
diff --git a/api/_lib/migrations/20260806120000_agent_reg_pending_cid_nullable.sql b/api/_lib/migrations/20260806120000_agent_reg_pending_cid_nullable.sqlnew file mode 100644index 000000000..efaa1a970--- /dev/null+++ b/api/_lib/migrations/20260806120000_agent_reg_pending_cid_nullable.sql@@ -0,0 +1,6 @@+-- The registration prep pipeline stores the manifest in R2 (a plain HTTPS+-- metadata URI) when no IPFS pinning provider is configured, which is the+-- default deployment shape. There is no CID in that case, but the column was+-- NOT NULL, so every prep 500'd at the insert. Make cid nullable; metadata_uri+-- remains the authoritative pointer either way.+alter table agent_registrations_pending alter column cid drop not null;diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 3c48f58fc..3f0f9765b 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -1048,7 +1048,7 @@ create index if not exists usage_events_metered_user_time on usage_events(user_icreate table if not exists agent_registrations_pending (id uuid primary key default gen_random_uuid(),user_id uuid not null references users(id) on delete cascade,- cid text not null, -- IPFS CID+ cid text, -- IPFS CID (null when stored via the R2 fallback)metadata_uri text not null, -- ipfs://CIDpayload jsonb not null, -- registration JSONcreated_at timestamptz not null default now(),diff --git a/api/agents/register/[action].js b/api/agents/register/[action].jsindex f48d55377..231533062 100644--- a/api/agents/register/[action].js+++ b/api/agents/register/[action].js@@ -1,6 +1,6 @@// Consolidated ERC-8004 agent registration endpoints.// prep: build metadata + pin + store record-// confirm: verify on-chain tx, upsert agent_identities+// confirm: verify on-chain tx, upsert agent_identities + erc8004_agents_indeximport { sql } from '../../_lib/db.js';import { getSessionUser } from '../../_lib/auth.js';@@ -11,6 +11,7 @@ import { env } from '../../_lib/env.js';import { erc8004RegistryFields } from '../../_lib/three-brand.js';import { r2, publicUrl } from '../../_lib/r2.js';import { SERVER_CHAIN_META } from '../../_lib/onchain.js';+import { evmRpcEndpoints } from '../../_lib/evm/rpc.js';import { publishFeedEvent } from '../../_lib/feed.js';import { PutObjectCommand } from '@aws-sdk/client-s3';import { AbiCoder, getAddress, keccak256, toUtf8Bytes } from 'ethers';@@ -20,8 +21,14 @@ import { z } from 'zod';const prepSchema = z.object({name: z.string().trim().min(1).max(60),- description: z.string().trim().max(280),+ // agent_identities bios run up to 500 chars (api/agents.js) — accept the+ // same cap here so a long bio doesn't 400 the deploy.+ description: z.string().trim().max(500),avatarId: z.string().uuid(),+ // When deploying an EXISTING three.ws agent (the profile-page DeployButton),+ // its row id — confirm binds the on-chain identity onto that row instead of+ // inserting a duplicate.+ agentDbId: z.string().uuid().optional(),brain: z.object({ provider: z.string().optional(), model: z.string().optional(), instructions: z.string().optional() }).optional(),skills: z.array(z.string().regex(/^[a-z0-9-]{1,40}$/i)).max(16).optional(),embedPolicy: z.record(z.any()).optional(),@@ -55,8 +62,12 @@ async function pinRegistrationJson(jsonObj) {await storeToR2(jsonBytes);return { cid: r.cid, metadataURI: `ipfs://${r.cid}` };}+ } else {+ console.warn('[register/prep] web3.storage upload failed:', res.status);}- } catch {}+ } catch (e) {+ console.warn('[register/prep] web3.storage upload error:', e?.message);+ }}// 2. Try Pinata if configured.@@ -76,8 +87,12 @@ async function pinRegistrationJson(jsonObj) {await storeToR2(jsonBytes);return { cid: r.IpfsHash, metadataURI: `ipfs://${r.IpfsHash}` };}+ } else {+ console.warn('[register/prep] pinata upload failed:', res.status);}- } catch {}+ } catch (e) {+ console.warn('[register/prep] pinata upload error:', e?.message);+ }}// 3. No IPFS provider — store in R2 and return a real HTTPS URL.@@ -96,6 +111,10 @@ async function handlePrep(req, res) {const body = parse(prepSchema, await readJson(req));const [avatar] = await sql`select id from avatars where id = ${body.avatarId} and owner_id = ${session.id} and deleted_at is null limit 1`;if (!avatar) return error(res, 404, 'not_found', 'avatar not found');+ if (body.agentDbId) {+ const [agent] = await sql`select id from agent_identities where id = ${body.agentDbId} and user_id = ${session.id} and deleted_at is null limit 1`;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ }const registrationJson = {$schema: 'https://3d-agent.io/schemas/manifest/0.1.json', spec: 'agent-manifest/0.1',name: body.name, description: body.description, image: '', tags: [],@@ -110,7 +129,10 @@ async function handlePrep(req, res) {};const { cid, metadataURI } = await pinRegistrationJson(registrationJson);const expiresAt = new Date(Date.now() + 60 * 60 * 1000);- const [prep] = await sql`insert into agent_registrations_pending (user_id, cid, metadata_uri, payload, expires_at) values (${session.id}, ${cid}, ${metadataURI}, ${JSON.stringify(registrationJson)}::jsonb, ${expiresAt}) returning id`;+ // payload stores the pinned manifest plus a _local block confirm needs to+ // bind the identity row (never pinned — added after the pin above).+ const payload = { ...registrationJson, _local: { avatarId: body.avatarId, ...(body.agentDbId ? { agentDbId: body.agentDbId } : {}) } };+ const [prep] = await sql`insert into agent_registrations_pending (user_id, cid, metadata_uri, payload, expires_at) values (${session.id}, ${cid}, ${metadataURI}, ${JSON.stringify(payload)}::jsonb, ${expiresAt}) returning id`;return json(res, 200, { ok: true, cid, metadataURI, prepId: prep.id });}@@ -119,25 +141,58 @@ async function handlePrep(req, res) {const confirmSchema = z.object({prepId: z.string().uuid(),chainId: z.number().int().positive(),- agentId: z.union([z.string(), z.number()]),+ // The client's best-effort parse of the Registered event. '0'/absent means+ // "couldn't parse" — the server-decoded event id is authoritative either way.+ agentId: z.union([z.string(), z.number()]).optional(),txHash: z.string().regex(/^0x[a-f0-9]{64}$/i),});-function eventSignatureHash(sig) { return keccak256(toUtf8Bytes(sig)); }+const RPC_TIMEOUT_MS = 10_000;+const REGISTERED_TOPIC = keccak256(toUtf8Bytes('Registered(uint256,string,address)'));-async function fetchTransactionReceipt(rpcUrl, txHash) {- const res = await fetch(rpcUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_getTransactionReceipt', params: [txHash] }) });- const data = await res.json();- if (data.error) throw new Error(`RPC error: ${data.error.message}`);- return data.result;+// eth_getTransactionReceipt with sequential failover across the chain's full+// endpoint list (RPC_URL_<id> override → Alchemy → keyless public tail).+async function fetchTransactionReceipt(chainId, primaryUrl, txHash) {+ const urls = evmRpcEndpoints(chainId, primaryUrl);+ let lastErr;+ for (const url of urls.length ? urls : [primaryUrl]) {+ const ac = new AbortController();+ const t = setTimeout(() => ac.abort(), RPC_TIMEOUT_MS);+ try {+ const res = await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_getTransactionReceipt', params: [txHash] }),+ signal: ac.signal,+ });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data = await res.json();+ if (data.error) throw new Error(`RPC error: ${data.error.message}`);+ return data.result;+ } catch (err) {+ lastErr = err;+ } finally {+ clearTimeout(t);+ }+ }+ throw lastErr ?? new Error('no RPC endpoint available');}+/**+ * Decode the Registered(uint256 indexed agentId, string agentURI, address+ * indexed owner) event emitted by the Identity Registry. Returns the full+ * on-chain truth — id and owner from the indexed topics, URI from the data —+ * so nothing security-relevant comes from the client.+ */function parseRegisteredEvent(logs, registryAddress) {const registryAddr = getAddress(registryAddress);- const topic0 = eventSignatureHash('Registered(uint256,string,address)');- for (const log of logs) {- if (getAddress(log.address) === registryAddr && log.topics[0] === topic0) {- return AbiCoder.defaultAbiCoder().decode(['string'], log.data)[0];+ for (const log of logs ?? []) {+ if (getAddress(log.address) === registryAddr && log.topics?.[0] === REGISTERED_TOPIC) {+ return {+ onChainId: BigInt(log.topics[1]).toString(),+ owner: getAddress('0x' + log.topics[2].slice(-40)).toLowerCase(),+ agentURI: AbiCoder.defaultAbiCoder().decode(['string'], log.data)[0],+ };}}throw new Error('Registered event not found in receipt');@@ -156,15 +211,84 @@ async function handleConfirm(req, res) {const [prep] = await sql`select id, cid, metadata_uri, payload from agent_registrations_pending where id = ${body.prepId} and user_id = ${session.id} and expires_at > now() limit 1`;if (!prep) return error(res, 404, 'not_found', 'prep record not found or expired');let receipt;- try { receipt = await fetchTransactionReceipt(chainMeta.rpc, body.txHash); }+ try { receipt = await fetchTransactionReceipt(body.chainId, chainMeta.rpc, body.txHash); }catch (err) { return error(res, 400, 'bad_request', `tx verification failed: ${err.message}`); }if (!receipt) return error(res, 400, 'bad_request', 'tx not found or still pending');- if (receipt.status !== 1) return error(res, 400, 'bad_request', 'tx failed on-chain');- let agentURI;- try { agentURI = parseRegisteredEvent(receipt.logs, chainMeta.registry); }+ const status = typeof receipt.status === 'string' ? Number.parseInt(receipt.status, 16) : receipt.status;+ if (status !== 1) return error(res, 400, 'bad_request', 'tx failed on-chain');+ let ev;+ try { ev = parseRegisteredEvent(receipt.logs, chainMeta.registry); }catch (err) { return error(res, 400, 'bad_request', `failed to parse event: ${err.message}`); }- if (agentURI !== prep.metadata_uri) return error(res, 409, 'conflict', `metadata URI mismatch: expected ${prep.metadata_uri} got ${agentURI}`);- const [updated] = await sql`insert into agent_identities (user_id, name, description, avatar_id, chain_id, erc8004_agent_id, erc8004_registry, registration_cid) values (${session.id}, ${(prep.payload.name || 'Unnamed Agent').slice(0, 255)}, ${(prep.payload.description || '').slice(0, 1000)}, null, ${body.chainId}, ${String(body.agentId)}, ${chainMeta.registry}, ${prep.cid}) on conflict (user_id) do update set name=excluded.name, description=excluded.description, chain_id=excluded.chain_id, erc8004_agent_id=excluded.erc8004_agent_id, erc8004_registry=excluded.erc8004_registry, registration_cid=excluded.registration_cid, updated_at=now() returning id`;+ if (ev.agentURI !== prep.metadata_uri) return error(res, 409, 'conflict', `metadata URI mismatch: expected ${prep.metadata_uri} got ${ev.agentURI}`);+ // The client's parsed agentId is advisory; when it claims one, it must match+ // the id the chain actually emitted.+ const claimed = body.agentId == null ? null : String(body.agentId);+ if (claimed && claimed !== '0' && claimed !== ev.onChainId) {+ return error(res, 409, 'conflict', `agentId mismatch: receipt says ${ev.onChainId}`);+ }++ const local = prep.payload?._local || {};+ const onchain = {+ chain: `eip155:${body.chainId}`,+ family: 'evm',+ tx_hash: body.txHash,+ onchain_id: ev.onChainId,+ contract_or_mint: chainMeta.registry,+ wallet: ev.owner,+ metadata_uri: prep.metadata_uri,+ confirmed_at: new Date().toISOString(),+ };++ let identityId;+ if (local.agentDbId) {+ // Bind onto the existing agent row the DeployButton was pressed on —+ // merge meta.onchain, never clobber the agent's own name/description.+ const [existing] = await sql`select id, meta from agent_identities where id = ${local.agentDbId} and user_id = ${session.id} and deleted_at is null limit 1`;+ if (existing) {+ const mergedMeta = { ...(existing.meta || {}), onchain };+ await sql`+ update agent_identities+ set meta = ${JSON.stringify(mergedMeta)}::jsonb,+ wallet_address = ${ev.owner},+ chain_id = ${body.chainId},+ erc8004_agent_id = ${BigInt(ev.onChainId)},+ erc8004_registry = ${chainMeta.registry},+ registration_cid = ${prep.cid ?? prep.metadata_uri},+ updated_at = now()+ where id = ${existing.id} and user_id = ${session.id}+ `;+ identityId = existing.id;+ }+ }+ if (!identityId) {+ const [inserted] = await sql`+ insert into agent_identities+ (user_id, name, description, avatar_id, wallet_address, chain_id, erc8004_agent_id, erc8004_registry, registration_cid, meta)+ values+ (${session.id}, ${(prep.payload.name || 'Unnamed Agent').slice(0, 255)}, ${(prep.payload.description || '').slice(0, 1000)},+ ${local.avatarId ?? null}, ${ev.owner}, ${body.chainId}, ${BigInt(ev.onChainId)}, ${chainMeta.registry},+ ${prep.cid ?? prep.metadata_uri}, ${JSON.stringify({ onchain })}::jsonb)+ returning id+ `;+ identityId = inserted.id;+ }++ // Mirror into the public registry index so /deployments shows the agent the+ // moment the tx confirms, instead of waiting for the next crawler pass.+ await sql`+ insert into erc8004_agents_index+ (chain_id, agent_id, owner, registry, agent_uri, name, description, active,+ registered_block, registered_tx, registered_at, last_seen_at)+ values+ (${body.chainId}, ${ev.onChainId}, ${ev.owner}, ${chainMeta.registry.toLowerCase()},+ ${prep.metadata_uri}, ${(prep.payload.name || '').slice(0, 200) || null},+ ${(prep.payload.description || '').slice(0, 1000) || null}, true,+ ${Number.parseInt(receipt.blockNumber, 16) || null}, ${body.txHash}, now(), now())+ on conflict (chain_id, agent_id) do update+ set agent_uri = excluded.agent_uri, name = excluded.name,+ description = excluded.description, last_seen_at = now()+ `.catch((e) => console.warn('[register/confirm] index mirror failed:', e?.message));+await sql`delete from agent_registrations_pending where id = ${body.prepId}`;// Truthful "deployed on-chain" ticker event — only after the ERC-8004 tx is// verified and the agent row carries its on-chain id. Fire-and-forget.@@ -172,11 +296,11 @@ async function handleConfirm(req, res) {type: 'agent-onchain',ts: Date.now(),actor: prep.payload.name || 'An agent',- agentId: updated.id,+ agentId: identityId,name: prep.payload.name || 'An agent',chain: chainMeta.name || 'EVM',}).catch(() => {});- return json(res, 200, { ok: true, agentId: updated.id });+ return json(res, 200, { ok: true, agentId: identityId, onchainAgentId: ev.onChainId, owner: ev.owner });}// ── dispatcher ────────────────────────────────────────────────────────────────