Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(solana): enrol agents in the open Solana agent registry and read provider trust tiers when hiring
nirholasb7362d5ce4e2
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex a83276422..789b66b15 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -24,6 +24,7 @@ packages, a generated standalone GitHub mirror). See| Event Market pages and share cards | [pages/event-markets.html](pages/event-markets.html) `→ /event-markets`, [pages/event-market.html](pages/event-market.html) `→ /event-markets/<slug>`, [src/event-markets/](src/event-markets/), [api/event-market-og.js](api/event-market-og.js), [api/event-market-share.js](api/event-market-share.js), [api/_lib/event-market-card.js](api/_lib/event-market-card.js) | Live | Browse and detail pages, pick flow, odds chart, per-market SVG share card and crawlable meta page, entry strips on Arena, event, launches and home. Docs: [docs/event-markets.md](docs/event-markets.md#pages-and-share-cards). Tests: [tests/event-market-card.test.js](tests/event-market-card.test.js) || Event Market scoring, leaderboard and rewards | [api/_lib/event-markets/scoring.js](api/_lib/event-markets/scoring.js), [rollup.js](api/_lib/event-markets/rollup.js), [fairness.js](api/_lib/event-markets/fairness.js), [leaderboard.js](api/_lib/event-markets/leaderboard.js), [api/cron/event-markets-rollup.js](api/cron/event-markets-rollup.js), [data/event-market-scoring.json](data/event-market-scoring.json), [pages/event-markets-leaderboard.html](pages/event-markets-leaderboard.html) `→ /event-markets/leaderboard`, [scripts/event-markets-season-payouts.mjs](scripts/event-markets-season-payouts.mjs) | Live once migration 20261012400000 is applied; payouts owner-gated | Scores, streaks, season ranks and badges from the rollup cron; wallet-derived names; fair-play ranking checks; season reward table printed for owner approval, never sent automatically. Docs: [docs/event-markets.md](docs/event-markets.md#scoring-and-seasons). Tests: [tests/event-markets-scoring.test.js](tests/event-markets-scoring.test.js) || Event Market live feed | [api/event-markets/stream.js](api/event-markets/stream.js), [api/_lib/event-markets/hub.js](api/_lib/event-markets/hub.js), [feed.js](api/_lib/event-markets/feed.js), [moves.js](api/_lib/event-markets/moves.js), [live-stats.js](api/_lib/event-markets/live-stats.js), [api/cron/event-markets-feed.js](api/cron/event-markets-feed.js), [src/event-markets/live-feed.js](src/event-markets/live-feed.js), [ticker.js](src/event-markets/ticker.js), [data/event-markets-feed.json](data/event-markets-feed.json) | Live (migration 20261012200000 applied) | SSE odds, picks, moves and lifecycle with Last-Event-ID resume, odds-move detector, home ticker, in-place odds on the market page with polling fallback, pulse and trending additions. Docs: [docs/event-markets.md](docs/event-markets.md#live-feed). Tests: [tests/event-markets-live-feed.test.js](tests/event-markets-live-feed.test.js), [tests/event-markets-live-stats.test.js](tests/event-markets-live-stats.test.js). Bench: [scripts/event-markets-fanout-bench.mjs](scripts/event-markets-fanout-bench.mjs) |+| Solana agent registry (8004) | [api/_lib/solana-8004.js](api/_lib/solana-8004.js), hook in [api/_lib/onchain-deploy.js](api/_lib/onchain-deploy.js), read side in [api/_lib/agent-economy.js](api/_lib/agent-economy.js) and [api/agents/a2a-hire.js](api/agents/a2a-hire.js), badge in [src/agent-detail.js](src/agent-detail.js), back-fill [scripts/register-8004-agents.mjs](scripts/register-8004-agents.mjs), proof [scripts/prove-8004-registry.mjs](scripts/prove-8004-registry.mjs), SDK patch [scripts/fix-8004-solana-esm.mjs](scripts/fix-8004-solana-esm.mjs) | Devnet live; mainnet registration opt-in (`SOLANA_8004_REGISTER_MAINNET=1`) | Authority-managed registration beside the Metaplex identity, registry block on the agent row, live tier read in hires, tier tie-break in offer ranking, `minRegistryTier` guard, agent-page badge, rate-limited back-fill. Docs: [docs/solana-agent-registry.md](docs/solana-agent-registry.md). Tests: [tests/solana-8004.test.js](tests/solana-8004.test.js), [tests/solana-8004.devnet.test.js](tests/solana-8004.devnet.test.js) || App pages (hub plus Android, Seeker, iOS, Desktop, Web) | Pages [pages/apps.html](pages/apps.html) `→ /apps` and `pages/apps-{web,android,seeker,ios,desktop}.html` `→ /apps/*`, code [src/apps.js](src/apps.js), [src/apps.css](src/apps.css) | Built and verified locally | One page per platform with its real install path and status; the desktop page reads the live release feed. Docs: [docs/apps.md](docs/apps.md) || The Grid (a neon wireframe room of live app surfaces, a board, a directory, a Pulse wall and a kiosk per app) | Code [src/desktop/grid/](src/desktop/grid) `→ /?world=grid`, entered from the campus HUD, tests [tests/desktop-grid.test.js](tests/desktop-grid.test.js) | Built and verified locally | Walk up to a surface and press E to open the app on the desktop; every panel reads a live feed; byte tier comes from mined gems. Docs: [docs/desktop.md](docs/desktop.md) || The Field (a live, zoomable map of every agent and surface) | Page [pages/desktop.html](pages/desktop.html) `→ /?view=field`, code [src/field/](src/field) ([README](src/field/README.md)): pure layout and camera [logic.js](src/field/logic.js), feeds [data.js](src/field/data.js), map [field.js](src/field/field.js), entry and view switch [entry.js](src/field/entry.js) | Built and verified locally | Public agents drawn as stars in a golden-angle core around ten live districts; semantic zoom from one readout per district to full cards (avatars, launches, $THREE quote and CA, Pulse wallet moves, top skills, most-talked-to agents); Pulse events fly in as comets; search over places, agents and every nav page; any page opens in place at a shareable `/?go=` URL. The homepage `/` is the web desktop; the campus is at `/?world=1`. Docs: [docs/field.md](docs/field.md) |diff --git a/api/_lib/agent-economy.js b/api/_lib/agent-economy.jsindex 491fcd60a..03a861580 100644--- a/api/_lib/agent-economy.js+++ b/api/_lib/agent-economy.js@@ -12,6 +12,7 @@// rails; this module only records the business-level hire and its lifecycle so// it can be queried, rated, and audited.+import { publicRegistry8004 } from './solana-8004.js';import { sql } from './db.js';import { cdnUrlOrNull } from './r2.js';@@ -36,6 +37,7 @@ function shapeProvider(row) {avatar_thumbnail_url: avatarThumb(row.provider_thumb_key, row.provider_avatar_vis),solana_address: row.provider_addr || null,is_public: row.provider_is_public !== false,+ registry_8004: publicRegistry8004(row.provider_registry_8004, 'mainnet'),};}@@ -222,6 +224,7 @@ export async function listOffersWithStats({ limit = 60, providerAgentId = null }ai.name AS provider_name,ai.is_public AS provider_is_public,ai.meta->>'solana_address' AS provider_addr,+ ai.meta->'registry_8004' AS provider_registry_8004,av.thumbnail_key AS provider_thumb_key,av.visibility AS provider_avatar_vis,st.completed AS completed,@@ -249,7 +252,11 @@ export async function listOffersWithStats({ limit = 60, providerAgentId = null }) st ON trueWHERE s.archived_at IS NULL AND s.bazaar_listed = true${providerFilter}- ORDER BY st.completed DESC NULLS LAST, s.created_at DESC+ ORDER BY st.completed DESC NULLS LAST,+ CASE ai.meta->'registry_8004'->'standing'->>'tier'+ WHEN 'Platinum' THEN 4 WHEN 'Gold' THEN 3 WHEN 'Silver' THEN 2 WHEN 'Bronze' THEN 1 ELSE 0+ END DESC,+ s.created_at DESCLIMIT ${capped}`;return rows.map(shapeOffer);@@ -269,6 +276,7 @@ async function listOffersBySlug(slug) {s.reputation_discount_enabled AS reputation_discount_enabled,ai.id AS provider_agent_id, ai.name AS provider_name, ai.is_public AS provider_is_public,ai.meta->>'solana_address' AS provider_addr,+ ai.meta->'registry_8004' AS provider_registry_8004,av.thumbnail_key AS provider_thumb_key, av.visibility AS provider_avatar_vis,NULL::bigint AS completed, NULL::bigint AS refunded, NULL::bigint AS total,NULL::float8 AS earned_usd, NULL::float8 AS avg_rating, NULL::bigint AS rating_count,diff --git a/api/_lib/onchain-deploy.js b/api/_lib/onchain-deploy.jsindex 9f3039055..a48786228 100644--- a/api/_lib/onchain-deploy.js+++ b/api/_lib/onchain-deploy.js@@ -37,6 +37,7 @@ import { solanaConnection } from './solana/connection.js';import { generateSolanaAgentWallet } from './agent-wallet.js';import { publishFeedEvent } from './feed.js';import { pinToIPFS } from './ipfs-pin.js';+import { register8004Agent, registrationEnabled as registry8004Enabled } from './solana-8004.js';// Genesis-hash chain refs (CAIP-2), mirroring api/agents/onchain/[action].js.export const SOLANA_REFS = {@@ -487,6 +488,20 @@ export async function registerAgentOnce({ umi, authoritySigner, agent, asset, co)`.catch(() => {});+ // Enrol in the open 8004 registry too, on the same authority-managed path. The+ // Metaplex identity above is already persisted, so a failure here is reported+ // and left for the back-fill rather than unwinding it.+ let registry8004 = null;+ if (registry8004Enabled(network)) {+ try {+ const r = await register8004Agent({ agent: { ...agent, meta: { ...current, ...(isMainnet ? {} : { devnet: current.devnet }) } }, network });+ registry8004 = { asset: r.asset, signature: r.signature, alreadyRegistered: r.alreadyRegistered };+ onEvent?.('registry_8004', { agent_id: agent.id, asset: r.asset, signature: r.signature, already_registered: r.alreadyRegistered });+ } catch (err) {+ onEvent?.('registry_8004_error', { agent_id: agent.id, name: agentName, error: err.message });+ }+ }+onEvent?.('registered', {agent_id: agent.id,name: agentName,@@ -497,5 +512,5 @@ export async function registerAgentOnce({ umi, authoritySigner, agent, asset, coexplorer_url: explorerUrl(identityPda, network),});- return { asset: resolvedAsset, identityPda, registrationUri, signature, alreadyRegistered };+ return { asset: resolvedAsset, identityPda, registrationUri, signature, alreadyRegistered, registry8004 };}diff --git a/api/_lib/solana-8004.js b/api/_lib/solana-8004.jsnew file mode 100644index 000000000..535c1ca2c--- /dev/null+++ b/api/_lib/solana-8004.js@@ -0,0 +1,405 @@+// Open Solana agent registry (8004): registration and standing reads.+// ---------------------------------------------------------------------------+// The 8004 registry is the Solana port of the ERC-8004 agent identity standard:+// every registered agent is a Metaplex Core asset owned by the registry program+// family, with a feedback ledger and an ATOM engine that turns feedback into a+// sybil-resistant trust tier (Unrated, Bronze, Silver, Gold, Platinum).+//+// This module owns two things, both through the published `8004-solana` SDK:+//+// 1. WRITE. `register8004Agent` enrols an agent with the same authority-managed+// flow as the Metaplex identity step in `onchain-deploy.js`: the platform+// authority key signs and pays, the agent owner never signs and needs no+// SOL. The registration URI is the agent's live, mutable registration+// document, so its services and model stay accurate after enrolment. The+// registry asset address is stored on the agent row at+// `meta.registry_8004` (mainnet) or `meta.devnet.registry_8004` (devnet).+//+// 2. READ. `read8004Standing` reads any registry asset's trust tier and+// feedback score straight from chain. Reads never need a key and never+// throw: an unreachable RPC is reported as `unavailable`, never as an+// unrated agent, so a hiring agent cannot mistake an outage for a verdict.+//+// Mainnet writes spend authority SOL, so they are opt-in: set+// SOLANA_8004_REGISTER_MAINNET=1. Devnet writes are always allowed.++import bs58 from 'bs58';+import { Keypair } from '@solana/web3.js';+import { sql } from './db.js';+import { env } from './env.js';+import { solanaRpcEndpoints } from './solana/connection.js';++export const TIER_NAMES = ['Unrated', 'Bronze', 'Silver', 'Gold', 'Platinum'];++/** Rough rent + fee for one registration (agent account + core asset + ATOM stats). */+export const EST_REGISTER_8004_LAMPORTS = 12_000_000;++/** A cached standing older than this is re-read from chain by the refresh job. */+export const STANDING_TTL_MS = 6 * 60 * 60 * 1000;++/** The funded platform authority secret (same key that mints and registers Core assets). */+function authoritySecret() {+ return process.env.SOLANA_AGENT_COLLECTION_AUTHORITY_KEY || process.env.LAUNCH_FUNDER_SECRET || null;+}++const READ_TIMEOUT_MS = 8_000;++let _sdkModule = null;+async function sdkModule() {+ if (!_sdkModule) _sdkModule = await import('8004-solana');+ return _sdkModule;+}++/** 8004 SDK cluster name for one of our network names. */+export function clusterFor(network) {+ return network === 'devnet' ? 'devnet' : 'mainnet-beta';+}++/** Program ids for the registry on this network (primary source: the published SDK). */+export async function registryProgramIds(network) {+ const { getProgramIds } = await sdkModule();+ const ids = getProgramIds(clusterFor(network));+ return {+ registry: ids.agentRegistry.toBase58(),+ atomEngine: ids.atomEngine.toBase58(),+ mplCore: ids.mplCore.toBase58(),+ };+}++/** Whether this process may sign a registration on `network`. */+export function registrationEnabled(network, e = process.env) {+ if (network === 'devnet') return true;+ return e.SOLANA_8004_REGISTER_MAINNET === '1';+}++/** Where an agent's registry block lives inside `meta` for a network. */+export function registryBlockOf(meta, network) {+ const m = meta || {};+ return (network === 'devnet' ? m.devnet?.registry_8004 : m.registry_8004) || null;+}++/** The registry block for whichever network the agent is registered on (mainnet wins). */+export function anyRegistryBlock(meta) {+ const main = registryBlockOf(meta, 'mainnet');+ if (main?.asset) return { ...main, network: 'mainnet' };+ const dev = registryBlockOf(meta, 'devnet');+ if (dev?.asset) return { ...dev, network: 'devnet' };+ return null;+}++/** Numeric rank of a tier name, for ordering. Unknown and missing rank 0. */+export function tierRank(name) {+ const i = TIER_NAMES.indexOf(name);+ return i < 0 ? 0 : i;+}++function rpcUrlFor(network) {+ return solanaRpcEndpoints(network === 'devnet' ? 'devnet' : 'mainnet')[0] || undefined;+}++/** Build an SDK instance. Read-only unless a keypair is given. */+export async function build8004Sdk(network, { signer = null, rpcUrl = null } = {}) {+ const { SolanaSDK } = await sdkModule();+ return new SolanaSDK({+ cluster: clusterFor(network),+ rpcUrl: rpcUrl || rpcUrlFor(network),+ ...(signer ? { signer } : {}),+ // Standing must reflect chain state, not a third-party indexer's lag.+ useIndexer: false,+ forceOnChain: true,+ });+}++function withTimeout(promise, ms, label) {+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}++/**+ * Read one registry asset's standing from chain.+ *+ * @returns {Promise<{+ * registered: boolean, unavailable?: boolean, error?: string,+ * asset: string, network: string,+ * tier?: string, tier_rank?: number,+ * average_score?: number|null, total_feedbacks?: number,+ * quality_score?: number|null, confidence?: number|null, risk_score?: number|null,+ * unique_clients?: number|null, checked_at: string+ * }>}+ */+export async function read8004Standing(asset, network, { sdk = null } = {}) {+ const checked_at = new Date().toISOString();+ const base = { asset, network, checked_at };+ try {+ const { PublicKey } = await import('@solana/web3.js');+ const s = sdk || (await build8004Sdk(network));+ const pk = new PublicKey(asset);+ const account = await withTimeout(s.loadAgent(pk), READ_TIMEOUT_MS, 'loadAgent');+ if (!account) return { ...base, registered: false };++ const [tier, summary, enriched] = await Promise.all([+ withTimeout(s.getTrustTier(pk), READ_TIMEOUT_MS, 'getTrustTier').catch(() => 0),+ withTimeout(s.getSummary(pk), READ_TIMEOUT_MS, 'getSummary').catch(() => null),+ withTimeout(s.getEnrichedSummary(pk), READ_TIMEOUT_MS, 'getEnrichedSummary').catch(() => null),+ ]);+ const rank = Number(tier) || 0;+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);+ return {+ ...base,+ registered: true,+ tier: TIER_NAMES[rank] || 'Unrated',+ tier_rank: rank,+ average_score: num(summary?.averageScore),+ total_feedbacks: Number(summary?.totalFeedbacks ?? enriched?.totalFeedbacks ?? 0),+ quality_score: num(enriched?.qualityScore),+ confidence: num(enriched?.confidence),+ risk_score: num(enriched?.riskScore),+ unique_clients: num(enriched?.uniqueCallers),+ };+ } catch (err) {+ return { ...base, registered: false, unavailable: true, error: String(err?.message || err).slice(0, 200) };+ }+}++/** Reduce a standing to the compact snapshot stored beside the registry address. */+export function standingSnapshot(standing) {+ if (!standing?.registered) return null;+ return {+ tier: standing.tier,+ tier_rank: standing.tier_rank,+ average_score: standing.average_score,+ total_feedbacks: standing.total_feedbacks,+ checked_at: standing.checked_at,+ };+}++async function writeBlock(agentId, network, block) {+ const json = JSON.stringify(block);+ if (network === 'devnet') {+ await sql`+ UPDATE agent_identities+ SET meta = jsonb_set(+ meta,+ '{devnet}',+ COALESCE(meta->'devnet', '{}'::jsonb) || jsonb_build_object('registry_8004', ${json}::jsonb)+ ), updated_at = NOW()+ WHERE id = ${agentId}+ `;+ } else {+ await sql`+ UPDATE agent_identities+ SET meta = jsonb_set(meta, '{registry_8004}', ${json}::jsonb), updated_at = NOW()+ WHERE id = ${agentId}+ `;+ }+}++/**+ * Enrol an agent in the 8004 registry. Idempotent: an agent whose stored asset+ * still resolves on chain is returned as-is without a transaction.+ *+ * @param {object} p+ * @param {{id: string, name?: string, meta?: object}} p.agent+ * @param {'mainnet'|'devnet'} p.network+ * @param {Keypair} [p.keypair] defaults to the platform authority+ * @param {object} [p.sdk] injected for tests+ * @returns {Promise<{asset: string, signature: string|null, alreadyRegistered: boolean, registrationUri: string, block: object}>}+ */+export async function register8004Agent({ agent, network, keypair = null, sdk = null }) {+ if (!registrationEnabled(network)) {+ throw new Error('mainnet 8004 registration is off: set SOLANA_8004_REGISTER_MAINNET=1 to enable it');+ }+ const existing = registryBlockOf(agent.meta, network);+ const registrationUri = `${env.APP_ORIGIN}/api/agents/${agent.id}/registration`;++ let signer = keypair;+ if (!signer && !sdk) {+ const secret = authoritySecret();+ if (!secret) {+ throw new Error('Set SOLANA_AGENT_COLLECTION_AUTHORITY_KEY (or LAUNCH_FUNDER_SECRET) to the funded authority wallet secret.');+ }+ signer = Keypair.fromSecretKey(bs58.decode(secret));+ }+ const s = sdk || (await build8004Sdk(network, { signer }));++ if (existing?.asset) {+ const { PublicKey } = await import('@solana/web3.js');+ const live = await s.loadAgent(new PublicKey(existing.asset));+ if (live) {+ return { asset: existing.asset, signature: null, alreadyRegistered: true, registrationUri: existing.registration_uri || registrationUri, block: existing };+ }+ }++ const result = await s.registerAgent(registrationUri, { atomEnabled: true });+ if (!result?.asset) {+ throw new Error(`8004 registerAgent returned no asset${result?.error ? `: ${result.error}` : ''}`);+ }+ const asset = result.asset.toBase58();+ const signature = result.signature || result.signatures?.[0] || null;+ const { getProgramIds } = await sdkModule();+ const ids = getProgramIds(clusterFor(network));++ const block = {+ standard: '8004-solana',+ program: ids.agentRegistry.toBase58(),+ asset,+ registration_uri: registrationUri,+ authority: signer ? signer.publicKey.toBase58() : null,+ network,+ ...(signature ? { tx_hash: signature } : {}),+ registered_at: new Date().toISOString(),+ };+ await writeBlock(agent.id, network, block);++ await sql`+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)+ VALUES (${agent.id}, ${'solana.register_8004'},+ ${JSON.stringify({ asset, network, signature, program: block.program })}::jsonb,+ ${'registry_8004'})+ `.catch(() => {});++ return { asset, signature, alreadyRegistered: false, registrationUri, block };+}++/**+ * Re-read one agent's standing and store the snapshot beside its registry block.+ * Returns the live standing. An unreachable RPC leaves the stored snapshot alone.+ */+export async function refresh8004Standing({ agent, network, sdk = null }) {+ const block = registryBlockOf(agent.meta, network);+ if (!block?.asset) return null;+ const standing = await read8004Standing(block.asset, network, { sdk });+ if (standing.unavailable) return standing;+ await writeBlock(agent.id, network, { ...block, standing: standingSnapshot(standing) });+ return standing;+}++/**+ * Agents minted on this network that have no 8004 registration yet, oldest first.+ * Only agents that already hold a Core asset qualify, mirroring the Metaplex+ * back-fill, so the registry is never populated with empty shells.+ */+export async function fetchUnregistered8004(network, limit) {+ return network === 'mainnet'+ ? sql`+ SELECT id, user_id, name, description, meta FROM agent_identities+ WHERE deleted_at IS NULL+ AND meta->>'sol_mint_address' IS NOT NULL+ AND meta->'registry_8004'->>'asset' IS NULL+ ORDER BY created_at ASC LIMIT ${limit}`+ : sql`+ SELECT id, user_id, name, description, meta FROM agent_identities+ WHERE deleted_at IS NULL+ AND meta->'devnet'->>'sol_mint_address' IS NOT NULL+ AND meta->'devnet'->'registry_8004'->>'asset' IS NULL+ ORDER BY created_at ASC LIMIT ${limit}`;+}++/** Registered agents whose cached standing is missing or older than the TTL. */+export async function fetchStale8004(network, limit, ttlMs = STANDING_TTL_MS) {+ const cutoff = new Date(Date.now() - ttlMs).toISOString();+ return network === 'mainnet'+ ? sql`+ SELECT id, name, meta FROM agent_identities+ WHERE deleted_at IS NULL+ AND meta->'registry_8004'->>'asset' IS NOT NULL+ AND COALESCE(meta->'registry_8004'->'standing'->>'checked_at', '') < ${cutoff}+ ORDER BY COALESCE(meta->'registry_8004'->'standing'->>'checked_at', '') ASC LIMIT ${limit}`+ : sql`+ SELECT id, name, meta FROM agent_identities+ WHERE deleted_at IS NULL+ AND meta->'devnet'->'registry_8004'->>'asset' IS NOT NULL+ AND COALESCE(meta->'devnet'->'registry_8004'->'standing'->>'checked_at', '') < ${cutoff}+ ORDER BY COALESCE(meta->'devnet'->'registry_8004'->'standing'->>'checked_at', '') ASC LIMIT ${limit}`;+}++/**+ * One back-fill pass: register up to `limit` unregistered agents, then refresh+ * stale standings. Sequential with a pause between registrations so the+ * authority wallet and the RPC are never hammered. Returns a per-agent log.+ */+export async function runBackfill8004({ network, limit = 5, pauseMs = 750, register = true, refresh = true, keypair = null, sdk = null, onEvent = null }) {+ const out = { network, registered: [], already: [], refreshed: [], errors: [] };+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+ if (register && registrationEnabled(network)) {+ for (const agent of await fetchUnregistered8004(network, limit)) {+ try {+ const r = await register8004Agent({ agent, network, keypair, sdk });+ (r.alreadyRegistered ? out.already : out.registered).push({ agent_id: agent.id, asset: r.asset, signature: r.signature });+ onEvent?.('registered', { agent_id: agent.id, asset: r.asset, signature: r.signature });+ } catch (err) {+ out.errors.push({ agent_id: agent.id, error: err.message });+ onEvent?.('error', { agent_id: agent.id, error: err.message });+ }+ await sleep(pauseMs);+ }+ }+ if (refresh) {+ for (const agent of await fetchStale8004(network, limit * 4)) {+ const st = await refresh8004Standing({ agent, network, sdk }).catch(() => null);+ if (st && !st.unavailable) out.refreshed.push({ agent_id: agent.id, tier: st.tier });+ }+ }+ return out;+}++/**+ * The public, non-sensitive view of a stored registry block, with its cached+ * standing. This is what catalogs, agent cards and hire responses carry.+ * Returns null when the agent is not registered (so callers render nothing).+ */+export function publicRegistry8004(block, network = block?.network || 'mainnet') {+ if (!block?.asset) return null;+ const st = block.standing || null;+ const suffix = network === 'devnet' ? '?cluster=devnet' : '';+ return {+ asset: block.asset,+ program: block.program || null,+ network,+ tier: st?.tier || null,+ tier_rank: st ? tierRank(st.tier) : null,+ average_score: st?.average_score ?? null,+ total_feedbacks: st?.total_feedbacks ?? null,+ checked_at: st?.checked_at || null,+ explorer_url: `https://solscan.io/account/${block.asset}${suffix}`,+ };+}++/**+ * Replace a cached registry view with a live chain read. When the chain cannot be+ * reached the cached view is kept and flagged `stale`, so a hire is never decided+ * on a silently missing signal.+ */+export async function liveRegistry8004(view, { sdk = null } = {}) {+ if (!view?.asset) return view;+ const live = await read8004Standing(view.asset, view.network, { sdk });+ if (live.unavailable) return { ...view, stale: true };+ if (!live.registered) return { ...view, tier: null, tier_rank: null, average_score: null, total_feedbacks: null, checked_at: live.checked_at, registered: false };+ return {+ ...view,+ registered: true,+ tier: live.tier,+ tier_rank: live.tier_rank,+ average_score: live.average_score,+ total_feedbacks: live.total_feedbacks,+ checked_at: live.checked_at,+ stale: false,+ };+}++/** Parse a caller-supplied minimum tier name (case-insensitive). Null when absent, throws on junk. */+export function parseMinTier(value) {+ if (value == null || value === '') return null;+ const i = TIER_NAMES.findIndex((n) => n.toLowerCase() === String(value).toLowerCase());+ if (i < 0) throw new RangeError(`minRegistryTier must be one of ${TIER_NAMES.join(', ')}`);+ return i;+}++/** True when a registry view meets a minimum tier rank. */+export function meetsMinTier(view, minRank) {+ if (minRank == null || minRank <= 0) return true;+ return (view?.tier_rank ?? 0) >= minRank;+}diff --git a/api/agents/a2a-hire.js b/api/agents/a2a-hire.jsindex ed8cccc08..9b51d44a2 100644--- a/api/agents/a2a-hire.js+++ b/api/agents/a2a-hire.js@@ -31,6 +31,7 @@ import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';import { limits } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';import { randomUUID } from 'node:crypto';+import { liveRegistry8004, meetsMinTier, parseMinTier } from '../_lib/solana-8004.js';import {SpendLimitError,@@ -115,7 +116,7 @@ export default wrap(async (req, res) => {if (!rl.success) return rateLimited(res, rl, 'hire rate limit exceeded');const body = (await readJson(req)) || {};- const { hirerAgentId, serviceSlug, input = null, maxUsd } = body;+ const { hirerAgentId, serviceSlug, input = null, maxUsd, minRegistryTier = null } = body;const idempotencyKey = body.idempotencyKey || randomUUID();if (!hirerAgentId || typeof hirerAgentId !== 'string') {@@ -187,6 +188,18 @@ export default wrap(async (req, res) => {return error(res, 400, 'self_hire', 'an agent cannot hire its own service');}+ // Open Solana agent registry standing: read live from the chain, falling back to+ // the stored snapshot (flagged stale) when the RPC is unreachable.+ let minTierRank;+ try {+ minTierRank = parseMinTier(minRegistryTier);+ } catch (e) {+ return error(res, 400, 'validation_error', e.message);+ }+ if (offer.provider.registry_8004) {+ offer.provider.registry_8004 = await liveRegistry8004(offer.provider.registry_8004);+ }+const usd = atomicsToUsdc(offer.price_atomics);const priceNetwork = offer.network === 'solana' ? 'solana' : 'base';@@ -212,6 +225,13 @@ export default wrap(async (req, res) => {});}+ if (!meetsMinTier(offer.provider.registry_8004, minTierRank)) {+ return error(res, 409, 'provider_below_tier', `this provider is below the requested registry tier (${minRegistryTier})`, {+ required_tier: minRegistryTier,+ provider_tier: offer.provider.registry_8004?.tier || 'Unrated',+ });+ }+// Every hire pays mainnet USDC from the hirer's custodial wallet, so the caller// must have signed the real-funds agreements before any hire is recorded or// any spend is reserved.diff --git a/data/changelog.json b/data/changelog.jsonindex 8d1f792ec..0e344f8d0 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,17 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-24",+ "title": "Agents join the open Solana agent registry and hires read trust tiers",+ "summary": "Minted agents are enrolled in the open Solana agent registry (8004) with the platform authority signing, so owners pay nothing. The marketplace ranks providers by registry tier after completed hires, a hire can require a minimum tier, and agent pages show an 8004 tier badge when registered. A rate-limited back-fill covers existing agents.",+ "tags": [+ "solana",+ "agents",+ "marketplace"+ ],+ "link": "/docs/solana-agent-registry"+ },{"date": "2026-10-24","title": "Engine bridges are packaged for the Unity, Godot and Unreal stores",diff --git a/data/pages.json b/data/pages.jsonindex 1436432ad..56a44f38e 100644--- a/data/pages.json+++ b/data/pages.json@@ -4082,6 +4082,14 @@"changefreq": "monthly","added": "2026-08-14"},+ {+ "path": "/docs/solana-agent-registry",+ "title": "Docs · Solana Agent Registry",+ "description": "Agents are enrolled in the open Solana agent registry (8004) with the platform authority signing, and hires read the provider's trust tier: registration, storage, ranking, the minimum-tier guard, the back-fill and the devnet proof.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-10-24"+ },{"path": "/docs/selfie-to-avatar","title": "Docs · Selfie to Avatar",diff --git a/docs/solana-agent-registry.md b/docs/solana-agent-registry.mdnew file mode 100644index 000000000..f39590e42--- /dev/null+++ b/docs/solana-agent-registry.md@@ -0,0 +1,56 @@+# Open Solana agent registry (8004)++three.ws enrols agents in the open Solana agent registry, the Solana port of ERC-8004, and reads other agents' trust tiers when one agent hires another. It sits beside the Metaplex agent identity three.ws already writes, and beside the Trader Passport.++## What was verified++| Item | Value |+|---|---|+| SDK | `8004-solana` 0.8.5, MIT licence, adopted as a dependency |+| Registry program (mainnet) | resolved at runtime from the SDK (`getProgramIds('mainnet-beta')`) |+| Registry program (devnet) | `8oo4J9tBB3Hna1jRQ3rWvJjojqM5DYTDJo5cejUuJy3C` |+| ATOM engine (trust tiers) | `AToMufS4QD6hEXvcvBDg9m1AHeCLpmZQsyfYa5h9MwAF` |+| Tiers | Unrated, Bronze, Silver, Gold, Platinum |++The SDK imports `@noble/curves/ed25519`, which curves 2.x only exports with a `.js` suffix. `scripts/fix-8004-solana-esm.mjs` patches that import on install (idempotent, wired into `postinstall`).++## Registration++`api/_lib/solana-8004.js` `register8004Agent` calls the SDK `registerAgent` with the agent's registration document (`/api/agents/<id>/registration`) and ATOM enabled. The platform authority key signs and pays, so owners never sign and need no SOL, the same custody as the mint and `registerIdentityV1`. `registerAgentOnce` in `api/_lib/onchain-deploy.js` runs it right after the Metaplex registration. A failure there never fails the mint.++The result is stored on the agent row:++| Network | Location |+|---|---|+| mainnet | `agent_identities.meta.registry_8004` |+| devnet | `agent_identities.meta.devnet.registry_8004` |++Fields: `standard`, `program`, `asset`, `registration_uri`, `authority`, `network`, `tx_hash`, `registered_at`, and a cached `standing` snapshot (`tier`, `tier_rank`, `average_score`, `total_feedbacks`, `checked_at`).++Devnet registration is always on. Mainnet registration spends authority SOL (about 0.012 SOL per agent) and is opt-in: set `SOLANA_8004_REGISTER_MAINNET=1`.++## Reading trust tiers++- `GET /api/agents/offers` and the slug lookup carry `provider.registry_8004` (asset, program, tier, score, feedback count, explorer link) for providers registered on mainnet, or `null`.+- The catalog ranks by completed hires, then by registry tier, then by recency.+- `POST /api/agents/a2a-hire` reads the provider's standing live from the chain before spending, falling back to the stored snapshot flagged `stale: true` when the RPC is unreachable. An outage is never reported as Unrated.+- Optional body field `minRegistryTier` (`Bronze`, `Silver`, `Gold`, `Platinum`) rejects a hire with `409 provider_below_tier` before any spend reservation.+- The agent page shows an `8004 <Tier>` pill next to the trust pills when the agent is registered (a devnet registration is labelled "devnet"), and nothing otherwise.++ATOM scores ramp slowly by design (anti-sybil), so a freshly registered agent reads Unrated until it has feedback from distinct clients.++## Back-fill++```+node --env-file=.env scripts/register-8004-agents.mjs --network devnet --limit 5 --dry-run+node --env-file=.env scripts/register-8004-agents.mjs --network devnet --limit 5 --confirm+SOLANA_8004_REGISTER_MAINNET=1 node --env-file=.env scripts/register-8004-agents.mjs --network mainnet --limit 5 --confirm+```++It registers minted agents that have no registry asset (sequentially, 750 ms apart) and refreshes cached standings older than six hours. `--refresh-only` skips registration. Re-runs are safe.++## Proof and tests++- `node scripts/prove-8004-registry.mjs` registers an agent with throwaway devnet keys, leaves feedback from a second wallet and reads the tier back. It refuses any non-devnet RPC.+- `tests/solana-8004.test.js` covers blocks, gating, reads, outage handling and idempotent registration with an injected SDK.+- `RUN_DEVNET_8004=1 npx vitest run tests/solana-8004.devnet.test.js` runs the live devnet round trip.diff --git a/package-lock.json b/package-lock.jsonindex 26f28499c..619d574fe 100644--- a/package-lock.json+++ b/package-lock.json@@ -86,6 +86,7 @@"packages/skill-import"],"dependencies": {+ "8004-solana": "^0.8.5","@0xsplits/splits-sdk": "^6.6.0","@ai-sdk/anthropic": "^4.0.53","@ai-sdk/openai": "^4.0.96",@@ -42174,6 +42175,71 @@"node": ">=20.0.0"}},+ "node_modules/8004-solana": {+ "version": "0.8.5",+ "resolved": "https://registry.npmjs.org/8004-solana/-/8004-solana-0.8.5.tgz",+ "integrity": "sha512-THzvK8is21N+Yom1sSaUhMig/KAyQDMAFhof12xQqtM5Eey4q0HBbPIusMEgtDadZHgo/m9jKnlkOhcI0Vsnrg==",+ "license": "MIT",+ "dependencies": {+ "@coral-xyz/borsh": "^0.32.1",+ "@noble/hashes": "^2.0.1",+ "@solana/web3.js": "^1.99.0",+ "borsh": "^0.7.0",+ "bs58": "^6.0.0",+ "tweetnacl": "^1.0.3"+ },+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/8004-solana/node_modules/@coral-xyz/borsh": {+ "version": "0.32.1",+ "resolved": "https://registry.npmjs.org/@coral-xyz/borsh/-/borsh-0.32.1.tgz",+ "integrity": "sha512-pWsqkkZ+psLlupMkgu5rDok7baDQLWKqyDsb76gUNArbVB783mF3ZOleKMHVXZczl5JuxnVVfO1+XDVvR17C3A==",+ "license": "Apache-2.0",+ "dependencies": {+ "bn.js": "^5.1.2",+ "buffer-layout": "^1.2.0"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "@solana/web3.js": "^1.69.0"+ }+ },+ "node_modules/8004-solana/node_modules/@noble/hashes": {+ "version": "2.4.0",+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",+ "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",+ "license": "MIT",+ "engines": {+ "node": ">= 20.19.0"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/8004-solana/node_modules/borsh": {+ "version": "0.7.0",+ "resolved": "https://registry.npmjs.org/borsh/-/borsh-0.7.0.tgz",+ "integrity": "sha512-CLCsZGIBCFnPtkNnieW/a8wmreDmfUtjU2m9yHrzPXIlNbqVs0AQrSatSG6vdNYUqdc83tkQi2eHfF98ubzQLA==",+ "license": "Apache-2.0",+ "dependencies": {+ "bn.js": "^5.2.0",+ "bs58": "^4.0.0",+ "text-encoding-utf-8": "^1.0.2"+ }+ },+ "node_modules/8004-solana/node_modules/borsh/node_modules/bs58": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/bs58/-/bs58-4.0.1.tgz",+ "integrity": "sha512-Ok3Wdf5vOIlBrgCvTq96gBkJw+JUEzdBgyaza5HLtPm7yTHkjRy8+JzNyHF7BHa0bNWOQIp3m5YF0nnFcOIKLw==",+ "license": "MIT",+ "dependencies": {+ "base-x": "^3.0.2"+ }+ },"node_modules/abitype": {"version": "1.0.6","resolved": "https://registry.npmjs.org/abitype/-/abitype-1.0.6.tgz",diff --git a/package.json b/package.jsonindex 93f0f55d8..1b1368f78 100644--- a/package.json+++ b/package.json@@ -156,7 +156,7 @@]},"scripts": {- "postinstall": "(node scripts/build-cache.mjs check agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json || (npm run build --prefix agent-payments-sdk && node scripts/build-cache.mjs stamp agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json)) && (node scripts/build-cache.mjs check solana-agent-sdk solana-agent-sdk/src solana-agent-sdk/package.json || (npm run build:dist --prefix solana-agent-sdk && node scripts/build-cache.mjs stamp solana-agent-sdk solana-agent-sdk/src solana-agent-sdk/package.json)) && (node scripts/build-cache.mjs check walk-sdk walk-sdk/src walk-sdk/package.json || (npm run build --prefix walk-sdk && node scripts/build-cache.mjs stamp walk-sdk walk-sdk/src walk-sdk/package.json)) && (node scripts/fix-pump-sdk-esm.mjs & node scripts/fix-x402-extensions-esm.mjs & node scripts/fix-zauth-sdk-solana-esm.mjs & node scripts/fix-colyseus-storage.mjs & node scripts/fix-colyseus-send.mjs & node scripts/fix-rapier-init-warning.mjs & node scripts/copy-three-decoders.mjs & node scripts/copy-voice-models.mjs & node scripts/setup-claude-skills.mjs & node scripts/setup-git-hooks.mjs & node scripts/build-docs-search-index.mjs & wait)",+ "postinstall": "(node scripts/build-cache.mjs check agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json || (npm run build --prefix agent-payments-sdk && node scripts/build-cache.mjs stamp agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json)) && (node scripts/build-cache.mjs check solana-agent-sdk solana-agent-sdk/src solana-agent-sdk/package.json || (npm run build:dist --prefix solana-agent-sdk && node scripts/build-cache.mjs stamp solana-agent-sdk solana-agent-sdk/src solana-agent-sdk/package.json)) && (node scripts/build-cache.mjs check walk-sdk walk-sdk/src walk-sdk/package.json || (npm run build --prefix walk-sdk && node scripts/build-cache.mjs stamp walk-sdk walk-sdk/src walk-sdk/package.json)) && (node scripts/fix-pump-sdk-esm.mjs & node scripts/fix-x402-extensions-esm.mjs & node scripts/fix-zauth-sdk-solana-esm.mjs & node scripts/fix-8004-solana-esm.mjs & node scripts/fix-colyseus-storage.mjs & node scripts/fix-colyseus-send.mjs & node scripts/fix-rapier-init-warning.mjs & node scripts/copy-three-decoders.mjs & node scripts/copy-voice-models.mjs & node scripts/setup-claude-skills.mjs & node scripts/setup-git-hooks.mjs & node scripts/build-docs-search-index.mjs & wait)","setup": "node scripts/setup-dev.mjs","dev": "vite --port 3000","dev:multi": "npm run dev --prefix multiplayer",@@ -583,6 +583,7 @@"vet:mcp-catalog": "node scripts/vet-mcp-integrations.mjs"},"dependencies": {+ "8004-solana": "^0.8.5","@0xsplits/splits-sdk": "^6.6.0","@ai-sdk/anthropic": "^4.0.53","@ai-sdk/openai": "^4.0.96",diff --git a/prompts/finish/_context/beat-PROGRESS.md b/prompts/finish/_context/beat-PROGRESS.mdindex 0f7b9926f..8213d52d7 100644--- a/prompts/finish/_context/beat-PROGRESS.md+++ b/prompts/finish/_context/beat-PROGRESS.md@@ -19,3 +19,4 @@ Append one dated entry per finished or partially finished order: order number, c- 2026-10-23: order 608 (MPP on Solana) done in c28db0aa. One URL answers both x402 and MPP Payment challenges, buyerFetch pays either with caps and a dryRun quote, 15 tests in tests/mpp-solana.test.js including CLI interop and a cap block, docs/mpp-solana.md. Owner (gate 1): real mainnet settlement is not run; command is `three-ws pay https://three.ws/api/x402/gas-oracle --max 0.002`.- 2026-10-23: order 609 (one definition, many rails) done in 8d56cd92. Dry-run quote is identical on x402, mpp, a2a and ap2 (10000 / 9750 / 250), disabling a rail 404s, 22 tests in tests/skill-rails.test.js, docs/skill-rails.md. The publish UI rail checkboxes already existed.- 2026-10-24: order 624 (installable skills repository) done. Spec validator (`npm run check:skills-spec`), clean-directory install test (`npm run test:skills-install`, `npx skills add` lists and installs 20/20, 6/6, 14/14), 21 skills' frontmatter fixed, `npx skills add` install line in the generated repo READMEs, listing copy in docs/skill-directory-listings.md. Remaining, owner-gated (gate 2): publishing the three repos and posting listings; commands print from `npm run build:skill-repos`. Commit: see git log subject 'feat(skills)'.+- 2026-10-24: order 622 (Solana agent registry) built, PARTIAL. Registration beside registerIdentityV1, registry block on the agent row, live tier read and minRegistryTier guard in a2a-hire, tier tie-break in offer ranking, agent-page badge, rate-limited back-fill (scripts/register-8004-agents.mjs), docs/solana-agent-registry.md, 15 unit tests. Round trip (register, feedback, tier read) proven on a local validator that cloned the devnet registry programs. Remaining: rerun scripts/prove-8004-registry.mjs against public devnet once the faucet limit (429) clears (owner: any session with a funded devnet key); mainnet back-fill is gate 1 (SOLANA_8004_REGISTER_MAINNET=1 and --confirm). Commit: see git log subject 'feat(solana)'.diff --git a/scripts/fix-8004-solana-esm.mjs b/scripts/fix-8004-solana-esm.mjsnew file mode 100644index 000000000..891e8a2a6--- /dev/null+++ b/scripts/fix-8004-solana-esm.mjs@@ -0,0 +1,32 @@+// Patches 8004-solana after install so it resolves under @noble/curves 2.x.+//+// The SDK's signing helper imports `@noble/curves/ed25519` (extensionless), a+// subpath that only @noble/curves 1.x exports. This repo hoists @noble/curves+// 2.x (shared by the Solana kit tree), whose export map only lists+// `./ed25519.js`, so importing the SDK throws ERR_PACKAGE_PATH_NOT_EXPORTED at+// load time. Both majors export the same `ed25519` binding from that file, so+// pointing the specifier at the `.js` subpath is behavior-neutral.+//+// Idempotent (the rewritten specifier no longer matches) and wired into the+// postinstall chain so it survives `npm ci`.++import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++const repo = dirname(dirname(fileURLToPath(import.meta.url)));+const file = join(repo, 'node_modules/8004-solana/dist/utils/signing.js');++if (!existsSync(file)) {+ console.log('[fix-8004-solana-esm] package not installed, skipping');+ process.exit(0);+}++const src = readFileSync(file, 'utf8');+const out = src.replace(/(['"])@noble\/curves\/ed25519\1/g, "'@noble/curves/ed25519.js'");+if (out === src) {+ console.log('[fix-8004-solana-esm] already patched');+} else {+ writeFileSync(file, out);+ console.log('[fix-8004-solana-esm] pointed @noble/curves/ed25519 at the .js subpath');+}diff --git a/scripts/prove-8004-registry.mjs b/scripts/prove-8004-registry.mjsnew file mode 100644index 000000000..15e44073c--- /dev/null+++ b/scripts/prove-8004-registry.mjs@@ -0,0 +1,76 @@+#!/usr/bin/env node+// Devnet proof for the open Solana agent registry (api/_lib/solana-8004.js).+//+// With throwaway keypairs it registers an agent through the same SDK path the+// platform authority uses, has a second wallet leave feedback, then reads the+// agent back and prints its trust tier and score. No database, no real funds.+// Refuses to run against anything but devnet (a local validator that cloned the+// registry programs from devnet is accepted with LOCAL_VALIDATOR=1).+//+// node scripts/prove-8004-registry.mjs+// DEVNET_RPC_URL=https://... node scripts/prove-8004-registry.mjs++import { Connection, Keypair, LAMPORTS_PER_SOL, SystemProgram, Transaction, sendAndConfirmTransaction } from '@solana/web3.js';+import { build8004Sdk, read8004Standing, registryProgramIds } from '../api/_lib/solana-8004.js';++const RPC = process.env.DEVNET_RPC_URL || 'https://api.devnet.solana.com';+const DEVNET_GENESIS = 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG';+const local = process.env.LOCAL_VALIDATOR === '1' && /^http:\/\/(127\.0\.0\.1|localhost)/.test(RPC);+const conn = new Connection(RPC, 'confirmed');++if (!local && (await conn.getGenesisHash()) !== DEVNET_GENESIS) {+ console.error('refusing to run: the RPC is not devnet');+ process.exit(2);+}++async function fund(kp, sol) {+ for (let attempt = 0; attempt < 4; attempt++) {+ try {+ const sig = await conn.requestAirdrop(kp.publicKey, Math.round(sol * LAMPORTS_PER_SOL));+ const bh = await conn.getLatestBlockhash();+ await conn.confirmTransaction({ signature: sig, ...bh }, 'confirmed');+ return;+ } catch (e) {+ if (attempt === 3) throw e;+ await new Promise((r) => setTimeout(r, 2500 * (attempt + 1)));+ }+ }+}++const ids = await registryProgramIds('devnet');+console.log('registry program:', ids.registry);+console.log('atom engine :', ids.atomEngine);++const authority = Keypair.generate();+const reviewer = Keypair.generate();+await fund(authority, 1);+if (process.env.FUND_REVIEWER_FROM_AUTHORITY === '1') {+ const tx = new Transaction().add(+ SystemProgram.transfer({ fromPubkey: authority.publicKey, toPubkey: reviewer.publicKey, lamports: 0.1 * LAMPORTS_PER_SOL }),+ );+ await sendAndConfirmTransaction(conn, tx, [authority]);+} else {+ await fund(reviewer, 1);+}++const sdk = await build8004Sdk('devnet', { signer: authority, rpcUrl: RPC });+const uri = `https://three.ws/api/agents/00000000-0000-4000-8000-000000000000/registration`;+const reg = await sdk.registerAgent(uri, { atomEnabled: true });+const asset = reg.asset.toBase58();+console.log('\nregistered asset :', asset);+console.log('register tx :', reg.signature);++const before = await read8004Standing(asset, 'devnet', { sdk });+console.log('standing (new) :', JSON.stringify(before));++const reviewerSdk = await build8004Sdk('devnet', { signer: reviewer, rpcUrl: RPC });+const fb = await reviewerSdk.giveFeedback(reg.asset, { value: '90', score: 90, tag1: 'quality', feedbackUri: '' });+console.log('feedback tx :', fb.signature);++const after = await read8004Standing(asset, 'devnet', { sdk });+console.log('standing (after) :', JSON.stringify(after));+if (!after.registered || after.total_feedbacks < 1) {+ console.error('read-back did not show the feedback');+ process.exit(1);+}+console.log('\nOK');diff --git a/scripts/register-8004-agents.mjs b/scripts/register-8004-agents.mjsnew file mode 100644index 000000000..c9ce4ded9--- /dev/null+++ b/scripts/register-8004-agents.mjs@@ -0,0 +1,86 @@+#!/usr/bin/env node+/**+ * Back-fill: enrol already-minted three.ws agents in the open Solana agent+ * registry (8004) and refresh the cached trust tier of registered ones.+ * ---------------------------------------------------------------------------+ * The platform authority key signs and pays, so agent owners never sign. The run+ * is rate limited (one registration at a time with a pause) and idempotent:+ * agents that already hold a registry asset are skipped.+ *+ * Usage (env comes from .env via Node's --env-file):+ * # preview, no SOL and no writes:+ * node --env-file=.env scripts/register-8004-agents.mjs --network devnet --limit 5 --dry-run+ *+ * # real devnet run:+ * node --env-file=.env scripts/register-8004-agents.mjs --network devnet --limit 5 --confirm+ *+ * # real mainnet run (spends authority SOL; also needs SOLANA_8004_REGISTER_MAINNET=1):+ * SOLANA_8004_REGISTER_MAINNET=1 node --env-file=.env scripts/register-8004-agents.mjs --network mainnet --limit 5 --confirm+ *+ * Flags: --network devnet|mainnet, --limit N, --pause-ms N, --refresh-only, --dry-run, --confirm.+ */++import {+ EST_REGISTER_8004_LAMPORTS,+ fetchStale8004,+ fetchUnregistered8004,+ registrationEnabled,+ runBackfill8004,+} from '../api/_lib/solana-8004.js';++function arg(name, fallback) {+ const i = process.argv.indexOf(name);+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback;+}+const flag = (name) => process.argv.includes(name);++async function main() {+ const network = arg('--network', 'mainnet') === 'devnet' ? 'devnet' : 'mainnet';+ const limit = Math.min(500, Math.max(1, Number(arg('--limit', '5')) || 5));+ const pauseMs = Math.max(0, Number(arg('--pause-ms', '750')) || 0);+ const refreshOnly = flag('--refresh-only');+ const dryRun = flag('--dry-run');++ console.log('\nthree.ws open Solana agent registry (8004) back-fill');+ console.log(` network: ${network} limit: ${limit} ${dryRun ? 'DRY RUN' : 'LIVE'}`);++ if (!refreshOnly && !registrationEnabled(network)) {+ console.error('\nMainnet registration is off. Set SOLANA_8004_REGISTER_MAINNET=1 to enable it.');+ process.exit(1);+ }++ if (dryRun) {+ const todo = refreshOnly ? [] : await fetchUnregistered8004(network, limit);+ const stale = await fetchStale8004(network, limit * 4);+ const sol = ((todo.length * EST_REGISTER_8004_LAMPORTS) / 1e9).toFixed(4);+ console.log(`\n would register: ${todo.length} agents (about ${sol} SOL)`);+ for (const a of todo) console.log(` ${a.id} ${a.name}`);+ console.log(` would refresh standing: ${stale.length} agents`);+ return;+ }++ if (!flag('--confirm')) {+ console.error('\nRefusing to sign without --confirm (use --dry-run to preview).');+ process.exit(1);+ }++ const out = await runBackfill8004({+ network,+ limit,+ pauseMs,+ register: !refreshOnly,+ refresh: true,+ onEvent: (kind, d) => console.log(` ${kind}: ${d.agent_id} ${d.signature || d.error || ''}`),+ });+ console.log(+ `\n registered ${out.registered.length}, already ${out.already.length}, refreshed ${out.refreshed.length}, errors ${out.errors.length}`,+ );+ if (out.errors.length) process.exitCode = 1;+}++main()+ .catch((err) => {+ console.error(err);+ process.exitCode = 1;+ })+ .finally(() => setTimeout(() => process.exit(), 50));diff --git a/src/agent-detail.js b/src/agent-detail.jsindex 16e90e96d..ee068648d 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -530,6 +530,29 @@ function el(tag, props = {}, children = []) {return node;}+const REGISTRY_TIER_ACCENT = { platinum: 'violet', gold: 'amber', silver: 'muted', bronze: 'amber' };++// Open Solana agent registry badge (8004). Mainnet registration wins; a devnet+// registration is shown labelled. Returns null when the agent is not registered,+// so an unregistered agent renders nothing.+function registry8004Pill(meta) {+ const main = meta?.registry_8004;+ const dev = meta?.devnet?.registry_8004;+ const block = main?.asset ? main : dev?.asset ? dev : null;+ if (!block) return null;+ const standing = block.standing || null;+ const tier = standing?.tier || 'Unrated';+ const label = `8004 ${tier}${block === dev && block !== main ? ' (devnet)' : ''}`;+ const node = pill(label, REGISTRY_TIER_ACCENT[tier.toLowerCase()] || '');+ const parts = ['Registered in the open Solana agent registry'];+ if (standing && standing.total_feedbacks != null) {+ parts.push(`${standing.total_feedbacks} feedback${standing.total_feedbacks === 1 ? '' : 's'}`);+ if (standing.average_score != null) parts.push(`average score ${standing.average_score}`);+ }+ node.title = parts.join(', ');+ return node;+}+function pill(text, accent = '') {return el('span', { class: `ad-pill ${accent ? `ad-pill-${accent}` : ''}`, text });}@@ -1285,6 +1308,9 @@ function render(agent) {trustPills.appendChild(seeker);}+ const registryPill = registry8004Pill(agent.rawMetadata?.meta);+ if (registryPill) trustPills.appendChild(registryPill);+const services = $('ad-services');services.innerHTML = '';(agent.services || []).forEach((s) => services.appendChild(renderService(s)));diff --git a/tests/solana-8004.devnet.test.js b/tests/solana-8004.devnet.test.jsnew file mode 100644index 000000000..ad7292f4a--- /dev/null+++ b/tests/solana-8004.devnet.test.js@@ -0,0 +1,14 @@+import { describe, it, expect } from 'vitest';+import { execFileSync } from 'node:child_process';++// Live devnet round trip: register an agent in the open Solana agent registry,+// leave feedback from a second wallet and read the tier back. Spends only+// throwaway devnet SOL. Opt in with RUN_DEVNET_8004=1 (needs a working faucet).+describe.skipIf(process.env.RUN_DEVNET_8004 !== '1')('8004 registry on devnet', () => {+ it('registers, takes feedback and reads the tier back', () => {+ const out = execFileSync('node', ['scripts/prove-8004-registry.mjs'], { encoding: 'utf8', timeout: 170_000 });+ expect(out).toMatch(/registered asset : [1-9A-HJ-NP-Za-km-z]{32,44}/);+ expect(out).toMatch(/feedback tx/);+ expect(out.trim().endsWith('OK')).toBe(true);+ }, 180_000);+});diff --git a/tests/solana-8004.test.js b/tests/solana-8004.test.jsnew file mode 100644index 000000000..e1fbf7a4a--- /dev/null+++ b/tests/solana-8004.test.js@@ -0,0 +1,158 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Keypair } from '@solana/web3.js';++const sqlState = { calls: [], queue: [] };+vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ sqlState.calls.push({ query: strings.join('?'), values });+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ }),+}));+vi.mock('../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'https://three.ws' } }));++const {+ TIER_NAMES,+ anyRegistryBlock,+ meetsMinTier,+ parseMinTier,+ publicRegistry8004,+ read8004Standing,+ register8004Agent,+ registrationEnabled,+ registryBlockOf,+ registryProgramIds,+ liveRegistry8004,+ tierRank,+} = await import('../api/_lib/solana-8004.js');++const ASSET = Keypair.generate().publicKey;++function fakeSdk(over = {}) {+ return {+ loadAgent: vi.fn(async () => ({ asset: ASSET })),+ getTrustTier: vi.fn(async () => 3),+ getSummary: vi.fn(async () => ({ averageScore: 91, totalFeedbacks: 7 })),+ getEnrichedSummary: vi.fn(async () => ({ qualityScore: 88, confidence: 0.7, riskScore: 4, uniqueCallers: 5 })),+ registerAgent: vi.fn(async () => ({ asset: ASSET, signature: 'sig1' })),+ ...over,+ };+}++beforeEach(() => {+ sqlState.calls = [];+ sqlState.queue = [];+});++describe('tiers and blocks', () => {+ it('ranks tiers in order and unknown as 0', () => {+ expect(TIER_NAMES.map(tierRank)).toEqual([0, 1, 2, 3, 4]);+ expect(tierRank('Mythic')).toBe(0);+ expect(tierRank(undefined)).toBe(0);+ });++ it('picks the block per network and prefers mainnet', () => {+ const meta = { registry_8004: { asset: 'M' }, devnet: { registry_8004: { asset: 'D' } } };+ expect(registryBlockOf(meta, 'mainnet').asset).toBe('M');+ expect(registryBlockOf(meta, 'devnet').asset).toBe('D');+ expect(anyRegistryBlock(meta)).toMatchObject({ asset: 'M', network: 'mainnet' });+ expect(anyRegistryBlock({ devnet: { registry_8004: { asset: 'D' } } })).toMatchObject({ network: 'devnet' });+ expect(anyRegistryBlock({})).toBeNull();+ expect(registryBlockOf(null, 'mainnet')).toBeNull();+ });++ it('gates mainnet behind the env flag and always allows devnet', () => {+ expect(registrationEnabled('devnet', {})).toBe(true);+ expect(registrationEnabled('mainnet', {})).toBe(false);+ expect(registrationEnabled('mainnet', { SOLANA_8004_REGISTER_MAINNET: '1' })).toBe(true);+ });++ it('resolves program ids from the published SDK', async () => {+ const ids = await registryProgramIds('devnet');+ expect(ids.registry).toMatch(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/);+ expect(ids.registry).not.toBe((await registryProgramIds('mainnet')).registry);+ });+});++describe('read8004Standing', () => {+ it('reads tier and feedback from the registry', async () => {+ const r = await read8004Standing(ASSET.toBase58(), 'devnet', { sdk: fakeSdk() });+ expect(r).toMatchObject({ registered: true, tier: 'Gold', tier_rank: 3, average_score: 91, total_feedbacks: 7 });+ });++ it('reports an unknown asset as unregistered, not unavailable', async () => {+ const r = await read8004Standing(ASSET.toBase58(), 'devnet', { sdk: fakeSdk({ loadAgent: async () => null }) });+ expect(r.registered).toBe(false);+ expect(r.unavailable).toBeUndefined();+ });++ it('reports an RPC failure as unavailable, never as Unrated', async () => {+ const sdk = fakeSdk({ loadAgent: async () => { throw new Error('rpc down'); } });+ const r = await read8004Standing(ASSET.toBase58(), 'devnet', { sdk });+ expect(r).toMatchObject({ registered: false, unavailable: true });+ expect(r.tier).toBeUndefined();+ });+});++describe('register8004Agent', () => {+ it('registers once, stores the block on the agent row and logs an action', async () => {+ const sdk = fakeSdk({ loadAgent: async () => null });+ const out = await register8004Agent({ agent: { id: 'a1', meta: {} }, network: 'devnet', sdk });+ expect(out).toMatchObject({ asset: ASSET.toBase58(), signature: 'sig1', alreadyRegistered: false });+ expect(sdk.registerAgent).toHaveBeenCalledWith('https://three.ws/api/agents/a1/registration', { atomEnabled: true });+ const write = sqlState.calls[0];+ expect(write.query).toContain("'registry_8004'");+ expect(write.values[0]).toContain(ASSET.toBase58());+ expect(sqlState.calls[1].query).toContain('agent_actions');+ });++ it('is idempotent when the stored asset still resolves', async () => {+ const sdk = fakeSdk();+ const out = await register8004Agent({+ agent: { id: 'a1', meta: { devnet: { registry_8004: { asset: ASSET.toBase58() } } } },+ network: 'devnet',+ sdk,+ });+ expect(out.alreadyRegistered).toBe(true);+ expect(sdk.registerAgent).not.toHaveBeenCalled();+ expect(sqlState.calls).toHaveLength(0);+ });++ it('refuses mainnet without the opt-in flag', async () => {+ delete process.env.SOLANA_8004_REGISTER_MAINNET;+ await expect(register8004Agent({ agent: { id: 'a1', meta: {} }, network: 'mainnet', sdk: fakeSdk() })).rejects.toThrow(/SOLANA_8004_REGISTER_MAINNET/);+ });+});++describe('hire-side helpers', () => {+ it('shapes nothing for an unregistered agent', () => {+ expect(publicRegistry8004(null)).toBeNull();+ expect(publicRegistry8004({})).toBeNull();+ });++ it('exposes only public fields with an explorer link', () => {+ const v = publicRegistry8004({ asset: 'A', program: 'P', authority: 'secret-ish', standing: { tier: 'Silver', average_score: 80, total_feedbacks: 2, checked_at: 't' } }, 'mainnet');+ expect(v).toMatchObject({ asset: 'A', tier: 'Silver', tier_rank: 2, total_feedbacks: 2, explorer_url: 'https://solscan.io/account/A' });+ expect(v.authority).toBeUndefined();+ });++ it('marks the cached view stale when the chain cannot be read', async () => {+ const sdk = fakeSdk({ loadAgent: async () => { throw new Error('down'); } });+ const v = await liveRegistry8004({ asset: ASSET.toBase58(), network: 'devnet', tier: 'Gold', tier_rank: 3 }, { sdk });+ expect(v).toMatchObject({ stale: true, tier: 'Gold' });+ });++ it('replaces the cached tier with the live one', async () => {+ const v = await liveRegistry8004({ asset: ASSET.toBase58(), network: 'devnet', tier: 'Bronze', tier_rank: 1 }, { sdk: fakeSdk() });+ expect(v).toMatchObject({ tier: 'Gold', tier_rank: 3, stale: false });+ });++ it('parses and enforces the minimum tier', () => {+ expect(parseMinTier(undefined)).toBeNull();+ expect(parseMinTier('silver')).toBe(2);+ expect(() => parseMinTier('mythic')).toThrow(RangeError);+ expect(meetsMinTier(null, null)).toBe(true);+ expect(meetsMinTier(null, 2)).toBe(false);+ expect(meetsMinTier({ tier_rank: 2 }, 2)).toBe(true);+ expect(meetsMinTier({ tier_rank: 1 }, 2)).toBe(false);+ });+});