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 wallet adapters for EVM and Solana, unify deploy process

nirholas9fa5a8587365
diff --git a/api/mcp.js b/api/mcp.js
index 8d939553c..0e89170b2 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -26,6 +26,7 @@ import {
deleteAvatar,
} from './_lib/avatars.js';
import { fetchModel, FetchModelError } from './_lib/fetch-model.js';
+import { crawlAgentAttestations, KIND_MAP } from './_lib/solana-attestations.js';
import { inspectModel, suggestOptimizations } from './_lib/model-inspect.js';
import { validateBytes } from 'gltf-validator';
@@ -367,6 +368,57 @@ const TOOL_CATALOG = [
additionalProperties: false,
},
},
+ {
+ name: 'solana_agent_reputation',
+ title: 'Get Solana agent reputation',
+ description:
+ 'Computed reputation summary for a Solana-registered three.ws agent. Returns total/verified feedback counts, score averages (raw + verified-only), validation pass/fail, task acceptance, and dispute counts. Verified score only includes feedback whose task was acknowledged on-chain by the agent owner. Public; no auth required.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ asset: { type: 'string', description: 'Metaplex Core asset pubkey (the agent ID)' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'devnet' },
+ },
+ required: ['asset'],
+ additionalProperties: false,
+ },
+ },
+ {
+ name: 'solana_agent_attestations',
+ title: 'List Solana agent attestations',
+ description:
+ 'List recent on-chain attestations about a Solana-registered agent (feedback, validation, task offers, acceptances, disputes). Backed by the three.ws indexer for sub-100ms reads. Each row includes verified/disputed/revoked flags. Public; no auth required.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ asset: { type: 'string' },
+ kind: {
+ type: 'string',
+ enum: ['feedback', 'validation', 'task', 'accept', 'revoke', 'dispute', 'all'],
+ default: 'all',
+ },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'devnet' },
+ limit: { type: 'integer', minimum: 1, maximum: 200, default: 50 },
+ },
+ required: ['asset'],
+ additionalProperties: false,
+ },
+ },
+ {
+ name: 'solana_agent_passport',
+ title: 'Get Solana agent passport',
+ description:
+ 'Full discovery card for a Solana agent: identity (Metaplex Core asset), owner wallet, reputation summary, latest validation result, and attestation schema endpoint. Equivalent to an ERC-8004 passport — use this when one tool call should answer "who is this agent and can I trust them?".',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ asset: { type: 'string' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'devnet' },
+ },
+ required: ['asset'],
+ additionalProperties: false,
+ },
+ },
];
const TOOLS = {
diff --git a/src/onchain/adapters/base.js b/src/onchain/adapters/base.js
new file mode 100644
index 000000000..c0d0ab900
--- /dev/null
+++ b/src/onchain/adapters/base.js
@@ -0,0 +1,90 @@
+/**
+ * WalletAdapter — the contract every chain family implements.
+ *
+ * The deploy orchestrator only ever sees this interface. New chains plug in by
+ * adding a new adapter; the UI stays family-agnostic.
+ */
+
+/**
+ * @typedef {object} ConnectResult
+ * @property {string} address User's wallet address (hex for EVM, base58 for Solana).
+ * @property {import('../chain-ref.js').ChainRef} ref Chain the wallet is currently on.
+ */
+
+/**
+ * @typedef {object} PrepResponse
+ * @property {string} prepId
+ * @property {string} metadataUri // ipfs:// or https:// pointing at the manifest
+ * @property {string} [contractAddress] // EVM: identity-registry address
+ * @property {string} [txBase64] // Solana: serialized unsigned tx
+ * @property {string} [assetPubkey] // Solana: mint pubkey
+ * @property {string} [chainCaip2]
+ */
+
+/**
+ * @typedef {object} SignResult
+ * @property {string} txHash // EVM tx hash or Solana signature
+ * @property {string} [onchainId] // Optional family-specific ID (EVM agentId, Solana asset)
+ */
+
+/**
+ * @abstract
+ */
+export class WalletAdapter {
+ /** @returns {string} 'evm' | 'solana' */
+ get family() {
+ throw new Error('not implemented');
+ }
+
+ /** @returns {boolean} Whether an injected provider is detectable. */
+ isAvailable() {
+ throw new Error('not implemented');
+ }
+
+ /** @returns {string} URL to install a typical wallet for this family. */
+ installUrl() {
+ throw new Error('not implemented');
+ }
+
+ /**
+ * Connect (and on-Solana, optionally SIWS-link) the user's wallet.
+ * Implementations must throw on user rejection with `err.code === 'USER_REJECTED'`.
+ * @param {{ ensureLinked?: boolean, csrfToken?: string }} [opts]
+ * @returns {Promise<ConnectResult>}
+ */
+ async connect(_opts) {
+ throw new Error('not implemented');
+ }
+
+ /**
+ * Switch the wallet to the given ChainRef. EVM wallets prompt the user;
+ * Solana wallets typically have no concept of switching — adapters return
+ * silently if already on the right cluster, or throw if mismatched.
+ * @param {import('../chain-ref.js').ChainRef} ref
+ */
+ async switchTo(_ref) {
+ throw new Error('not implemented');
+ }
+
+ /**
+ * Sign and submit the prep transaction returned by the server.
+ * @param {PrepResponse} prep
+ * @param {import('../chain-ref.js').ChainRef} ref
+ * @returns {Promise<SignResult>}
+ */
+ async signAndSend(_prep, _ref) {
+ throw new Error('not implemented');
+ }
+}
+
+/** Helper: classify a thrown error as a user rejection across providers. */
+export function isUserRejection(err) {
+ if (!err) return false;
+ if (err.code === 'USER_REJECTED') return true;
+ if (err.code === 4001) return true;
+ if (err.code === 'ACTION_REJECTED') return true;
+ const msg = String(err.message || err).toLowerCase();
+ return /user rejected|user denied|rejected by user|user cancel|signature cancel|connection cancel/.test(
+ msg,
+ );
+}
diff --git a/src/onchain/adapters/evm.js b/src/onchain/adapters/evm.js
new file mode 100644
index 000000000..3bfcd4694
--- /dev/null
+++ b/src/onchain/adapters/evm.js
@@ -0,0 +1,73 @@
+/**
+ * EvmAdapter — wraps an injected EIP-1193 provider (MetaMask, Brave, Rabby…).
+ *
+ * Reuses the existing ethers integration in src/erc8004/agent-registry.js so we
+ * don't fork wallet state. The adapter is a thin facade over those helpers.
+ */
+
+import { WalletAdapter } from './base.js';
+import { ensureWallet, getIdentityRegistry } from '../../erc8004/agent-registry.js';
+import { switchChain, CHAIN_META } from '../../erc8004/chain-meta.js';
+import { evm } from '../chain-ref.js';
+
+export class EvmAdapter extends WalletAdapter {
+ get family() {
+ return 'evm';
+ }
+
+ isAvailable() {
+ return typeof window !== 'undefined' && !!window.ethereum;
+ }
+
+ installUrl() {
+ return 'https://metamask.io/download/';
+ }
+
+ async connect() {
+ const { signer, chainId } = await ensureWallet();
+ const address = await signer.getAddress();
+ return { address, ref: evm(chainId) };
+ }
+
+ async switchTo(ref) {
+ if (ref.family !== 'evm') {
+ throw new Error('EvmAdapter cannot switch to non-EVM chain');
+ }
+ await switchChain(ref.chainId);
+ }
+
+ async signAndSend(prep, ref) {
+ if (ref.family !== 'evm') throw new Error('EvmAdapter expects an EVM ChainRef');
+ const { signer } = await ensureWallet();
+ const registry = getIdentityRegistry(ref.chainId, signer);
+
+ const tx = await registry['register(string)'](prep.metadataUri);
+ const receipt = await tx.wait();
+ if (receipt?.status !== 1) {
+ const e = new Error('EVM transaction reverted');
+ e.code = 'TX_REVERTED';
+ throw e;
+ }
+
+ // Pull the agentId out of the Registered event for cross-checking server-side.
+ let onchainId = null;
+ for (const log of receipt.logs || []) {
+ try {
+ const parsed = registry.interface.parseLog(log);
+ if (parsed?.name === 'Registered') {
+ onchainId = String(parsed.args.agentId);
+ break;
+ }
+ } catch {
+ /* not our event */
+ }
+ }
+
+ return { txHash: tx.hash, onchainId };
+ }
+
+ /** @param {number} chainId */
+ chainName(chainId) {
+ return CHAIN_META[chainId]?.name || `Chain ${chainId}`;
+ }
+}
diff --git a/src/onchain/adapters/index.js b/src/onchain/adapters/index.js
new file mode 100644
index 000000000..b63235fc1
--- /dev/null
+++ b/src/onchain/adapters/index.js
@@ -0,0 +1,32 @@
+/**
+ * Adapter factory — pick the right WalletAdapter for a ChainRef family.
+ *
+ * Adapters are stateful (they hold the wallet provider handle), so callers
+ * generally hold one instance per family for the lifetime of the page.
+ */
+
+import { EvmAdapter } from './evm.js';
+import { SolanaAdapter } from './solana.js';
+
+const cache = new Map();
+
+/**
+ * @param {'evm'|'solana'} family
+ * @returns {import('./base.js').WalletAdapter}
+ */
+export function getAdapter(family) {
+ if (cache.has(family)) return cache.get(family);
+ let inst;
+ if (family === 'evm') inst = new EvmAdapter();
+ else if (family === 'solana') inst = new SolanaAdapter();
+ else throw new Error(`No adapter for chain family: ${family}`);
+ cache.set(family, inst);
+ return inst;
+}
+
+/** Test hook — forget cached adapters. */
+export function _resetAdapters() {
+ cache.clear();
+}
+
+export { isUserRejection } from './base.js';
diff --git a/src/onchain/adapters/solana.js b/src/onchain/adapters/solana.js
new file mode 100644
index 000000000..b51ef9c6c
--- /dev/null
+++ b/src/onchain/adapters/solana.js
@@ -0,0 +1,245 @@
+/**
+ * SolanaAdapter — Phantom / Backpack / Solflare via window injection.
+ *
+ * Two responsibilities the EVM adapter doesn't have:
+ * 1. Inline SIWS linking. If the wallet isn't yet linked to the user's
+ * account, this adapter runs the SIWS challenge as part of `connect()` so
+ * the deploy flow stays single-click. Implementation mirrors
+ * public/wallet/connect-button-solana.js but is callable headlessly.
+ * 2. Cluster control. We always submit the signed tx through a Connection we
+ * construct on the chosen cluster, never via the wallet's
+ * signAndSendTransaction default — the wallet's RPC may be on a different
+ * cluster than the one the user picked in the UI.
+ */
+
+import { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';
+import { WalletAdapter } from './base.js';
+import { solana } from '../chain-ref.js';
+
+const RPC = {
+ mainnet: 'https://api.mainnet-beta.solana.com',
+ devnet: 'https://api.devnet.solana.com',
+};
+
+function detect(preferred) {
+ if (typeof window === 'undefined') return null;
+ if (preferred === 'phantom') return window.phantom?.solana || window.solana || null;
+ if (preferred === 'backpack') return window.backpack?.solana || null;
+ if (preferred === 'solflare') return window.solflare || null;
+ if (window.phantom?.solana?.isPhantom) return window.phantom.solana;
+ if (window.solana?.isPhantom) return window.solana;
+ if (window.backpack?.solana) return window.backpack.solana;
+ if (window.solflare?.isSolflare) return window.solflare;
+ return null;
+}
+
+function toBase64(bytes) {
+ let s = '';
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
+ return btoa(s);
+}
+
+function decodeTx(b64) {
+ const bin = atob(b64);
+ const bytes = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
+ try {
+ return VersionedTransaction.deserialize(bytes);
+ } catch {
+ return Transaction.from(bytes);
+ }
+}
+
+export class SolanaAdapter extends WalletAdapter {
+ #provider = null;
+ #address = null;
+ #preferred;
+
+ constructor({ preferredWallet = null } = {}) {
+ super();
+ this.#preferred = preferredWallet;
+ }
+
+ get family() {
+ return 'solana';
+ }
+
+ isAvailable() {
+ return !!detect(this.#preferred);
+ }
+
+ installUrl() {
+ if (this.#preferred === 'backpack') return 'https://www.backpack.app';
+ if (this.#preferred === 'solflare') return 'https://solflare.com';
+ return 'https://phantom.app';
+ }
+
+ /**
+ * Connect, and if the wallet isn't linked to the current session, run SIWS
+ * inline so the caller doesn't have to redirect the user.
+ * @param {{ ensureLinked?: boolean, cluster?: 'mainnet'|'devnet' }} [opts]
+ */
+ async connect({ ensureLinked = true, cluster = 'mainnet' } = {}) {
+ const provider = detect(this.#preferred);
+ if (!provider) {
+ const err = new Error('No Solana wallet detected.');
+ err.code = 'NO_PROVIDER';
+ throw err;
+ }
+ this.#provider = provider;
+
+ let resp;
+ try {
+ resp = await provider.connect();
+ } catch (e) {
+ if (e?.code === 4001 || /reject/i.test(e?.message || '')) {
+ const err = new Error('Connection cancelled.');
+ err.code = 'USER_REJECTED';
+ throw err;
+ }
+ throw e;
+ }
+ this.#address = (resp?.publicKey || provider.publicKey)?.toString();
+ if (!this.#address) throw new Error('Could not read Solana wallet address.');
+
+ if (ensureLinked) {
+ await this.#ensureLinkedViaSiws(cluster);
+ }
+
+ return { address: this.#address, ref: solana(cluster) };
+ }
+
+ async switchTo(ref) {
+ // Solana wallets don't expose a switchCluster RPC. We respect the user's
+ // selection by sending the tx to our own Connection on the chosen
+ // cluster (see signAndSend). Nothing to do here.
+ if (ref.family !== 'solana') throw new Error('SolanaAdapter cannot switch to non-Solana');
+ }
+
+ async signAndSend(prep, ref) {
+ if (ref.family !== 'solana') throw new Error('SolanaAdapter expects a Solana ChainRef');
+ if (!this.#provider) throw new Error('Wallet not connected');
+ if (!prep.txBase64) throw new Error('Solana prep missing txBase64');
+
+ const tx = decodeTx(prep.txBase64);
+ const conn = new Connection(RPC[ref.cluster], 'confirmed');
+
+ // Always go through signTransaction + our own Connection so we control
+ // which cluster the tx lands on. Avoids the silent mismatch where
+ // Phantom is set to mainnet but the user picked devnet (or vice versa).
+ let signed;
+ try {
+ signed = await this.#provider.signTransaction(tx);
+ } catch (e) {
+ if (e?.code === 4001 || /reject/i.test(e?.message || '')) {
+ const err = new Error('Signature cancelled.');
+ err.code = 'USER_REJECTED';
+ throw err;
+ }
+ throw e;
+ }
+
+ const raw = signed.serialize();
+ const signature = await conn.sendRawTransaction(raw, {
+ skipPreflight: false,
+ preflightCommitment: 'confirmed',
+ });
+
+ // Poll signature status with a real deadline. confirmTransaction is
+ // deprecated and unreliable on devnet.
+ await this.#waitForConfirmation(conn, signature, 60_000);
+
+ return { txHash: signature, onchainId: prep.assetPubkey || null };
+ }
+
+ async #waitForConfirmation(conn, signature, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const { value } = await conn.getSignatureStatuses([signature]);
+ const status = value?.[0];
+ if (status) {
+ if (status.err) {
+ const e = new Error(`Tx failed: ${JSON.stringify(status.err)}`);
+ e.code = 'TX_FAILED';
+ throw e;
+ }
+ if (
+ status.confirmationStatus === 'confirmed' ||
+ status.confirmationStatus === 'finalized'
+ ) {
+ return;
+ }
+ }
+ await new Promise((r) => setTimeout(r, 1_000));
+ }
+ const e = new Error('Confirmation timed out after 60s. Tx may still land — check explorer.');
+ e.code = 'TX_TIMEOUT';
+ throw e;
+ }
+
+ async #ensureLinkedViaSiws(cluster) {
+ // Cheap pre-check: if already linked for this user+address, skip the
+ // signature prompt. Uses an existing endpoint that returns 200 if the
+ // session has any linked Solana wallet, 404 otherwise. We tolerate any
+ // non-200 here and fall through to the SIWS path.
+ try {
+ const r = await fetch(
+ `/api/auth/wallets/check?chain_type=solana&address=${encodeURIComponent(this.#address)}`,
+ { credentials: 'include' },
+ );
+ if (r.ok) {
+ const data = await r.json().catch(() => ({}));
+ if (data?.linked) return;
+ }
+ } catch {
+ /* non-fatal — proceed with SIWS */
+ }
+
+ const nonceRes = await fetch('/api/auth/siws/nonce', { credentials: 'include' });
+ if (!nonceRes.ok) throw new Error('Could not start wallet linking: nonce request failed.');
+ const { nonce, csrf } = await nonceRes.json();
+
+ const domain = location.host;
+ const uri = location.origin;
+ const issuedAt = new Date().toISOString();
+ const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();
+ const message = [
+ `${domain} wants you to sign in with your Solana account:`,
+ this.#address,
+ '',
+ 'Link this wallet to deploy your agent on Solana. No fees, no transaction.',
+ '',
+ `URI: ${uri}`,
+ 'Version: 1',
+ `Chain ID: ${cluster}`,
+ `Nonce: ${nonce}`,
+ `Issued At: ${issuedAt}`,
+ `Expiration Time: ${expirationTime}`,
+ ].join('\n');
+
+ const msgBytes = new TextEncoder().encode(message);
+ let sig;
+ try {
+ const out = await this.#provider.signMessage(msgBytes, 'utf8');
+ sig = out.signature;
+ } catch (e) {
+ if (e?.code === 4001 || /reject/i.test(e?.message || '')) {
+ const err = new Error('Wallet linking cancelled.');
+ err.code = 'USER_REJECTED';
+ throw err;
+ }
+ throw e;
+ }
+
+ const verifyRes = await fetch('/api/auth/siws/verify', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },
+ body: JSON.stringify({ message, signature: toBase64(sig) }),
+ });
+ if (!verifyRes.ok) {
+ const data = await verifyRes.json().catch(() => ({}));
+ throw new Error(data.error_description || 'Wallet linking failed.');
+ }
+ }
+}
diff --git a/src/onchain/chain-ref.js b/src/onchain/chain-ref.js
new file mode 100644
index 000000000..381d00fee
--- /dev/null
+++ b/src/onchain/chain-ref.js
@@ -0,0 +1,153 @@
+/**
+ * ChainRef — a single, comparable, serializable reference to "what chain."
+ *
+ * Replaces the dual world of (number EVM chainId) vs (sentinel strings like
+ * 'solana-devnet'). Every onchain helper takes a ChainRef; family-specific
+ * branching happens in adapters, not in the UI.
+ *
+ * Wire format is CAIP-2-shaped. CAIP-2 references for Solana are the
+ * genesis-hash prefix; we use the well-known short prefixes published in the
+ * spec so that the same string round-trips through DBs, URLs, and registries.
+ *
+ * Examples:
+ * 'eip155:1' Ethereum mainnet
+ * 'eip155:8453' Base mainnet
+ * 'eip155:84532' Base Sepolia
+ * 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' Solana mainnet-beta
+ * 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1' Solana devnet
+ */
+
+/** @typedef {{ namespace: 'eip155', chainId: number, family: 'evm' }} EvmChainRef */
+/** @typedef {{ namespace: 'solana', cluster: 'mainnet'|'devnet', family: 'solana' }} SolanaChainRef */
+/** @typedef {EvmChainRef|SolanaChainRef} ChainRef */
+
+// CAIP-2 references for Solana per https://chainagnostic.org/CAIPs/caip-2.
+const SOLANA_REFS = {
+ mainnet: '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ devnet: 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
+};
+const SOLANA_REF_TO_CLUSTER = Object.fromEntries(
+ Object.entries(SOLANA_REFS).map(([k, v]) => [v, k]),
+);
+
+/** @param {number} chainId @returns {EvmChainRef} */
+export function evm(chainId) {
+ if (!Number.isInteger(chainId) || chainId <= 0) {
+ throw new TypeError(`evm(): chainId must be a positive integer, got ${chainId}`);
+ }
+ return { namespace: 'eip155', chainId, family: 'evm' };
+}
+
+/** @param {'mainnet'|'devnet'} cluster @returns {SolanaChainRef} */
+export function solana(cluster) {
+ if (cluster !== 'mainnet' && cluster !== 'devnet') {
+ throw new TypeError(`solana(): cluster must be 'mainnet' or 'devnet', got ${cluster}`);
+ }
+ return { namespace: 'solana', cluster, family: 'solana' };
+}
+
+/** @param {ChainRef} ref @returns {string} CAIP-2 string */
+export function toCaip2(ref) {
+ if (ref.family === 'evm') return `eip155:${ref.chainId}`;
+ if (ref.family === 'solana') return `solana:${SOLANA_REFS[ref.cluster]}`;
+ throw new TypeError(`Unknown ChainRef family: ${ref?.family}`);
+}
+
+/** @param {string} caip2 @returns {ChainRef} */
+export function fromCaip2(caip2) {
+ if (typeof caip2 !== 'string') throw new TypeError('fromCaip2 expects a string');
+ const [ns, ref] = caip2.split(':');
+ if (ns === 'eip155') return evm(Number(ref));
+ if (ns === 'solana') {
+ const cluster = SOLANA_REF_TO_CLUSTER[ref];
+ if (!cluster) throw new Error(`Unknown solana ref: ${ref}`);
+ return solana(cluster);
+ }
+ throw new Error(`Unsupported namespace: ${ns}`);
+}
+
+/** @param {ChainRef} a @param {ChainRef} b */
+export function eqRef(a, b) {
+ if (!a || !b) return false;
+ return toCaip2(a) === toCaip2(b);
+}
+
+/** @param {ChainRef} ref */
+export function familyOf(ref) {
+ return ref.family;
+}
+
+// ── Registry of supported chains for the deploy UI ──────────────────────────
+//
+// This is the source-of-truth list the dropdown reads from. EVM entries point
+// at the legacy CHAIN_META + REGISTRY_DEPLOYMENTS tables for backwards compat;
+// new chains added here automatically appear in the picker.
+
+/**
+ * @typedef {{
+ * ref: ChainRef,
+ * name: string,
+ * shortName: string,
+ * testnet: boolean,
+ * explorerTx: (sigOrHash: string) => string,
+ * explorerAddress: (addr: string) => string,
+ * }} ChainEntry
+ */
+
+const SOLANA_ENTRIES = {
+ mainnet: {
+ ref: solana('mainnet'),
+ name: 'Solana',
+ shortName: 'SOL',
+ testnet: false,
+ explorerTx: (sig) => `https://solscan.io/tx/${sig}`,
+ explorerAddress: (addr) => `https://solscan.io/account/${addr}`,
+ },
+ devnet: {
+ ref: solana('devnet'),
+ name: 'Solana Devnet',
+ shortName: 'SOLdev',
+ testnet: true,
+ explorerTx: (sig) => `https://explorer.solana.com/tx/${sig}?cluster=devnet`,
+ explorerAddress: (addr) => `https://explorer.solana.com/address/${addr}?cluster=devnet`,
+ },
+};
+
+/**
+ * Build the registry by combining EVM chains from the legacy meta table with
+ * the Solana entries above. Pure function — no I/O.
+ *
+ * @param {Record<number, { name: string, shortName: string, explorer: string, testnet: boolean }>} evmMeta
+ * @param {Record<number, unknown>} evmDeployments Used as the gate for EVM inclusion
+ * @returns {ChainEntry[]}
+ */
+export function buildRegistry(evmMeta, evmDeployments) {
+ const entries = [];
+ for (const [idStr, meta] of Object.entries(evmMeta || {})) {
+ const id = Number(idStr);
+ if (!evmDeployments?.[id]) continue;
+ entries.push({
+ ref: evm(id),
+ name: meta.name,
+ shortName: meta.shortName,
+ testnet: !!meta.testnet,
+ explorerTx: (h) => `${meta.explorer}/tx/${h}`,
+ explorerAddress: (a) => `${meta.explorer}/address/${a}`,
+ });
+ }
+ entries.push(SOLANA_ENTRIES.mainnet, SOLANA_ENTRIES.devnet);
+ return entries;
+}
+
+/** @param {ChainEntry[]} reg @returns {{ mainnets: ChainEntry[], testnets: ChainEntry[] }} */
+export function groupRegistry(reg) {
+ const mainnets = [];
+ const testnets = [];
+ for (const e of reg) (e.testnet ? testnets : mainnets).push(e);
+ return { mainnets, testnets };
+}
+
+/** @param {ChainEntry[]} reg @param {string} caip2 */
+export function entryByCaip2(reg, caip2) {
+ return reg.find((e) => toCaip2(e.ref) === caip2) || null;
+}
diff --git a/src/onchain/deploy-button.js b/src/onchain/deploy-button.js
new file mode 100644
index 000000000..40914f9f8
--- /dev/null
+++ b/src/onchain/deploy-button.js
@@ -0,0 +1,213 @@
+/**
+ * OnchainDeployButton — drop-in replacement for src/erc8004/deploy-button.js.
+ *
+ * Differences:
+ * • Reads chain entries from chain-ref.js registry (CAIP-2 keyed) — Solana,
+ * EVM, and any future family share one dropdown without sentinel strings.
+ * • Delegates everything wallet-shaped to the adapter layer.
+ * • Rehydrates the success chip from `agent.onchain` (the unified shape
+ * returned by /api/agents/:id and persisted by the new confirm endpoint),
+ * so a page reload shows the deployed state regardless of family.
+ *
+ * Mounting:
+ * const btn = new OnchainDeployButton({ agent, container });
+ * btn.mount();
+ */
+
+import { CHAIN_META } from '../erc8004/chain-meta.js';
+import { REGISTRY_DEPLOYMENTS } from '../erc8004/abi.js';
+import {
+ buildRegistry,
+ groupRegistry,
+ entryByCaip2,
+ toCaip2,
+ fromCaip2,
+ evm,
+} from './chain-ref.js';
+import { deployAgent } from './deploy.js';
+import { isUserRejection } from './adapters/index.js';
+
+const DEFAULT_REF_CAIP2 = 'eip155:8453'; // Base mainnet
+
+const STEP_LABELS = {
+ connect: 'Connecting wallet',
+ prep: 'Preparing manifest',
+ sign: 'Sign tx',
+ confirm: 'Confirming on-chain',
+ save: 'Saving',
+};
+const STEP_ORDER = ['connect', 'prep', 'sign', 'confirm', 'save'];
+
+function _esc(s) {
+ return String(s ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+export class OnchainDeployButton {
+ /**
+ * @param {object} opts
+ * @param {object} opts.agent
+ * @param {HTMLElement} opts.container
+ * @param {string} [opts.preferredChain] CAIP-2 string. Defaults to Base mainnet.
+ */
+ constructor({ agent, container, preferredChain = DEFAULT_REF_CAIP2 }) {
+ this._agent = agent;
+ this._container = container;
+ this._registry = buildRegistry(CHAIN_META, REGISTRY_DEPLOYMENTS);
+ this._refCaip2 = preferredChain;
+ this._root = null;
+ }
+
+ mount() {
+ this._root = document.createElement('div');
+ this._root.className = 'deploy-button-root';
+ this._container.appendChild(this._root);
+ this._render();
+ }
+
+ unmount() {
+ this._root?.remove();
+ this._root = null;
+ }
+
+ // ── Render ─────────────────────────────────────────────────────────────
+
+ _render() {
+ if (!this._root) return;
+ const onchain = this._agent.onchain;
+ if (onchain?.txHash && onchain?.chain) {
+ const entry = entryByCaip2(this._registry, onchain.chain);
+ if (entry) {
+ this._renderSuccessChip(entry, onchain.txHash, onchain.contractOrMint);
+ return;
+ }
+ }
+ const entry = entryByCaip2(this._registry, this._refCaip2);
+ if (!entry) {
+ this._renderDisabled('Selected chain is not configured');
+ return;
+ }
+ this._renderDeployButton();
+ }
+
+ _renderDeployButton() {
+ const { mainnets, testnets } = groupRegistry(this._registry);
+ const optsHtml = (entries) =>
+ entries
+ .map((e) => {
+ const c = toCaip2(e.ref);
+ return `<option value="${_esc(c)}"${c === this._refCaip2 ? ' selected' : ''}>${_esc(e.name)}</option>`;
+ })
+ .join('');
+
+ this._root.innerHTML = `
+ <div class="deploy-chain-row">
+ <select class="deploy-chain-select" aria-label="Target chain">
+ <optgroup label="Mainnets">${optsHtml(mainnets)}</optgroup>
+ <optgroup label="Testnets">${optsHtml(testnets)}</optgroup>
+ </select>
+ <button class="deploy-btn" title="Deploy this agent on-chain">
+ &#x2B22; Deploy on-chain
+ </button>
+ </div>
+ `;
+ const sel = this._root.querySelector('.deploy-chain-select');
+ sel.addEventListener('change', (ev) => {
+ this._refCaip2 = ev.target.value;
+ });
+ this._root.querySelector('.deploy-btn').addEventListener('click', () => this._start());
+ }
+
+ _renderDisabled(msg) {
+ this._root.innerHTML = `
+ <button class="deploy-btn deploy-btn--disabled" disabled title="${_esc(msg)}">
+ &#x2B22; Deploy on-chain
+ </button>
+ <span class="deploy-tooltip">${_esc(msg)}</span>
+ `;
+ }
+
+ _renderProgress(activeStep) {
+ const idx = STEP_ORDER.indexOf(activeStep);
+ const html = STEP_ORDER.map((s, i) => {
+ const cls = i < idx ? 'done' : i === idx ? 'active' : 'pending';
+ return `<span class="progress-step progress-step--${cls}">${_esc(STEP_LABELS[s])}</span>`;
+ }).join('<span class="progress-sep" aria-hidden="true">&#x2192;</span>');
+ this._root.innerHTML = `
+ <div class="deploy-progress" role="status" aria-live="polite">
+ ${html}
+ </div>
+ `;
+ }
+
+ _renderError(msg, action) {
+ const actionHtml = action
+ ? `<button class="deploy-action-btn">${_esc(action.label)}</button>`
+ : '<button class="deploy-action-btn deploy-action-btn--reset">Try again</button>';
+ this._root.innerHTML = `
+ <div class="deploy-error" role="alert">
+ <span class="deploy-error-msg">${_esc(msg)}</span>
+ ${actionHtml}
+ </div>
+ `;
+ const btn = this._root.querySelector('.deploy-action-btn');
+ btn.addEventListener('click', action ? action.handler : () => this._renderDeployButton());
+ }
+
+ _renderSuccessChip(entry, txHash, contractOrMint) {
+ // Prefer the tx explorer link — it survives across chains and works for
+ // both EVM (tx hash) and Solana (signature).
+ const url = entry.explorerTx(txHash);
+ this._root.innerHTML = `
+ <a class="deploy-chip deploy-chip--success" href="${_esc(url)}" target="_blank" rel="noopener noreferrer"
+ aria-label="View on ${_esc(entry.name)} explorer">
+ &#x2B22; On-chain on ${_esc(entry.name)} &middot; view on explorer
+ </a>
+ `;
+ }
+
+ // ── Drive ──────────────────────────────────────────────────────────────
+
+ async _start() {
+ let ref;
+ try {
+ ref = fromCaip2(this._refCaip2);
+ } catch (e) {
+ this._renderError(`Invalid chain: ${e.message}`);
+ return;
+ }
+
+ try {
+ const result = await deployAgent({
+ agent: this._agent,
+ ref,
+ onProgress: (step) => this._renderProgress(step),
+ });
+ this._agent.onchain = {
+ chain: toCaip2(result.ref),
+ txHash: result.txHash,
+ onchainId: result.onchainId,
+ contractOrMint: result.contractOrMint,
+ };
+ const entry = entryByCaip2(this._registry, this._refCaip2);
+ this._renderSuccessChip(entry, result.txHash, result.contractOrMint);
+ } catch (err) {
+ if (isUserRejection(err)) return this._renderDeployButton();
+ if (err.code === 'NO_PROVIDER') {
+ this._renderError(err.message, {
+ label: 'Install wallet',
+ handler: () => window.open(err.installUrl, '_blank', 'noopener'),
+ });
+ return;
+ }
+ this._renderError(err.message || 'Deploy failed.');
+ }
+ }
+}
+
+// Re-export building blocks for callers that want to compose differently.
+export { evm, fromCaip2, toCaip2 } from './chain-ref.js';
+export { deployAgent } from './deploy.js';
diff --git a/src/onchain/deploy.js b/src/onchain/deploy.js
new file mode 100644
index 000000000..2aa4ffa83
--- /dev/null
+++ b/src/onchain/deploy.js
@@ -0,0 +1,142 @@
+/**
+ * Unified deploy orchestrator.
+ *
+ * Drives the prep → sign → confirm pipeline against the new unified API
+ * (`/api/agents/onchain/prep` + `/api/agents/onchain/confirm`). Family-specific
+ * details (EVM ABI calls, Solana tx submission, SIWS linking) live in the
+ * WalletAdapter. This module owns:
+ *
+ * • Prep idempotency (caches `prepId` per agent + chain so retries don't
+ * re-pin metadata or rebuild a fresh Solana mint keypair).
+ * • Progress callbacks for UI to render step state.
+ * • Error normalization (USER_REJECTED short-circuits cleanly).
+ */
+
+import { getAdapter } from './adapters/index.js';
+import { toCaip2 } from './chain-ref.js';
+
+const PREP_CACHE_TTL_MS = 50 * 60 * 1000; // server keeps prep 60m
+
+function prepCacheKey(agentId, ref) {
+ return `3dagent:onchain-prep:${agentId}:${toCaip2(ref)}`;
+}
+
+async function getOrCreatePrep(agent, ref, walletAddress) {
+ const key = prepCacheKey(agent.id, ref);
+ try {
+ const raw = localStorage.getItem(key);
+ if (raw) {
+ const cached = JSON.parse(raw);
+ if (cached?.prepId && cached?.expiresAt > Date.now()) return cached;
+ }
+ } catch {
+ /* fall through */
+ }
+
+ const body = {
+ agent_id: agent.id,
+ chain: toCaip2(ref),
+ wallet_address: walletAddress,
+ name: agent.name || 'Agent',
+ description: agent.description || '',
+ avatar_id: agent.avatarId || agent.avatar_id || null,
+ skills: Array.isArray(agent.skills) && agent.skills.length ? agent.skills : undefined,
+ };
+ const resp = await fetch('/api/agents/onchain/prep', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ if (!resp.ok) {
+ const data = await resp.json().catch(() => ({}));
+ const err = new Error(data.error_description || `prep returned ${resp.status}`);
+ err.status = resp.status;
+ err.code = data.error;
+ throw err;
+ }
+ const prep = await resp.json();
+ const cached = { ...prep, expiresAt: Date.now() + PREP_CACHE_TTL_MS };
+ try {
+ localStorage.setItem(key, JSON.stringify(cached));
+ } catch {
+ /* quota — fine */
+ }
+ return cached;
+}
+
+function clearPrepCache(agentId, ref) {
+ try {
+ localStorage.removeItem(prepCacheKey(agentId, ref));
+ } catch {
+ /* ignore */
+ }
+}
+
+/**
+ * @param {object} opts
+ * @param {{ id: string, name: string, [k: string]: any }} opts.agent
+ * @param {import('./chain-ref.js').ChainRef} opts.ref
+ * @param {(step: 'connect'|'prep'|'sign'|'confirm'|'save', detail?: object) => void} [opts.onProgress]
+ * @returns {Promise<{ ref: import('./chain-ref.js').ChainRef, txHash: string, onchainId: string|null, contractOrMint: string|null, agent: object }>}
+ */
+export async function deployAgent({ agent, ref, onProgress = () => {} }) {
+ if (!agent?.id) throw new Error('agent.id is required');
+
+ const adapter = getAdapter(ref.family);
+ if (!adapter.isAvailable()) {
+ const err = new Error(`No ${ref.family.toUpperCase()} wallet detected.`);
+ err.code = 'NO_PROVIDER';
+ err.installUrl = adapter.installUrl();
+ throw err;
+ }
+
+ onProgress('connect');
+ const { address, ref: walletRef } = await adapter.connect({
+ ensureLinked: true,
+ cluster: ref.family === 'solana' ? ref.cluster : undefined,
+ });
+
+ if (ref.family === 'evm' && walletRef.family === 'evm' && walletRef.chainId !== ref.chainId) {
+ await adapter.switchTo(ref);
+ }
+
+ onProgress('prep');
+ const prep = await getOrCreatePrep(agent, ref, address);
+
+ onProgress('sign');
+ const sig = await adapter.signAndSend(prep, ref);
+
+ onProgress('confirm');
+ const confirmResp = await fetch('/api/agents/onchain/confirm', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ prep_id: prep.prepId,
+ tx_hash: sig.txHash,
+ onchain_id: sig.onchainId || null,
+ wallet_address: address,
+ }),
+ });
+ if (!confirmResp.ok) {
+ const data = await confirmResp.json().catch(() => ({}));
+ const err = new Error(data.error_description || `confirm returned ${confirmResp.status}`);
+ err.status = confirmResp.status;
+ err.code = data.error;
+ err.txHash = sig.txHash;
+ throw err;
+ }
+ const result = await confirmResp.json();
+
+ onProgress('save');
+ clearPrepCache(agent.id, ref);
+
+ return {
+ ref,
+ txHash: sig.txHash,
+ onchainId: sig.onchainId,
+ contractOrMint: prep.contractAddress || prep.assetPubkey || null,
+ agent: result.agent,
+ };
+}