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.

fix: update sign-in link to use path without file extension

swarmsyyd78dfbd9816e
diff --git a/src/erc8004/agent-registry.js b/src/erc8004/agent-registry.js
index 9ab3786a1..bf11f0d34 100644
--- a/src/erc8004/agent-registry.js
+++ b/src/erc8004/agent-registry.js
@@ -186,10 +186,11 @@ export function getIdentityRegistry(chainId, signer) {
* @param {string} opts.name Agent name
* @param {string} opts.description Agent description
* @param {string} [opts.apiToken] Optional Pinata JWT (omit to use built-in storage)
+ * @param {Array<{name?:string,type?:string,endpoint:string,version?:string}>} [opts.services] Extra services to include in registration JSON
* @param {function} [opts.onStatus] Callback for progress updates
* @returns {Promise<{agentId: number, registrationUrl: string, txHash: string}>}
*/
-export async function registerAgent({ glbFile, name, description, apiToken, onStatus }) {
+export async function registerAgent({ glbFile, name, description, apiToken, services = [], onStatus }) {
const log = onStatus || (() => {});
// 1. Connect wallet
@@ -230,6 +231,7 @@ export async function registerAgent({ glbFile, name, description, apiToken, onSt
agentId,
chainId,
registryAddr: REGISTRY_DEPLOYMENTS[chainId].identityRegistry,
+ services,
});
// 6. Upload registration JSON
diff --git a/src/erc8004/chains.js b/src/erc8004/chains.js
new file mode 100644
index 000000000..71da19c85
--- /dev/null
+++ b/src/erc8004/chains.js
@@ -0,0 +1,144 @@
+/**
+ * Chain metadata for the ERC-8004 creator UI.
+ *
+ * Only chains that appear in REGISTRY_DEPLOYMENTS should be listed here.
+ * Default: BSC Testnet (chainId 97) — cheapest to experiment on.
+ */
+
+import { REGISTRY_DEPLOYMENTS } from './abi.js';
+
+/**
+ * @typedef {Object} ChainInfo
+ * @property {number} chainId
+ * @property {string} name Display name shown in the selector.
+ * @property {string} short Short label (e.g. "BSC", "Base").
+ * @property {string} symbol Native token symbol.
+ * @property {string} explorer Block explorer base URL (no trailing slash).
+ * @property {string} rpc Public RPC URL (used for read-only calls).
+ * @property {'mainnet'|'testnet'} kind
+ */
+
+/** @type {Record<number, ChainInfo>} */
+export const CHAIN_INFO = {
+ // ── Mainnets ──────────────────────────────────────────────────────────
+ 1: { chainId: 1, name: 'Ethereum', short: 'ETH', symbol: 'ETH', explorer: 'https://etherscan.io', rpc: 'https://eth.llamarpc.com', kind: 'mainnet' },
+ 10: { chainId: 10, name: 'Optimism', short: 'OP', symbol: 'ETH', explorer: 'https://optimistic.etherscan.io', rpc: 'https://mainnet.optimism.io', kind: 'mainnet' },
+ 56: { chainId: 56, name: 'BNB Chain', short: 'BSC', symbol: 'BNB', explorer: 'https://bscscan.com', rpc: 'https://bsc-dataseed.bnbchain.org', kind: 'mainnet' },
+ 100: { chainId: 100, name: 'Gnosis', short: 'GNO', symbol: 'xDAI', explorer: 'https://gnosisscan.io', rpc: 'https://rpc.gnosischain.com', kind: 'mainnet' },
+ 137: { chainId: 137, name: 'Polygon', short: 'MATIC', symbol: 'POL', explorer: 'https://polygonscan.com', rpc: 'https://polygon-rpc.com', kind: 'mainnet' },
+ 250: { chainId: 250, name: 'Fantom', short: 'FTM', symbol: 'FTM', explorer: 'https://ftmscan.com', rpc: 'https://rpc.ftm.tools', kind: 'mainnet' },
+ 324: { chainId: 324, name: 'zkSync Era', short: 'zkSync', symbol: 'ETH', explorer: 'https://explorer.zksync.io', rpc: 'https://mainnet.era.zksync.io', kind: 'mainnet' },
+ 1284: { chainId: 1284, name: 'Moonbeam', short: 'GLMR', symbol: 'GLMR', explorer: 'https://moonscan.io', rpc: 'https://rpc.api.moonbeam.network', kind: 'mainnet' },
+ 5000: { chainId: 5000, name: 'Mantle', short: 'MNT', symbol: 'MNT', explorer: 'https://explorer.mantle.xyz', rpc: 'https://rpc.mantle.xyz', kind: 'mainnet' },
+ 8453: { chainId: 8453, name: 'Base', short: 'BASE', symbol: 'ETH', explorer: 'https://basescan.org', rpc: 'https://mainnet.base.org', kind: 'mainnet' },
+ 42161: { chainId: 42161, name: 'Arbitrum One', short: 'ARB', symbol: 'ETH', explorer: 'https://arbiscan.io', rpc: 'https://arb1.arbitrum.io/rpc', kind: 'mainnet' },
+ 42220: { chainId: 42220, name: 'Celo', short: 'CELO', symbol: 'CELO', explorer: 'https://celoscan.io', rpc: 'https://forno.celo.org', kind: 'mainnet' },
+ 43114: { chainId: 43114, name: 'Avalanche', short: 'AVAX', symbol: 'AVAX', explorer: 'https://snowtrace.io', rpc: 'https://api.avax.network/ext/bc/C/rpc', kind: 'mainnet' },
+ 59144: { chainId: 59144, name: 'Linea', short: 'LINEA', symbol: 'ETH', explorer: 'https://lineascan.build', rpc: 'https://rpc.linea.build', kind: 'mainnet' },
+ 534352: { chainId: 534352, name: 'Scroll', short: 'SCR', symbol: 'ETH', explorer: 'https://scrollscan.com', rpc: 'https://rpc.scroll.io', kind: 'mainnet' },
+
+ // ── Testnets ──────────────────────────────────────────────────────────
+ 97: { chainId: 97, name: 'BSC Testnet', short: 'tBSC', symbol: 'tBNB', explorer: 'https://testnet.bscscan.com', rpc: 'https://data-seed-prebsc-1-s1.bnbchain.org:8545', kind: 'testnet' },
+ 11155111: { chainId: 11155111, name: 'Ethereum Sepolia', short: 'SEP', symbol: 'ETH', explorer: 'https://sepolia.etherscan.io', rpc: 'https://rpc.sepolia.org', kind: 'testnet' },
+ 84532: { chainId: 84532, name: 'Base Sepolia', short: 'baseSep', symbol: 'ETH', explorer: 'https://sepolia.basescan.org', rpc: 'https://sepolia.base.org', kind: 'testnet' },
+ 421614: { chainId: 421614, name: 'Arbitrum Sepolia', short: 'arbSep', symbol: 'ETH', explorer: 'https://sepolia.arbiscan.io', rpc: 'https://sepolia-rollup.arbitrum.io/rpc', kind: 'testnet' },
+ 11155420: { chainId: 11155420, name: 'Optimism Sepolia', short: 'opSep', symbol: 'ETH', explorer: 'https://sepolia-optimism.etherscan.io', rpc: 'https://sepolia.optimism.io', kind: 'testnet' },
+ 80002: { chainId: 80002, name: 'Polygon Amoy', short: 'Amoy', symbol: 'POL', explorer: 'https://amoy.polygonscan.com', rpc: 'https://rpc-amoy.polygon.technology', kind: 'testnet' },
+ 43113: { chainId: 43113, name: 'Avalanche Fuji', short: 'Fuji', symbol: 'AVAX', explorer: 'https://testnet.snowtrace.io', rpc: 'https://api.avax-test.network/ext/bc/C/rpc', kind: 'testnet' },
+};
+
+/** Default chain presented to new users. */
+export const DEFAULT_CHAIN_ID = 97; // BSC Testnet
+
+/**
+ * @param {number} chainId
+ * @returns {ChainInfo|null}
+ */
+export function getChainInfo(chainId) {
+ return CHAIN_INFO[chainId] || null;
+}
+
+/**
+ * Chains grouped as [mainnets, testnets], in the order users see them in the
+ * selector. Only chains with an ERC-8004 deployment are returned.
+ * @returns {{mainnets: ChainInfo[], testnets: ChainInfo[]}}
+ */
+export function supportedChainsGrouped() {
+ const mainnets = [];
+ const testnets = [];
+ for (const [id, info] of Object.entries(CHAIN_INFO)) {
+ const chainId = Number(id);
+ if (!REGISTRY_DEPLOYMENTS[chainId]?.identityRegistry) continue;
+ (info.kind === 'mainnet' ? mainnets : testnets).push(info);
+ }
+ mainnets.sort((a, b) => a.name.localeCompare(b.name));
+ testnets.sort((a, b) => a.name.localeCompare(b.name));
+ return { mainnets, testnets };
+}
+
+/**
+ * Convert a chainId to the 0x-prefixed hex form required by
+ * wallet_switchEthereumChain / wallet_addEthereumChain.
+ * @param {number} chainId
+ * @returns {string}
+ */
+export function toHexChainId(chainId) {
+ return '0x' + Number(chainId).toString(16);
+}
+
+/**
+ * Ask the connected wallet to switch chains, adding the chain definition if
+ * the wallet hasn't seen it before.
+ *
+ * Throws if the user rejects or no wallet is present.
+ * @param {number} chainId
+ */
+export async function requestSwitchChain(chainId) {
+ if (!window.ethereum?.request) {
+ throw new Error('No wallet available to switch chains.');
+ }
+ const info = getChainInfo(chainId);
+ if (!info) throw new Error(`Unknown chain: ${chainId}`);
+
+ const hex = toHexChainId(chainId);
+ try {
+ await window.ethereum.request({
+ method: 'wallet_switchEthereumChain',
+ params: [{ chainId: hex }],
+ });
+ } catch (err) {
+ // 4902 = chain not added to the wallet yet.
+ if (err?.code === 4902 || /unrecognized chain/i.test(err?.message || '')) {
+ await window.ethereum.request({
+ method: 'wallet_addEthereumChain',
+ params: [{
+ chainId: hex,
+ chainName: info.name,
+ nativeCurrency: { name: info.symbol, symbol: info.symbol, decimals: 18 },
+ rpcUrls: [info.rpc],
+ blockExplorerUrls: [info.explorer],
+ }],
+ });
+ } else {
+ throw err;
+ }
+ }
+}
+
+/**
+ * Build an explorer URL for a tx / address / token given a chainId.
+ * @param {number} chainId
+ * @param {'tx'|'address'|'token'} kind
+ * @param {string|number} value
+ * @returns {string}
+ */
+export function explorerUrl(chainId, kind, value) {
+ const info = getChainInfo(chainId);
+ if (!info) return '';
+ switch (kind) {
+ case 'tx': return `${info.explorer}/tx/${value}`;
+ case 'address': return `${info.explorer}/address/${value}`;
+ case 'token': return `${info.explorer}/token/${value}`;
+ default: return info.explorer;
+ }
+}
diff --git a/src/erc8004/enumeration.js b/src/erc8004/enumeration.js
new file mode 100644
index 000000000..a1593be7a
--- /dev/null
+++ b/src/erc8004/enumeration.js
@@ -0,0 +1,167 @@
+/**
+ * Agent enumeration & metadata fetching.
+ *
+ * Strategy, in priority order:
+ * 1. ERC-721 Enumerable: balanceOf + tokenOfOwnerByIndex (fast, one call per id)
+ * 2. Event scan: query Transfer(to = owner) filter on the registry (slow on
+ * chains with many blocks; keep a bounded `fromBlock` when provided)
+ *
+ * Metadata resolution fetches `tokenURI(id)` and follows ipfs://, ar://, https://.
+ */
+
+import { getIdentityRegistry } from './agent-registry.js';
+
+const IPFS_GATEWAYS = [
+ (cid) => `https://ipfs.io/ipfs/${cid}`,
+ (cid) => `https://cloudflare-ipfs.com/ipfs/${cid}`,
+ (cid) => `https://dweb.link/ipfs/${cid}`,
+];
+
+/**
+ * Resolve an ipfs://, ar://, or https:// URI to an HTTP URL.
+ * Returns the first gateway for ipfs — caller may retry others via `ipfsFallbackUrls`.
+ * @param {string} uri
+ * @returns {string}
+ */
+export function uriToHttp(uri) {
+ if (!uri) return '';
+ if (uri.startsWith('ipfs://')) return IPFS_GATEWAYS[0](uri.slice(7));
+ if (uri.startsWith('ar://')) return `https://arweave.net/${uri.slice(5)}`;
+ return uri;
+}
+
+/**
+ * Full list of fallback HTTP URLs for an IPFS URI (for retries).
+ * @param {string} uri
+ * @returns {string[]}
+ */
+export function ipfsFallbackUrls(uri) {
+ if (!uri?.startsWith('ipfs://')) return [uri];
+ const cid = uri.slice(7);
+ return IPFS_GATEWAYS.map((fn) => fn(cid));
+}
+
+/**
+ * Enumerate token IDs owned by `address` on the given registry.
+ *
+ * @param {import('ethers').Contract} registry
+ * @param {string} address
+ * @param {{ fromBlock?: number, onStatus?: (msg: string) => void }} [opts]
+ * @returns {Promise<{tokenIds: number[], balance: number, strategy: 'enumerable'|'event-scan'|'empty'}>}
+ */
+export async function getAgentsByOwner(registry, address, opts = {}) {
+ const log = opts.onStatus || (() => {});
+
+ log('Reading balance…');
+ const balance = Number(await registry.balanceOf(address));
+ if (balance === 0) return { tokenIds: [], balance: 0, strategy: 'empty' };
+
+ // Try ERC-721 Enumerable first.
+ try {
+ const tokenIds = [];
+ for (let i = 0; i < balance; i++) {
+ tokenIds.push(Number(await registry.tokenOfOwnerByIndex(address, i)));
+ }
+ return { tokenIds, balance, strategy: 'enumerable' };
+ } catch {
+ // Fall through to event scan.
+ }
+
+ log('Scanning Transfer events…');
+ const filter = registry.filters.Transfer(null, address);
+ const events = opts.fromBlock
+ ? await registry.queryFilter(filter, opts.fromBlock)
+ : await registry.queryFilter(filter);
+
+ const seen = new Set();
+ const tokenIds = [];
+ for (const e of events) {
+ const id = Number(e.args.tokenId);
+ if (seen.has(id)) continue;
+ seen.add(id);
+ try {
+ const currentOwner = await registry.ownerOf(id);
+ if (currentOwner.toLowerCase() === address.toLowerCase()) tokenIds.push(id);
+ } catch { /* burned — skip */ }
+ }
+ return { tokenIds, balance, strategy: 'event-scan' };
+}
+
+/**
+ * Fetch `tokenURI(id)` and its resolved JSON (if reachable).
+ *
+ * @param {import('ethers').Contract} registry
+ * @param {number} tokenId
+ * @returns {Promise<{id: number, uri: string, meta: object|null, owner: string|null}>}
+ */
+export async function fetchTokenMeta(registry, tokenId) {
+ let uri = '';
+ let meta = null;
+ let owner = null;
+
+ try { uri = await registry.tokenURI(tokenId); } catch { /* no URI set */ }
+ try { owner = await registry.ownerOf(tokenId); } catch { /* burned */ }
+
+ if (uri) {
+ const urls = ipfsFallbackUrls(uri);
+ for (const u of urls) {
+ try {
+ const r = await fetch(u, { signal: AbortSignal.timeout(6000) });
+ const ct = r.headers.get('content-type') || '';
+ if (r.ok && ct.includes('json')) {
+ meta = await r.json();
+ break;
+ }
+ } catch { /* try next gateway */ }
+ }
+ }
+ return { id: tokenId, uri, meta, owner };
+}
+
+/**
+ * Scan past `Registered` events for a given owner — powers the History tab.
+ *
+ * @param {import('ethers').Contract} registry
+ * @param {string} ownerAddress
+ * @param {{ fromBlock?: number, limit?: number }} [opts]
+ * @returns {Promise<Array<{agentId: number, agentURI: string, txHash: string, blockNumber: number, blockHash: string}>>}
+ */
+export async function getRegistrationHistory(registry, ownerAddress, opts = {}) {
+ const limit = opts.limit ?? 50;
+ const filter = registry.filters.Registered(null, null, ownerAddress);
+ const events = opts.fromBlock
+ ? await registry.queryFilter(filter, opts.fromBlock)
+ : await registry.queryFilter(filter);
+
+ return events
+ .map((e) => ({
+ agentId: Number(e.args.agentId),
+ agentURI: String(e.args.agentURI || ''),
+ txHash: e.transactionHash,
+ blockNumber: Number(e.blockNumber),
+ blockHash: e.blockHash,
+ }))
+ .sort((a, b) => b.blockNumber - a.blockNumber)
+ .slice(0, limit);
+}
+
+/**
+ * Read-only registry connect — uses a public RPC when no signer is available.
+ * Used by the Search tab when a user hasn't connected a wallet yet.
+ *
+ * @param {number} chainId
+ * @param {string} rpcUrl
+ * @returns {Promise<import('ethers').Contract>}
+ */
+export async function getReadOnlyRegistry(chainId, rpcUrl) {
+ const { JsonRpcProvider, Contract } = await import('ethers');
+ const { REGISTRY_DEPLOYMENTS, IDENTITY_REGISTRY_ABI } = await import('./abi.js');
+ const deployment = REGISTRY_DEPLOYMENTS[chainId];
+ if (!deployment?.identityRegistry) {
+ throw new Error(`No registry for chain ${chainId}`);
+ }
+ const provider = new JsonRpcProvider(rpcUrl);
+ return new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, provider);
+}
+
+export { getIdentityRegistry };
diff --git a/src/erc8004/privy.js b/src/erc8004/privy.js
index 26940d9a8..ff161461b 100644
--- a/src/erc8004/privy.js
+++ b/src/erc8004/privy.js
@@ -136,9 +136,26 @@ export async function connectWithPrivy() {
// Helpers
// ---------------------------------------------------------------------------
-/** @returns {boolean} Whether a Privy app ID is configured. */
+/**
+ * Whether a Privy app ID is configured.
+ *
+ * Synchronous best-guess from the build-time value + any runtime value resolved
+ * so far. For an accurate runtime answer (forces /api/config fetch on first
+ * call) use `isPrivyConfiguredAsync`.
+ *
+ * @returns {boolean}
+ */
export function isPrivyConfigured() {
- return Boolean(APP_ID);
+ if (_resolvedAppId !== null) return Boolean(_resolvedAppId);
+ return Boolean(BUILD_APP_ID);
+}
+
+/**
+ * Runtime check that resolves the app ID (build-time or /api/config).
+ * @returns {Promise<boolean>}
+ */
+export async function isPrivyConfiguredAsync() {
+ return Boolean(await resolveAppId());
}
/** @returns {object|null} The Privy client instance (null if not initialized). */
diff --git a/src/erc8004/queries.js b/src/erc8004/queries.js
new file mode 100644
index 000000000..30d5faabf
--- /dev/null
+++ b/src/erc8004/queries.js
@@ -0,0 +1,211 @@
+/**
+ * Read-only queries against the Identity Registry.
+ *
+ * Used by the tabbed registration UI (My Agents / Search / History).
+ *
+ * All queries use a read-only provider (wallet provider preferred; public RPC
+ * fallback from CHAIN_META). We deliberately avoid backend state for these —
+ * the chain is the source of truth.
+ */
+
+import { BrowserProvider, Contract, JsonRpcProvider } from 'ethers';
+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './abi.js';
+import { CHAIN_META } from './chain-meta.js';
+
+/**
+ * Return a read-only ethers provider. Uses the connected wallet provider if
+ * `ethProvider` is given, else falls back to the public RPC from CHAIN_META.
+ *
+ * @param {number} chainId
+ * @param {any} [ethProvider] EIP-1193 provider (window.ethereum / Privy)
+ */
+export function getReadProvider(chainId, ethProvider) {
+ if (ethProvider) return new BrowserProvider(ethProvider);
+ const meta = CHAIN_META[chainId];
+ if (!meta) throw new Error(`No RPC configured for chainId ${chainId}`);
+ return new JsonRpcProvider(meta.rpcUrl, chainId);
+}
+
+/** @param {number} chainId @param {any} [ethProvider] */
+export function getReadRegistry(chainId, ethProvider) {
+ const deployment = REGISTRY_DEPLOYMENTS[chainId];
+ if (!deployment || !deployment.identityRegistry) {
+ throw new Error(`No Identity Registry for chainId ${chainId}`);
+ }
+ const provider = getReadProvider(chainId, ethProvider);
+ return new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, provider);
+}
+
+/**
+ * Verify the registry's on-chain version. Non-throwing — returns null on error.
+ * @param {number} chainId @param {any} [ethProvider]
+ * @returns {Promise<string|null>}
+ */
+export async function getRegistryVersion(chainId, ethProvider) {
+ try {
+ const registry = getReadRegistry(chainId, ethProvider);
+ return await registry.getVersion();
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * @param {number} chainId @param {any} [ethProvider]
+ * @returns {Promise<bigint>}
+ */
+export async function getTotalSupply(chainId, ethProvider) {
+ const registry = getReadRegistry(chainId, ethProvider);
+ return await registry.totalSupply();
+}
+
+/**
+ * List agent IDs owned by `address`. Strategy:
+ *
+ * 1. Try ERC-721 Enumerable: balanceOf → tokenOfOwnerByIndex.
+ * 2. If that reverts, fall back to a Registered-event scan over the last
+ * `eventScanBlocks` blocks (default 500k ~= 1 week on 12s chains, cheap
+ * on most public RPCs), filtered by owner topic.
+ * 3. If neither path yields full detail, return `{ ids: [...], partial: true }`
+ * so the UI can render the count + a "check explorer" fallback.
+ *
+ * @param {object} opts
+ * @param {number} opts.chainId
+ * @param {string} opts.owner
+ * @param {any} [opts.ethProvider]
+ * @param {number} [opts.eventScanBlocks]
+ * @returns {Promise<{ ids: bigint[], count: number, partial: boolean, mode: 'enumerable'|'events'|'count-only' }>}
+ */
+export async function listAgentsByOwner({ chainId, owner, ethProvider, eventScanBlocks = 500000 }) {
+ const registry = getReadRegistry(chainId, ethProvider);
+ const balance = await registry.balanceOf(owner);
+ const count = Number(balance);
+ if (count === 0) return { ids: [], count: 0, partial: false, mode: 'enumerable' };
+
+ // 1. Enumerable path
+ try {
+ const ids = [];
+ for (let i = 0; i < count; i++) {
+ const id = await registry.tokenOfOwnerByIndex(owner, i);
+ ids.push(id);
+ }
+ return { ids, count, partial: false, mode: 'enumerable' };
+ } catch { /* fall through */ }
+
+ // 2. Event-scan fallback
+ try {
+ const provider = registry.runner.provider || registry.runner;
+ const latest = await provider.getBlockNumber();
+ const fromBlock = Math.max(0, latest - eventScanBlocks);
+ const filter = registry.filters.Registered(null, null, owner);
+ const events = await registry.queryFilter(filter, fromBlock, latest);
+ const idsFromEvents = [];
+ for (const ev of events) {
+ const id = ev.args?.agentId;
+ if (id === undefined) continue;
+ // Confirm still owned (transfers could have moved it)
+ try {
+ const currentOwner = await registry.ownerOf(id);
+ if (currentOwner.toLowerCase() === owner.toLowerCase()) idsFromEvents.push(id);
+ } catch { /* ignore burned/missing */ }
+ }
+ return {
+ ids: idsFromEvents,
+ count,
+ partial: idsFromEvents.length < count,
+ mode: 'events',
+ };
+ } catch { /* fall through */ }
+
+ // 3. Count-only
+ return { ids: [], count, partial: true, mode: 'count-only' };
+}
+
+/**
+ * Fetch recent Registered events for display in the History tab.
+ * Optionally filter to a specific owner.
+ *
+ * @param {object} opts
+ * @param {number} opts.chainId
+ * @param {string} [opts.owner]
+ * @param {any} [opts.ethProvider]
+ * @param {number} [opts.blocks] Scan depth (default 500k)
+ * @param {number} [opts.limit] Max events returned (newest first)
+ * @returns {Promise<Array<{ agentId: bigint, agentURI: string, owner: string, blockNumber: number, txHash: string }>>}
+ */
+export async function listRegisteredEvents({ chainId, owner, ethProvider, blocks = 500000, limit = 100 }) {
+ const registry = getReadRegistry(chainId, ethProvider);
+ const provider = registry.runner.provider || registry.runner;
+ const latest = await provider.getBlockNumber();
+ const fromBlock = Math.max(0, latest - blocks);
+ const filter = owner
+ ? registry.filters.Registered(null, null, owner)
+ : registry.filters.Registered();
+ const events = await registry.queryFilter(filter, fromBlock, latest);
+
+ const out = events
+ .slice()
+ .reverse()
+ .slice(0, limit)
+ .map((ev) => ({
+ agentId: ev.args.agentId,
+ agentURI: ev.args.agentURI,
+ owner: ev.args.owner,
+ blockNumber: ev.blockNumber,
+ txHash: ev.transactionHash,
+ }));
+ return out;
+}
+
+/**
+ * Fetch on-chain detail for a single agent: owner + tokenURI.
+ * Does NOT fetch the off-chain metadata JSON — callers do that via fetchAgentMetadata.
+ *
+ * @param {object} opts
+ * @param {number} opts.chainId
+ * @param {bigint|number|string} opts.agentId
+ * @param {any} [opts.ethProvider]
+ */
+export async function getAgentOnchain({ chainId, agentId, ethProvider }) {
+ const registry = getReadRegistry(chainId, ethProvider);
+ const [owner, uri] = await Promise.all([
+ registry.ownerOf(agentId).catch(() => null),
+ registry.tokenURI(agentId).catch(() => null),
+ ]);
+ return { agentId: BigInt(agentId), owner, uri };
+}
+
+/**
+ * Resolve any IPFS/Arweave/data/https URI to a fetchable URL and parse JSON.
+ *
+ * @param {string} uri
+ * @returns {Promise<{ ok: boolean, data?: any, error?: string, resolvedUrl?: string }>}
+ */
+export async function fetchAgentMetadata(uri) {
+ if (!uri) return { ok: false, error: 'empty uri' };
+
+ // data:application/json;base64,... (inline)
+ if (uri.startsWith('data:')) {
+ try {
+ const match = uri.match(/^data:application\/json(?:;base64)?,(.*)$/);
+ if (!match) return { ok: false, error: 'unsupported data URI' };
+ const payload = /;base64,/.test(uri) ? atob(match[1]) : decodeURIComponent(match[1]);
+ return { ok: true, data: JSON.parse(payload), resolvedUrl: uri };
+ } catch (err) {
+ return { ok: false, error: 'data URI parse failed: ' + err.message };
+ }
+ }
+
+ let url = uri;
+ if (uri.startsWith('ipfs://')) url = 'https://ipfs.io/ipfs/' + uri.slice(7);
+ else if (uri.startsWith('ar://')) url = 'https://arweave.net/' + uri.slice(5);
+
+ try {
+ const res = await fetch(url);
+ if (!res.ok) return { ok: false, error: `HTTP ${res.status}`, resolvedUrl: url };
+ const data = await res.json();
+ return { ok: true, data, resolvedUrl: url };
+ } catch (err) {
+ return { ok: false, error: err.message, resolvedUrl: url };
+ }
+}
diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.js
index 0792b9395..1212d46a2 100644
--- a/src/erc8004/register-ui.js
+++ b/src/erc8004/register-ui.js
@@ -1,210 +1,858 @@
/**
- * ERC-8004 Agent Registration UI.
+ * ERC-8004 registration UI.
*
- * Renders the registration form and drives the registerAgent() flow.
- * Uses plain DOM (consistent with the rest of the project).
+ * Tabbed interface for creating, listing, searching, and auditing ERC-8004
+ * agents. Inspired by erc8004.agency but extended with GLB uploads and 3D
+ * viewer links specific to 3D-Agent.
+ *
+ * Tabs:
+ * - Create Agent (4-step wizard: Identity → Services → Configuration → Deploy)
+ * - My Agents (owned-by-wallet, current chain)
+ * - Search (by Agent ID)
+ * - Templates (pre-fills Create Agent)
+ * - History (Registered events for the connected wallet)
+ *
+ * Uses plain DOM — consistent with the rest of the project.
*/
-import { registerAgent, connectWallet, pinFile } from './agent-registry.js';
+import { registerAgent, connectWallet, pinFile, getIdentityRegistry, buildRegistrationJSON } from './agent-registry.js';
import { isPrivyConfigured } from './privy.js';
+import { REGISTRY_DEPLOYMENTS } from './abi.js';
+import {
+ CHAIN_META,
+ DEFAULT_CHAIN_ID,
+ switchChain,
+ addressExplorerUrl,
+ tokenExplorerUrl,
+ txExplorerUrl,
+ supportedChainIds,
+} from './chain-meta.js';
+import {
+ getReadRegistry,
+ listAgentsByOwner,
+ listRegisteredEvents,
+ getAgentOnchain,
+ fetchAgentMetadata,
+ getRegistryVersion,
+ getTotalSupply,
+} from './queries.js';
+
+// ───────────────────────────────────────────────────────────────────────────
+// Templates (for the Templates tab → prefills Create)
+// ───────────────────────────────────────────────────────────────────────────
+
+const TEMPLATES = [
+ { id: 'defi', emoji: '📈', name: 'DeFi Trading Agent', description: 'Automated DeFi yield optimization, liquidity management, and token swaps across protocols.' },
+ { id: 'support', emoji: '🎧', name: 'Customer Support Bot', description: 'AI-powered support agent for handling tickets, FAQ queries, and multi-language communication.' },
+ { id: 'code', emoji: '🔍', name: 'Code Review Agent', description: 'Automated code analysis, security auditing, gas optimization, and best practice enforcement.' },
+ { id: 'data', emoji: '📊', name: 'Data Analysis Agent', description: 'On-chain and off-chain data analysis, reporting, visualization, and pattern recognition.' },
+ { id: 'content', emoji: '✍️', name: 'Content Creator', description: 'AI content generation for social media, documentation, technical writing, and marketing.' },
+ { id: 'research',emoji: '🔬', name: 'Research Assistant', description: 'Deep research on protocols, tokens, governance proposals, and market trends.' },
+];
+
+const SERVICE_TYPES = ['A2A', 'MCP', 'OASF', 'x402', 'web', 'custom'];
+
+// ───────────────────────────────────────────────────────────────────────────
+// Helpers
+// ───────────────────────────────────────────────────────────────────────────
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => (
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
+));
+const shortAddr = (a) => a ? a.slice(0, 6) + '…' + a.slice(-4) : '';
+
+// ───────────────────────────────────────────────────────────────────────────
+// RegisterUI
+// ───────────────────────────────────────────────────────────────────────────
export class RegisterUI {
/**
- * @param {HTMLElement} containerEl Parent element to mount into.
- * @param {function} [onRegistered] Callback after successful registration.
+ * @param {HTMLElement} containerEl
+ * @param {(result: { agentId: number, txHash: string, chainId: number }) => void} [onRegistered]
*/
constructor(containerEl, onRegistered) {
this.container = containerEl;
this.onRegistered = onRegistered || (() => {});
- this.walletAddress = null;
- this.selectedFile = null;
+
+ // Wallet state
+ this.wallet = null; // { address, chainId }
+
+ // Selected chain for reads + writes. Initialized to BSC Testnet; if the
+ // wallet is already on a different supported chain, we'll adopt that.
+ this.selectedChainId = DEFAULT_CHAIN_ID;
+
+ // Tab state
+ this.activeTab = 'create';
+
+ // Wizard state
+ this.wizardStep = 1;
+ this.form = {
+ name: '',
+ description: '',
+ imageUrl: '',
+ glbFile: null,
+ services: [], // [{ name, type, endpoint }]
+ apiToken: '', // optional Pinata JWT
+ };
+
+ // Cache of signed-in user's backend agent id (if any) — linked after deploy
+ this._backendAgentId = null;
this._build();
this._bind();
+ this._fetchBackendAgent(); // fire & forget
}
// -----------------------------------------------------------------------
- // DOM
+ // Top-level DOM
// -----------------------------------------------------------------------
_build() {
this.el = document.createElement('div');
this.el.className = 'erc8004-register';
this.el.innerHTML = `
- <div class="erc8004-card">
- <h2 class="erc8004-title">Register 3D Agent</h2>
- <p class="erc8004-subtitle">Mint your avatar as an ERC-8004 on-chain agent</p>
-
- <!-- Step 1: Connect wallet -->
- <div class="erc8004-section" data-step="wallet">
- <button class="erc8004-btn erc8004-btn--connect" type="button">
- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="1" y="4" width="22" height="16" rx="2"/><path d="M1 10h22"/></svg>
- ${isPrivyConfigured() ? 'Connect Wallet' : 'Connect Wallet'}
- </button>
- <p class="erc8004-wallet-hint">${isPrivyConfigured() ? 'MetaMask, WalletConnect, Coinbase, or email' : 'Requires MetaMask or compatible wallet'}</p>
- <span class="erc8004-wallet-addr"></span>
+ <div class="erc8004-card erc8004-card--wide">
+ <div class="erc8004-header">
+ <div class="erc8004-brand">
+ <span class="erc8004-brand-badge">8004</span>
+ <span class="erc8004-brand-title"><b>ERC-8004</b> Agent Studio</span>
+ </div>
+ <div class="erc8004-controls">
+ <select class="erc8004-chain-select" title="Target chain"></select>
+ <button class="erc8004-btn erc8004-btn--wallet" type="button">
+ ${isPrivyConfigured() ? 'Connect Wallet' : 'Connect MetaMask'}
+ </button>
+ <button class="erc8004-btn erc8004-btn--close" type="button" title="Close">✕</button>
+ </div>
</div>
- <!-- Step 2: Agent details -->
- <div class="erc8004-section" data-step="details">
- <label class="erc8004-label">
- Agent Name
- <input type="text" class="erc8004-input" name="agentName" placeholder="e.g. Alpha-Agent-01" maxlength="64" required />
- </label>
-
- <label class="erc8004-label">
- Description
- <textarea class="erc8004-input erc8004-textarea" name="agentDesc" placeholder="What does this agent do?" maxlength="500" rows="3"></textarea>
- </label>
-
- <label class="erc8004-label">
- 3D Avatar (GLB)
- <div class="erc8004-file-drop" id="erc8004-file-drop">
- <input type="file" accept=".glb,.gltf" class="erc8004-file-input" />
- <span class="erc8004-file-text">Drop .glb file or click to browse</span>
- </div>
- </label>
-
+ <div class="erc8004-stats">
+ <div class="erc8004-stat"><div class="erc8004-stat-val" data-stat="total">—</div><div class="erc8004-stat-lbl">Agents Registered</div></div>
+ <div class="erc8004-stat"><div class="erc8004-stat-val" data-stat="chains">${supportedChainIds().length}</div><div class="erc8004-stat-lbl">Chains Supported</div></div>
+ <div class="erc8004-stat"><div class="erc8004-stat-val" data-stat="version">—</div><div class="erc8004-stat-lbl">Registry Version</div></div>
</div>
- <!-- Step 3: Register -->
- <div class="erc8004-section" data-step="submit">
- <button class="erc8004-btn erc8004-btn--register" type="button" disabled>
- Register Agent On-Chain
- </button>
- </div>
+ <nav class="erc8004-tabs" role="tablist">
+ <button class="erc8004-tab erc8004-tab--active" data-tab="create">Create Agent</button>
+ <button class="erc8004-tab" data-tab="my">My Agents</button>
+ <button class="erc8004-tab" data-tab="search">Search</button>
+ <button class="erc8004-tab" data-tab="templates">Templates</button>
+ <button class="erc8004-tab" data-tab="history">History</button>
+ </nav>
- <!-- Status log -->
- <div class="erc8004-log"></div>
-
- <!-- Result -->
- <div class="erc8004-result" style="display:none">
- <div class="erc8004-result-inner">
- <span class="erc8004-checkmark">&#10003;</span>
- <h3>Agent Registered!</h3>
- <dl class="erc8004-result-dl">
- <dt>Agent ID</dt> <dd class="erc8004-res-id"></dd>
- <dt>Metadata</dt> <dd class="erc8004-res-cid"></dd>
- <dt>Tx Hash</dt> <dd class="erc8004-res-tx"></dd>
- </dl>
- <button class="erc8004-btn erc8004-btn--view" type="button">View in 3D</button>
- </div>
- </div>
+ <div class="erc8004-tab-body" data-role="tab-body"></div>
</div>
`;
this.container.appendChild(this.el);
+
+ this._populateChainSelect();
+ this._renderActiveTab();
+ this._refreshStats();
}
_bind() {
- const $ = (sel) => this.el.querySelector(sel);
+ this.el.querySelector('.erc8004-btn--wallet').addEventListener('click', () => this._connectWallet());
+ this.el.querySelector('.erc8004-btn--close').addEventListener('click', () => this.destroy());
- // Connect wallet
- $('.erc8004-btn--connect').addEventListener('click', async () => {
- try {
- const { address, chainId } = await connectWallet();
- this.walletAddress = address;
- $('.erc8004-wallet-addr').textContent =
- address.slice(0, 6) + '...' + address.slice(-4) + ` (chain ${chainId})`;
- $('.erc8004-btn--connect').textContent = 'Connected';
- $('.erc8004-btn--connect').disabled = true;
- this._checkReady();
- } catch (err) {
- this._log('Wallet error: ' + err.message, true);
+ this.el.querySelector('.erc8004-chain-select').addEventListener('change', async (e) => {
+ const newChain = Number(e.target.value);
+ this.selectedChainId = newChain;
+ // If wallet connected and on the wrong chain, try to switch
+ if (this.wallet && this.wallet.chainId !== newChain && window.ethereum) {
+ try {
+ await switchChain(newChain);
+ this.wallet.chainId = newChain;
+ this._refreshWalletButton();
+ } catch (err) {
+ this._toast('Chain switch rejected: ' + err.message, true);
+ }
}
+ this._renderActiveTab();
+ this._refreshStats();
});
- // File input
- const fileInput = $('.erc8004-file-input');
- const fileDrop = $('#erc8004-file-drop');
-
- fileInput.addEventListener('change', (e) => {
- this.selectedFile = e.target.files[0] || null;
- this._updateFileLabel();
+ this.el.querySelectorAll('.erc8004-tab').forEach((btn) => {
+ btn.addEventListener('click', () => this._setTab(btn.dataset.tab));
});
+ }
- fileDrop.addEventListener('dragover', (e) => {
- e.preventDefault();
- fileDrop.classList.add('erc8004-file-drop--active');
- });
- fileDrop.addEventListener('dragleave', () => {
- fileDrop.classList.remove('erc8004-file-drop--active');
- });
- fileDrop.addEventListener('drop', (e) => {
- e.preventDefault();
- fileDrop.classList.remove('erc8004-file-drop--active');
- const file = e.dataTransfer.files[0];
- if (file && /\.(glb|gltf)$/i.test(file.name)) {
- this.selectedFile = file;
- this._updateFileLabel();
+ destroy() {
+ this.el.remove();
+ }
+
+ // -----------------------------------------------------------------------
+ // Wallet & chain
+ // -----------------------------------------------------------------------
+
+ async _connectWallet() {
+ try {
+ const { address, chainId } = await connectWallet();
+ this.wallet = { address, chainId: Number(chainId) };
+
+ // Adopt wallet's chain if supported; otherwise keep selected and offer switch
+ if (REGISTRY_DEPLOYMENTS[this.wallet.chainId]) {
+ this.selectedChainId = this.wallet.chainId;
+ const sel = this.el.querySelector('.erc8004-chain-select');
+ if (sel) sel.value = String(this.selectedChainId);
}
- });
- // Register
- $('.erc8004-btn--register').addEventListener('click', () => this._doRegister());
+ this._refreshWalletButton();
+ this._renderActiveTab();
+ this._refreshStats();
+ } catch (err) {
+ this._toast('Wallet: ' + err.message, true);
+ }
+ }
+
+ _refreshWalletButton() {
+ const btn = this.el.querySelector('.erc8004-btn--wallet');
+ if (!this.wallet) {
+ btn.textContent = isPrivyConfigured() ? 'Connect Wallet' : 'Connect MetaMask';
+ btn.classList.remove('erc8004-btn--connected');
+ return;
+ }
+ btn.textContent = shortAddr(this.wallet.address);
+ btn.classList.add('erc8004-btn--connected');
+ }
- // View result — jump to viewer with the registered model
- $('.erc8004-btn--view').addEventListener('click', () => {
- const id = $('.erc8004-res-id').textContent;
- window.location.hash = id ? `agent=${id}` : '';
- window.location.reload();
+ _populateChainSelect() {
+ const sel = this.el.querySelector('.erc8004-chain-select');
+ const ids = supportedChainIds();
+ // Testnets first (default-friendly), then mainnets
+ const testnets = ids.filter((id) => CHAIN_META[id].testnet);
+ const mainnets = ids.filter((id) => !CHAIN_META[id].testnet);
+ const groupT = document.createElement('optgroup'); groupT.label = 'Testnets';
+ const groupM = document.createElement('optgroup'); groupM.label = 'Mainnets';
+ for (const id of testnets) {
+ const opt = document.createElement('option');
+ opt.value = String(id); opt.textContent = CHAIN_META[id].name;
+ groupT.appendChild(opt);
+ }
+ for (const id of mainnets) {
+ const opt = document.createElement('option');
+ opt.value = String(id); opt.textContent = CHAIN_META[id].name;
+ groupM.appendChild(opt);
+ }
+ sel.appendChild(groupT);
+ sel.appendChild(groupM);
+ sel.value = String(this.selectedChainId);
+ }
+
+ async _refreshStats() {
+ const el = (k) => this.el.querySelector(`[data-stat="${k}"]`);
+ try {
+ const [total, version] = await Promise.all([
+ getTotalSupply(this.selectedChainId).catch(() => null),
+ getRegistryVersion(this.selectedChainId).catch(() => null),
+ ]);
+ if (total !== null) el('total').textContent = String(total);
+ if (version) el('version').textContent = version;
+ } catch { /* swallow; stats are cosmetic */ }
+ }
+
+ // -----------------------------------------------------------------------
+ // Backend agent link (optional)
+ // -----------------------------------------------------------------------
+
+ async _fetchBackendAgent() {
+ try {
+ const res = await fetch('/api/agents/me', { credentials: 'include' });
+ if (!res.ok) return;
+ const { agent } = await res.json();
+ if (agent && agent.id) this._backendAgentId = agent.id;
+ } catch { /* anon user or endpoint unavailable — fine */ }
+ }
+
+ async _linkAgentToAccount({ agentId, chainId, txHash }) {
+ if (!this._backendAgentId || !this.wallet) return;
+ try {
+ await fetch(`/api/agents/${encodeURIComponent(this._backendAgentId)}/wallet`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ wallet_address: this.wallet.address,
+ chain_id: chainId,
+ erc8004_agent_id: agentId,
+ tx_hash: txHash,
+ }),
+ });
+ } catch (err) {
+ console.warn('[erc8004] Failed to link on-chain agentId to account:', err.message);
+ }
+ }
+
+ // -----------------------------------------------------------------------
+ // Tabs
+ // -----------------------------------------------------------------------
+
+ _setTab(tab) {
+ this.activeTab = tab;
+ this.el.querySelectorAll('.erc8004-tab').forEach((btn) => {
+ btn.classList.toggle('erc8004-tab--active', btn.dataset.tab === tab);
});
+ this._renderActiveTab();
+ }
+
+ _renderActiveTab() {
+ const body = this.el.querySelector('[data-role="tab-body"]');
+ body.innerHTML = '';
+ switch (this.activeTab) {
+ case 'create': this._renderCreate(body); break;
+ case 'my': this._renderMyAgents(body); break;
+ case 'search': this._renderSearch(body); break;
+ case 'templates': this._renderTemplates(body); break;
+ case 'history': this._renderHistory(body); break;
+ }
}
- _updateFileLabel() {
- const label = this.el.querySelector('.erc8004-file-text');
- label.textContent = this.selectedFile ? this.selectedFile.name : 'Drop .glb file or click to browse';
- this._checkReady();
+ // -----------------------------------------------------------------------
+ // Tab: Create Agent (4-step wizard)
+ // -----------------------------------------------------------------------
+
+ _renderCreate(body) {
+ const step = this.wizardStep;
+ body.innerHTML = `
+ <div class="erc8004-wizard">
+ <ol class="erc8004-steps">
+ ${[1,2,3,4].map((n) => `
+ <li class="erc8004-step ${n === step ? 'erc8004-step--active' : ''} ${n < step ? 'erc8004-step--done' : ''}">
+ <span class="erc8004-step-num">${n}</span>
+ <span class="erc8004-step-lbl">${['Identity','Services','Configuration','Deploy'][n-1]}</span>
+ </li>
+ `).join('')}
+ </ol>
+ <div class="erc8004-wizard-body" data-role="wizard-body"></div>
+ </div>
+ `;
+ const wbody = body.querySelector('[data-role="wizard-body"]');
+ if (step === 1) this._renderStepIdentity(wbody);
+ else if (step === 2) this._renderStepServices(wbody);
+ else if (step === 3) this._renderStepConfig(wbody);
+ else this._renderStepDeploy(wbody);
}
- _checkReady() {
- const btn = this.el.querySelector('.erc8004-btn--register');
- const name = this.el.querySelector('[name="agentName"]').value.trim();
- btn.disabled = !(this.walletAddress && this.selectedFile && name.length > 0);
+ _renderStepIdentity(body) {
+ body.innerHTML = `
+ <h3 class="erc8004-h3">Agent Identity</h3>
+ <p class="erc8004-p">Define your agent's core identity — name, description, and image.</p>
+
+ <label class="erc8004-label">Agent Name <span class="erc8004-req">*</span>
+ <input class="erc8004-input" name="name" maxlength="100" placeholder="e.g., DeFi Yield Optimizer" value="${esc(this.form.name)}" />
+ </label>
+ <p class="erc8004-hint">A short, memorable name (max 100 chars)</p>
+
+ <label class="erc8004-label">Description <span class="erc8004-req">*</span>
+ <textarea class="erc8004-input erc8004-textarea" name="description" maxlength="1000" rows="4" placeholder="Describe what your agent does, capabilities, pricing…">${esc(this.form.description)}</textarea>
+ </label>
+ <p class="erc8004-hint">Clear description (max 1000 chars)</p>
+
+ <label class="erc8004-label">Image URL
+ <input class="erc8004-input" name="imageUrl" placeholder="https://example.com/avatar.png or ipfs://…" value="${esc(this.form.imageUrl)}" />
+ </label>
+ <p class="erc8004-hint">Avatar or logo for your agent NFT</p>
+
+ <div class="erc8004-wizard-nav">
+ <span></span>
+ <button class="erc8004-btn erc8004-btn--primary" data-role="next">Next: Services →</button>
+ </div>
+ `;
+ body.querySelector('[name="name"]').addEventListener('input', (e) => this.form.name = e.target.value);
+ body.querySelector('[name="description"]').addEventListener('input', (e) => this.form.description = e.target.value);
+ body.querySelector('[name="imageUrl"]').addEventListener('input', (e) => this.form.imageUrl = e.target.value);
+ body.querySelector('[data-role="next"]').addEventListener('click', () => {
+ if (!this.form.name.trim() || !this.form.description.trim()) {
+ this._toast('Name and description are required.', true);
+ return;
+ }
+ this.wizardStep = 2;
+ this._renderActiveTab();
+ });
}
- _log(msg, isError = false) {
- const log = this.el.querySelector('.erc8004-log');
- const line = document.createElement('div');
- line.className = 'erc8004-log-line' + (isError ? ' erc8004-log-error' : '');
- line.textContent = msg;
- log.appendChild(line);
- log.scrollTop = log.scrollHeight;
+ _renderStepServices(body) {
+ body.innerHTML = `
+ <h3 class="erc8004-h3">Service Endpoints</h3>
+ <p class="erc8004-p">Add one or more endpoints so other agents can discover and talk to yours. Optional but recommended.</p>
+
+ <div class="erc8004-services" data-role="list"></div>
+
+ <button class="erc8004-btn erc8004-btn--ghost" data-role="add">+ Add endpoint</button>
+
+ <div class="erc8004-wizard-nav">
+ <button class="erc8004-btn" data-role="back">← Back</button>
+ <button class="erc8004-btn erc8004-btn--primary" data-role="next">Next: Configuration →</button>
+ </div>
+ `;
+ const list = body.querySelector('[data-role="list"]');
+ const renderList = () => {
+ list.innerHTML = this.form.services.map((svc, i) => `
+ <div class="erc8004-svc-row" data-i="${i}">
+ <select class="erc8004-input erc8004-input--tight" data-field="type">
+ ${SERVICE_TYPES.map((t) => `<option value="${t}" ${svc.type === t ? 'selected' : ''}>${t}</option>`).join('')}
+ </select>
+ <input class="erc8004-input" data-field="name" placeholder="Name" value="${esc(svc.name)}" />
+ <input class="erc8004-input" data-field="endpoint" placeholder="https://… or ipfs://…" value="${esc(svc.endpoint)}" />
+ <button class="erc8004-btn erc8004-btn--ghost erc8004-btn--x" data-role="rm" title="Remove">✕</button>
+ </div>
+ `).join('');
+
+ list.querySelectorAll('.erc8004-svc-row').forEach((row) => {
+ const i = Number(row.dataset.i);
+ row.querySelectorAll('[data-field]').forEach((input) => {
+ input.addEventListener('input', (e) => {
+ this.form.services[i][e.target.dataset.field] = e.target.value;
+ });
+ });
+ row.querySelector('[data-role="rm"]').addEventListener('click', () => {
+ this.form.services.splice(i, 1);
+ renderList();
+ });
+ });
+ };
+ renderList();
+
+ body.querySelector('[data-role="add"]').addEventListener('click', () => {
+ this.form.services.push({ type: 'A2A', name: '', endpoint: '' });
+ renderList();
+ });
+ body.querySelector('[data-role="back"]').addEventListener('click', () => { this.wizardStep = 1; this._renderActiveTab(); });
+ body.querySelector('[data-role="next"]').addEventListener('click', () => { this.wizardStep = 3; this._renderActiveTab(); });
}
- async _doRegister() {
- const $ = (sel) => this.el.querySelector(sel);
- const name = $('[name="agentName"]').value.trim();
- const description = $('[name="agentDesc"]').value.trim();
- const registerBtn = $('.erc8004-btn--register');
+ _renderStepConfig(body) {
+ body.innerHTML = `
+ <h3 class="erc8004-h3">Configuration</h3>
+ <p class="erc8004-p">Optional: attach a 3D avatar (GLB) so anyone can render your agent in a browser. If provided, it becomes the agent's primary image.</p>
+
+ <label class="erc8004-label">3D Avatar (GLB)
+ <div class="erc8004-file-drop" data-role="drop">
+ <input type="file" accept=".glb,.gltf" class="erc8004-file-input" />
+ <span class="erc8004-file-text">${this.form.glbFile ? esc(this.form.glbFile.name) : 'Drop .glb file or click to browse'}</span>
+ </div>
+ </label>
+
+ <label class="erc8004-label">IPFS Pinning Token (optional)
+ <input class="erc8004-input" type="password" name="apiToken" placeholder="Pinata JWT — leave blank to use built-in R2 storage" value="${esc(this.form.apiToken)}" />
+ </label>
+ <p class="erc8004-hint">Without a token, uploads go through our backend (R2). Paste a Pinata JWT to pin directly to IPFS.</p>
+
+ <div class="erc8004-wizard-nav">
+ <button class="erc8004-btn" data-role="back">← Back</button>
+ <button class="erc8004-btn erc8004-btn--primary" data-role="next">Next: Deploy →</button>
+ </div>
+ `;
+ const drop = body.querySelector('[data-role="drop"]');
+ const input = drop.querySelector('.erc8004-file-input');
+ const label = drop.querySelector('.erc8004-file-text');
+
+ const setFile = (f) => {
+ if (!f) return;
+ if (!/\.(glb|gltf)$/i.test(f.name)) { this._toast('Must be a .glb or .gltf file', true); return; }
+ this.form.glbFile = f;
+ label.textContent = f.name;
+ };
- registerBtn.disabled = true;
- registerBtn.textContent = 'Registering...';
+ input.addEventListener('change', (e) => setFile(e.target.files[0]));
+ drop.addEventListener('dragover', (e) => { e.preventDefault(); drop.classList.add('erc8004-file-drop--active'); });
+ drop.addEventListener('dragleave', () => drop.classList.remove('erc8004-file-drop--active'));
+ drop.addEventListener('drop', (e) => { e.preventDefault(); drop.classList.remove('erc8004-file-drop--active'); setFile(e.dataTransfer.files[0]); });
+
+ body.querySelector('[name="apiToken"]').addEventListener('input', (e) => this.form.apiToken = e.target.value);
+ body.querySelector('[data-role="back"]').addEventListener('click', () => { this.wizardStep = 2; this._renderActiveTab(); });
+ body.querySelector('[data-role="next"]').addEventListener('click', () => { this.wizardStep = 4; this._renderActiveTab(); });
+ }
+
+ _renderStepDeploy(body) {
+ const meta = CHAIN_META[this.selectedChainId];
+ const walletOk = !!this.wallet;
+ const chainOk = walletOk && this.wallet.chainId === this.selectedChainId;
+ body.innerHTML = `
+ <h3 class="erc8004-h3">Review &amp; Deploy</h3>
+ <p class="erc8004-p">Your agent will be minted as an ERC-721 NFT on <b>${esc(meta.name)}</b>. This is the only step that costs gas.</p>
+
+ <dl class="erc8004-summary">
+ <dt>Name</dt> <dd>${esc(this.form.name)}</dd>
+ <dt>Description</dt> <dd>${esc(this.form.description)}</dd>
+ ${this.form.imageUrl ? `<dt>Image</dt> <dd>${esc(this.form.imageUrl)}</dd>` : ''}
+ ${this.form.glbFile ? `<dt>GLB File</dt> <dd>${esc(this.form.glbFile.name)} (${(this.form.glbFile.size/1024).toFixed(1)} KB)</dd>` : ''}
+ <dt>Services</dt> <dd>${this.form.services.length ? this.form.services.map(s => `${esc(s.type)}: ${esc(s.endpoint || '—')}`).join('<br>') : '<span class="erc8004-muted">none</span>'}</dd>
+ <dt>Chain</dt> <dd>${esc(meta.name)} (chainId ${this.selectedChainId})</dd>
+ <dt>Registry</dt> <dd><code>${esc(REGISTRY_DEPLOYMENTS[this.selectedChainId].identityRegistry)}</code></dd>
+ </dl>
+
+ ${!walletOk ? `<div class="erc8004-alert">Connect a wallet before deploying.</div>` : ''}
+ ${walletOk && !chainOk ? `<div class="erc8004-alert">Your wallet is on chain ${this.wallet.chainId}. <button class="erc8004-link" data-role="switch">Switch to ${esc(meta.name)}</button></div>` : ''}
+
+ <div class="erc8004-log" data-role="log"></div>
+
+ <div class="erc8004-result" data-role="result" style="display:none">
+ <h4 class="erc8004-h4">✓ Agent registered</h4>
+ <dl class="erc8004-result-dl">
+ <dt>Agent ID</dt> <dd data-role="res-id"></dd>
+ <dt>Metadata</dt> <dd data-role="res-uri"></dd>
+ <dt>Tx Hash</dt> <dd data-role="res-tx"></dd>
+ </dl>
+ <div class="erc8004-row">
+ <button class="erc8004-btn" data-role="view-3d">View in 3D</button>
+ <a class="erc8004-btn" data-role="view-explorer" target="_blank" rel="noopener">View on explorer ↗</a>
+ </div>
+ </div>
+
+ <div class="erc8004-wizard-nav">
+ <button class="erc8004-btn" data-role="back">← Back</button>
+ <button class="erc8004-btn erc8004-btn--primary" data-role="deploy" ${walletOk ? '' : 'disabled'}>🚀 Register Agent On-Chain</button>
+ </div>
+ `;
+ body.querySelector('[data-role="back"]').addEventListener('click', () => { this.wizardStep = 3; this._renderActiveTab(); });
+
+ const switchBtn = body.querySelector('[data-role="switch"]');
+ if (switchBtn) {
+ switchBtn.addEventListener('click', async () => {
+ try {
+ await switchChain(this.selectedChainId);
+ if (this.wallet) this.wallet.chainId = this.selectedChainId;
+ this._renderActiveTab();
+ } catch (err) {
+ this._toast('Switch failed: ' + err.message, true);
+ }
+ });
+ }
+
+ body.querySelector('[data-role="deploy"]').addEventListener('click', () => this._doDeploy(body));
+ }
+
+ async _doDeploy(body) {
+ const log = body.querySelector('[data-role="log"]');
+ const say = (msg, err = false) => {
+ const line = document.createElement('div');
+ line.className = 'erc8004-log-line' + (err ? ' erc8004-log-error' : '');
+ line.textContent = msg;
+ log.appendChild(line);
+ log.scrollTop = log.scrollHeight;
+ };
+ const deployBtn = body.querySelector('[data-role="deploy"]');
+ deployBtn.disabled = true;
try {
- const result = await registerAgent({
- glbFile: this.selectedFile,
+ // Ensure we're on the target chain
+ if (this.wallet && this.wallet.chainId !== this.selectedChainId) {
+ say(`Switching to ${CHAIN_META[this.selectedChainId].name}…`);
+ await switchChain(this.selectedChainId);
+ this.wallet.chainId = this.selectedChainId;
+ }
+
+ const result = await this._doRegister(say);
+
+ body.querySelector('[data-role="result"]').style.display = '';
+ body.querySelector('[data-role="res-id"]').textContent = String(result.agentId);
+ body.querySelector('[data-role="res-uri"]').textContent = result.registrationUrl;
+ body.querySelector('[data-role="res-tx"]').textContent = result.txHash;
+
+ const view3D = body.querySelector('[data-role="view-3d"]');
+ view3D.addEventListener('click', () => {
+ // Jump to the viewer with this model loaded
+ window.location.hash = `agent=${result.agentId}`;
+ window.location.reload();
+ });
+ body.querySelector('[data-role="view-explorer"]').href = txExplorerUrl(this.selectedChainId, result.txHash);
+
+ this.onRegistered({ ...result, chainId: this.selectedChainId });
+ await this._linkAgentToAccount({ agentId: result.agentId, chainId: this.selectedChainId, txHash: result.txHash });
+ this._refreshStats();
+ } catch (err) {
+ say('Registration failed: ' + (err.shortMessage || err.message || String(err)), true);
+ deployBtn.disabled = false;
+ }
+ }
+
+ /**
+ * Wraps agent-registry.registerAgent() with GLB-optional behavior: if the
+ * user uploaded a GLB we use the existing flow; otherwise we go straight
+ * to metadata-JSON pinning + on-chain mint.
+ */
+ async _doRegister(say) {
+ const { name, description, imageUrl, glbFile, services, apiToken } = this.form;
+
+ // GLB path — use the existing registerAgent flow (pins GLB, mints, updates URI).
+ // We extend it by appending user-supplied services to the registration JSON.
+ if (glbFile) {
+ return await registerAgent({
+ glbFile,
name,
description,
- onStatus: (msg) => this._log(msg),
+ apiToken: apiToken || undefined,
+ onStatus: say,
+ services: services.filter((s) => s.endpoint.trim()).map((s) => ({
+ name: s.name || s.type,
+ type: s.type,
+ endpoint: s.endpoint,
+ version: '1.0',
+ })),
+ });
+ }
+
+ // URI-only path: mirror agent-registry.registerAgent() but without the GLB upload.
+ say('Connecting wallet…');
+ const { signer, chainId } = await connectWallet();
+ const registry = getIdentityRegistry(chainId, signer);
+
+ say('Registering agent on-chain…');
+ const seedURI = imageUrl || '';
+ const tx = seedURI
+ ? await registry['register(string)'](seedURI)
+ : await registry['register()']();
+ say(`Transaction submitted: ${tx.hash}`);
+ const receipt = await tx.wait();
+
+ const registeredEvent = receipt.logs
+ .map((l) => { try { return registry.interface.parseLog(l); } catch { return null; } })
+ .find((e) => e && e.name === 'Registered');
+ if (!registeredEvent) throw new Error('Registered event not found in receipt');
+ const agentId = Number(registeredEvent.args.agentId);
+ say(`Agent minted! agentId = ${agentId}`);
+
+ const registrationJSON = buildRegistrationJSON({
+ name,
+ description,
+ imageUrl: imageUrl || '',
+ agentId,
+ chainId,
+ registryAddr: REGISTRY_DEPLOYMENTS[chainId].identityRegistry,
+ services: services.filter((s) => s.endpoint.trim()).map((s) => ({
+ name: s.name || s.type,
+ type: s.type,
+ endpoint: s.endpoint,
+ version: '1.0',
+ })),
+ });
+
+ say('Uploading registration metadata…');
+ const jsonBlob = new Blob([JSON.stringify(registrationJSON, null, 2)], { type: 'application/json' });
+ const registrationUrl = await pinFile(jsonBlob, apiToken || undefined);
+ say(`Registration metadata: ${registrationUrl}`);
+
+ say('Updating agentURI on-chain…');
+ const updateTx = await registry.setAgentURI(agentId, registrationUrl);
+ await updateTx.wait();
+
+ return { agentId, registrationUrl, txHash: tx.hash };
+ }
+
+ // -----------------------------------------------------------------------
+ // Tab: My Agents
+ // -----------------------------------------------------------------------
+
+ _renderMyAgents(body) {
+ body.innerHTML = `
+ <h3 class="erc8004-h3">Your Registered Agents</h3>
+ ${this.wallet
+ ? `<p class="erc8004-p">Connected as <code>${esc(this.wallet.address)}</code> on <b>${esc(CHAIN_META[this.selectedChainId]?.name || '?')}</b>.</p>`
+ : `<p class="erc8004-p erc8004-muted">Connect a wallet to see agents you own.</p>`}
+ <div data-role="list"></div>
+ `;
+ if (!this.wallet) return;
+
+ const list = body.querySelector('[data-role="list"]');
+ list.innerHTML = `<div class="erc8004-muted">Scanning…</div>`;
+
+ listAgentsByOwner({
+ chainId: this.selectedChainId,
+ owner: this.wallet.address,
+ ethProvider: window.ethereum,
+ }).then(async (res) => {
+ if (res.count === 0) {
+ list.innerHTML = `<div class="erc8004-muted">No agents registered on this chain yet. <a class="erc8004-link" data-role="goto-create">Create one →</a></div>`;
+ list.querySelector('[data-role="goto-create"]').addEventListener('click', (e) => { e.preventDefault(); this._setTab('create'); });
+ return;
+ }
+ if (res.ids.length === 0 && res.partial) {
+ const explorer = addressExplorerUrl(this.selectedChainId, this.wallet.address);
+ list.innerHTML = `
+ <div class="erc8004-muted">
+ You own ${res.count} agent(s) but details could not be loaded from recent blocks.
+ <a href="${esc(explorer)}" target="_blank" rel="noopener" class="erc8004-link">Check explorer ↗</a>
+ </div>`;
+ return;
+ }
+ list.innerHTML = '';
+ for (const id of res.ids) {
+ const card = document.createElement('div');
+ card.className = 'erc8004-agent-card';
+ card.innerHTML = `<div class="erc8004-muted">Loading #${id}…</div>`;
+ list.appendChild(card);
+ this._fillAgentCard(card, id);
+ }
+ if (res.partial) {
+ const note = document.createElement('div');
+ note.className = 'erc8004-muted';
+ note.textContent = `Showing ${res.ids.length} of ${res.count} agents — older mints may be outside the scanned block window.`;
+ list.appendChild(note);
+ }
+ }).catch((err) => {
+ list.innerHTML = `<div class="erc8004-log-error">Query failed: ${esc(err.message)}</div>`;
+ });
+ }
+
+ async _fillAgentCard(card, agentId) {
+ try {
+ const { uri, owner } = await getAgentOnchain({
+ chainId: this.selectedChainId,
+ agentId,
+ ethProvider: window.ethereum,
});
+ const meta = uri ? await fetchAgentMetadata(uri) : { ok: false, error: 'no uri' };
+ const registryAddr = REGISTRY_DEPLOYMENTS[this.selectedChainId].identityRegistry;
+ const tokenUrl = tokenExplorerUrl(this.selectedChainId, registryAddr, agentId);
- // Show result
- $('.erc8004-res-id').textContent = result.agentId;
- $('.erc8004-res-cid').textContent = result.registrationUrl;
- $('.erc8004-res-tx').textContent = result.txHash;
- $('.erc8004-result').style.display = '';
- this._log('Registration complete!');
+ const name = meta.ok ? (meta.data.name || `Agent #${agentId}`) : `Agent #${agentId}`;
+ const description = meta.ok ? meta.data.description : '';
+ const image = meta.ok ? meta.data.image : '';
- this.onRegistered(result);
+ card.innerHTML = `
+ <div class="erc8004-agent-card-inner">
+ <div class="erc8004-agent-card-img">
+ ${image ? `<img src="${esc(resolveGateway(image))}" alt="" loading="lazy" />` : `<div class="erc8004-agent-card-ph">🤖</div>`}
+ </div>
+ <div class="erc8004-agent-card-body">
+ <div class="erc8004-agent-card-head">
+ <strong>${esc(name)}</strong>
+ <span class="erc8004-tag">#${agentId}</span>
+ </div>
+ ${description ? `<p class="erc8004-p erc8004-clip">${esc(description)}</p>` : ''}
+ <div class="erc8004-agent-card-actions">
+ ${tokenUrl ? `<a class="erc8004-link" href="${esc(tokenUrl)}" target="_blank" rel="noopener">Explorer ↗</a>` : ''}
+ <a class="erc8004-link" href="#agent=${agentId}">Open in viewer</a>
+ </div>
+ </div>
+ </div>
+ `;
} catch (err) {
- this._log('Registration failed: ' + err.message, true);
- registerBtn.disabled = false;
- registerBtn.textContent = 'Register Agent On-Chain';
+ card.innerHTML = `<div class="erc8004-log-error">Agent #${agentId}: ${esc(err.message)}</div>`;
}
}
- /** Remove the UI from the DOM. */
- destroy() {
- this.el.remove();
+ // -----------------------------------------------------------------------
+ // Tab: Search
+ // -----------------------------------------------------------------------
+
+ _renderSearch(body) {
+ body.innerHTML = `
+ <h3 class="erc8004-h3">Agent Search</h3>
+ <p class="erc8004-p">Find a registered agent by its on-chain ID on <b>${esc(CHAIN_META[this.selectedChainId]?.name)}</b>.</p>
+ <div class="erc8004-row">
+ <input class="erc8004-input" name="q" placeholder="Agent ID (e.g., 6443)" />
+ <button class="erc8004-btn erc8004-btn--primary" data-role="go">Search</button>
+ </div>
+ <div data-role="result" style="margin-top:14px"></div>
+ `;
+ const q = body.querySelector('[name="q"]');
+ const out = body.querySelector('[data-role="result"]');
+ const go = async () => {
+ const id = q.value.trim();
+ if (!/^\d+$/.test(id)) { out.innerHTML = `<div class="erc8004-log-error">Enter a numeric Agent ID.</div>`; return; }
+ out.innerHTML = `<div class="erc8004-muted">Loading #${id}…</div>`;
+ try {
+ const card = document.createElement('div');
+ card.className = 'erc8004-agent-card';
+ out.innerHTML = '';
+ out.appendChild(card);
+ await this._fillAgentCard(card, BigInt(id));
+ } catch (err) {
+ out.innerHTML = `<div class="erc8004-log-error">${esc(err.message)}</div>`;
+ }
+ };
+ body.querySelector('[data-role="go"]').addEventListener('click', go);
+ q.addEventListener('keydown', (e) => { if (e.key === 'Enter') go(); });
+ }
+
+ // -----------------------------------------------------------------------
+ // Tab: Templates
+ // -----------------------------------------------------------------------
+
+ _renderTemplates(body) {
+ body.innerHTML = `
+ <h3 class="erc8004-h3">Agent Templates</h3>
+ <p class="erc8004-p">Pre-built configurations — one click to prefill the Create Agent wizard.</p>
+ <div class="erc8004-template-grid">
+ ${TEMPLATES.map((t) => `
+ <button class="erc8004-template" data-id="${t.id}">
+ <div class="erc8004-template-emoji">${t.emoji}</div>
+ <div class="erc8004-template-name">${esc(t.name)}</div>
+ <div class="erc8004-template-desc">${esc(t.description)}</div>
+ </button>
+ `).join('')}
+ </div>
+ `;
+ body.querySelectorAll('.erc8004-template').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const t = TEMPLATES.find((x) => x.id === btn.dataset.id);
+ if (!t) return;
+ this.form.name = t.name;
+ this.form.description = t.description;
+ this.wizardStep = 1;
+ this._setTab('create');
+ });
+ });
}
+
+ // -----------------------------------------------------------------------
+ // Tab: History
+ // -----------------------------------------------------------------------
+
+ _renderHistory(body) {
+ body.innerHTML = `
+ <h3 class="erc8004-h3">Transaction History</h3>
+ <p class="erc8004-p">Recent <code>Registered</code> events on <b>${esc(CHAIN_META[this.selectedChainId]?.name)}</b>${this.wallet ? ` for <code>${esc(this.wallet.address)}</code>` : ''}.</p>
+ <div data-role="list"></div>
+ `;
+ const list = body.querySelector('[data-role="list"]');
+ list.innerHTML = `<div class="erc8004-muted">Loading…</div>`;
+
+ listRegisteredEvents({
+ chainId: this.selectedChainId,
+ owner: this.wallet?.address,
+ ethProvider: window.ethereum,
+ limit: 50,
+ }).then((events) => {
+ if (events.length === 0) {
+ list.innerHTML = `<div class="erc8004-muted">No events in the scanned window.</div>`;
+ return;
+ }
+ list.innerHTML = events.map((ev) => `
+ <div class="erc8004-history-row">
+ <div class="erc8004-history-main">
+ <div><strong>Agent #${ev.agentId}</strong> <span class="erc8004-muted">by ${esc(shortAddr(ev.owner))}</span></div>
+ <div class="erc8004-muted erc8004-small">Block ${ev.blockNumber} · <code>${esc(ev.agentURI).slice(0, 60)}${ev.agentURI.length > 60 ? '…' : ''}</code></div>
+ </div>
+ <a class="erc8004-link" href="${esc(txExplorerUrl(this.selectedChainId, ev.txHash))}" target="_blank" rel="noopener">tx ↗</a>
+ </div>
+ `).join('');
+ }).catch((err) => {
+ list.innerHTML = `<div class="erc8004-log-error">Failed to load: ${esc(err.message)}</div>`;
+ });
+ }
+
+ // -----------------------------------------------------------------------
+ // Toast
+ // -----------------------------------------------------------------------
+
+ _toast(msg, isError = false) {
+ const t = document.createElement('div');
+ t.className = 'erc8004-toast' + (isError ? ' erc8004-toast--error' : '');
+ t.textContent = msg;
+ this.el.appendChild(t);
+ setTimeout(() => t.remove(), 4000);
+ }
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Helpers
+// ───────────────────────────────────────────────────────────────────────────
+
+function resolveGateway(uri) {
+ if (!uri) return '';
+ if (uri.startsWith('ipfs://')) return 'https://ipfs.io/ipfs/' + uri.slice(7);
+ if (uri.startsWith('ar://')) return 'https://arweave.net/' + uri.slice(5);
+ return uri;
}
diff --git a/src/erc8004/templates.js b/src/erc8004/templates.js
new file mode 100644
index 000000000..a820af4bb
--- /dev/null
+++ b/src/erc8004/templates.js
@@ -0,0 +1,92 @@
+/**
+ * Pre-filled agent templates — seed the Create wizard with one click.
+ *
+ * Each template populates Identity (name, description) + Services. Users can
+ * still edit everything before deploying.
+ */
+
+/**
+ * @typedef {Object} AgentTemplate
+ * @property {string} id Unique key.
+ * @property {string} emoji Display icon.
+ * @property {string} name Card title & default agent name.
+ * @property {string} description Card copy & default agent description.
+ * @property {Array<{name: string, endpoint: string, version?: string}>} services
+ * @property {{trust?: string[], x402?: boolean}} [config]
+ */
+
+/** @type {AgentTemplate[]} */
+export const TEMPLATES = [
+ {
+ id: 'defi-trading',
+ emoji: '📈',
+ name: 'DeFi Trading Agent',
+ description: 'Automated DeFi yield optimization, liquidity management, and token swaps across protocols.',
+ services: [
+ { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
+ { name: 'MCP', endpoint: 'https://your-agent.example/mcp', version: '1.0' },
+ ],
+ config: { trust: ['reputation'], x402: true },
+ },
+ {
+ id: 'support-bot',
+ emoji: '🎧',
+ name: 'Customer Support Bot',
+ description: 'AI-powered support agent for handling tickets, FAQ queries, and multi-language communication.',
+ services: [
+ { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
+ ],
+ config: { trust: ['reputation'], x402: false },
+ },
+ {
+ id: 'code-review',
+ emoji: '🔍',
+ name: 'Code Review Agent',
+ description: 'Automated code analysis, security auditing, gas optimization, and best practice enforcement.',
+ services: [
+ { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
+ { name: 'MCP', endpoint: 'https://your-agent.example/mcp', version: '1.0' },
+ ],
+ config: { trust: ['reputation', 'validation'], x402: true },
+ },
+ {
+ id: 'data-analysis',
+ emoji: '📊',
+ name: 'Data Analysis Agent',
+ description: 'On-chain and off-chain data analysis, reporting, visualization, and pattern recognition.',
+ services: [
+ { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
+ { name: 'OASF', endpoint: 'https://your-agent.example/oasf', version: '1.0' },
+ ],
+ config: { trust: ['reputation'], x402: true },
+ },
+ {
+ id: 'content-creator',
+ emoji: '✍️',
+ name: 'Content Creator',
+ description: 'AI content generation for social media, documentation, technical writing, and marketing.',
+ services: [
+ { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
+ ],
+ config: { trust: ['reputation'], x402: true },
+ },
+ {
+ id: 'research-assistant',
+ emoji: '🔬',
+ name: 'Research Assistant',
+ description: 'Deep research on protocols, tokens, governance proposals, and market trends.',
+ services: [
+ { name: 'A2A', endpoint: 'https://your-agent.example/a2a', version: '1.0' },
+ { name: 'MCP', endpoint: 'https://your-agent.example/mcp', version: '1.0' },
+ ],
+ config: { trust: ['reputation'], x402: true },
+ },
+];
+
+/**
+ * @param {string} id
+ * @returns {AgentTemplate|null}
+ */
+export function getTemplate(id) {
+ return TEMPLATES.find((t) => t.id === id) || null;
+}