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: onchain deploy lib, bounty leaderboard, marketplace + pump improvements
nirholas50e1436348e0
diff --git a/api/_lib/onchain-deploy.js b/api/_lib/onchain-deploy.jsnew file mode 100644index 000000000..5d83fa207--- /dev/null+++ b/api/_lib/onchain-deploy.js@@ -0,0 +1,349 @@+// Shared server-side Metaplex Core agent deploy.+// ---------------------------------------------------------------------------+// Single source of truth for turning an agent into its on-chain identity — a+// Metaplex Core asset minted into the three.ws Agent Collection. Used by both:+// • api/admin/bulk-launch.js — the live SSE dashboard,+// • scripts/deploy-agents-onchain.mjs — the CLI batch/canary runner.+//+// Custody model: one funded wallet (the collection authority) is the mint fee+// payer and — on first run — deploys the Collection account. Each agent is+// owned by its own custodial Solana wallet (generated on demand); the owner does+// NOT sign the mint, so agent wallets never need SOL.++import { Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js';+import bs58 from 'bs58';+import { CID } from 'multiformats/cid';+import * as raw from 'multiformats/codecs/raw';+import { sha256 } from 'multiformats/hashes/sha2';+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';+import { mplCore, create, createCollection, ruleSet } from '@metaplex-foundation/mpl-core';+import {+ generateSigner,+ publicKey as umiPublicKey,+ createSignerFromKeypair,+ signerIdentity,+} from '@metaplex-foundation/umi';+import { sql } from './db.js';+import { env } from './env.js';+import { putObject, publicUrl as r2PublicUrl } from './r2.js';+import {+ buildAgentManifest,+ buildAgentOnchainAttributes,+ agentRoyaltyConfig,+ agentHomeUrl,+} from './three-brand.js';+import { getAgentCollection } from './solana-collection.js';+import { solanaRpcEndpoints } from './solana/connection.js';+import { generateSolanaAgentWallet } from './agent-wallet.js';+import { publishFeedEvent } from './feed.js';++// Genesis-hash chain refs (CAIP-2), mirroring api/agents/onchain/[action].js.+export const SOLANA_REFS = {+ mainnet: '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ devnet: 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1',+};++// A Core asset minted into a collection costs ~0.0037 SOL rent + fee; deploying+// the Collection account on first run costs ~0.003 SOL rent + fee.+export const EST_MINT_LAMPORTS = Math.floor(0.004 * LAMPORTS_PER_SOL);+export const EST_COLLECTION_LAMPORTS = Math.floor(0.005 * LAMPORTS_PER_SOL);++export function explorerUrl(asset, network) {+ const suffix = network === 'devnet' ? '?cluster=devnet' : '';+ return `https://solscan.io/account/${asset}${suffix}`;+}++/** Resolve the funded authority secret (collection authority == mint fee payer). */+export function authoritySecret() {+ return process.env.SOLANA_AGENT_COLLECTION_AUTHORITY_KEY || process.env.LAUNCH_FUNDER_SECRET || null;+}++/** Build a Umi instance whose identity (payer) + signer is the funded authority. */+export function buildAuthorityUmi(network, secret = authoritySecret()) {+ if (!secret) {+ throw new Error('Set SOLANA_AGENT_COLLECTION_AUTHORITY_KEY (or LAUNCH_FUNDER_SECRET) to the funded authority wallet secret.');+ }+ let authorityKeypair;+ try {+ authorityKeypair = Keypair.fromSecretKey(bs58.decode(secret));+ } catch {+ throw new Error('authority/funder secret is not a valid base58 keypair');+ }+ const umi = createUmi(solanaRpcEndpoints(network)[0]).use(mplCore());+ const authoritySigner = createSignerFromKeypair(+ umi,+ umi.eddsa.createKeypairFromSecretKey(authorityKeypair.secretKey),+ );+ umi.use(signerIdentity(authoritySigner));+ return { umi, authoritySigner, authorityKeypair };+}++/** Current authority/funder balance, in lamports (0 on RPC error). */+export async function funderLamports(umi, pubkey) {+ try {+ const bal = await umi.rpc.getBalance(pubkey);+ return Number(bal.basisPoints);+ } catch {+ return 0;+ }+}++// Pin the manifest. Try web3.storage for true IPFS pinning; otherwise fall back+// to R2 while computing the real CIDv1 (raw codec, sha2-256) from the bytes, so+// the content is verifiable content-addressing and the returned HTTPS URL is+// real and resolvable — never a stub. Mirrors api/agents/onchain/[action].js.+export async function pinManifest(manifest, agentId) {+ const bytes = Buffer.from(JSON.stringify(manifest), 'utf-8');+ const token = process.env.WEB3_STORAGE_TOKEN;+ if (token) {+ try {+ const r = await fetch('https://api.web3.storage/upload', {+ method: 'POST',+ headers: { Authorization: `Bearer ${token}` },+ body: bytes,+ });+ if (r.ok) {+ const data = await r.json();+ if (data.cid) return { cid: data.cid, uri: `ipfs://${data.cid}` };+ }+ } catch {+ /* fall through to R2 */+ }+ }+ const digest = await sha256.digest(bytes);+ const cid = CID.create(1, raw.code, digest).toString();+ const key = `agent-manifests/bulk/${agentId}.json`;+ await putObject({ key, body: bytes, contentType: 'application/json' });+ return { cid, uri: r2PublicUrl(key) };+}++/** Agents still missing an on-chain identity on this network. */+export async function fetchUndeployedAgents(network, limit) {+ return network === 'mainnet'+ ? sql`+ SELECT ai.id, ai.user_id, ai.name, ai.description, ai.meta, ai.avatar_id,+ av.thumbnail_key, av.storage_key+ FROM agent_identities ai+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL+ WHERE ai.deleted_at IS NULL+ AND ai.meta->>'sol_mint_address' IS NULL+ ORDER BY ai.created_at ASC+ LIMIT ${limit}+ `+ : sql`+ SELECT ai.id, ai.user_id, ai.name, ai.description, ai.meta, ai.avatar_id,+ av.thumbnail_key, av.storage_key+ FROM agent_identities ai+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL+ WHERE ai.deleted_at IS NULL+ AND ai.meta->'devnet'->>'sol_mint_address' IS NULL+ ORDER BY ai.created_at ASC+ LIMIT ${limit}+ `;+}++// Resolve the three.ws Agent Collection for this network: prefer the env var+// (keeps the interactive deploy + edit paths aligned), then a persisted setting,+// then deploy the Collection account on first run and persist its address.+// `onEvent(type, data)` receives a 'collection' event; pass a logger or SSE emitter.+export async function resolveAgentCollection({ umi, authoritySigner, network, onEvent }) {+ const authority = authoritySigner.publicKey.toString();++ const envAddr = getAgentCollection(network);+ if (envAddr) {+ onEvent?.('collection', { address: envAddr, source: 'env', authority });+ return envAddr;+ }++ await sql`+ CREATE TABLE IF NOT EXISTS app_settings (+ key text PRIMARY KEY,+ value jsonb NOT NULL,+ updated_at timestamptz NOT NULL DEFAULT now()+ )+ `;+ const settingKey = `solana_agent_collection_${network}`;+ const [row] = await sql`SELECT value FROM app_settings WHERE key = ${settingKey}`;+ if (row?.value?.address) {+ onEvent?.('collection', { address: row.value.address, source: 'db', authority });+ return row.value.address;+ }++ // First run for this network: deploy the Collection account, funded ++ // authority-signed by the funder.+ const bal = await funderLamports(umi, authoritySigner.publicKey);+ if (bal < EST_COLLECTION_LAMPORTS) {+ throw new Error(+ `funder needs ~${(EST_COLLECTION_LAMPORTS / LAMPORTS_PER_SOL).toFixed(3)} SOL to deploy the three.ws Agents collection — top up ${authority} and re-run`,+ );+ }+ const collectionSigner = generateSigner(umi);+ const collectionUri = `${env.APP_ORIGIN}/api/agents/solana-collection-metadata?network=${network}`;+ const result = await createCollection(umi, {+ collection: collectionSigner,+ name: 'three.ws Agents',+ uri: collectionUri,+ plugins: [+ {+ type: 'Attributes',+ attributeList: [+ { key: 'platform', value: 'three.ws' },+ { key: 'url', value: env.APP_ORIGIN },+ { key: 'standard', value: 'metaplex-core' },+ { key: 'schema', value: 'agent-manifest/0.1' },+ { key: 'chain', value: `solana:${SOLANA_REFS[network]}` },+ ],+ },+ ],+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });++ const address = collectionSigner.publicKey.toString();+ const signature = bs58.encode(result.signature);+ await sql`+ INSERT INTO app_settings (key, value)+ VALUES (${settingKey}, ${JSON.stringify({ address, authority, signature, deployed_at: new Date().toISOString() })}::jsonb)+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()+ `;+ onEvent?.('collection', { address, source: 'deployed', authority, signature });+ return address;+}++/**+ * Deploy a single agent on-chain: ensure its owner wallet, pin its manifest,+ * mint the Core asset into the collection, and persist the result. Returns+ * { asset, signature, metadataUri, ownerAddress, image }. Pure of UI concerns —+ * pass `onEvent` to receive a 'wallet' event when a custodial wallet is created.+ */+export async function deployAgentOnce({ umi, authoritySigner, collectionAddr, collectionPk, agent, network, onEvent }) {+ const agentName = agent.name || 'Agent';++ // 1. Owner = the agent's own custodial Solana wallet (generate if missing).+ let meta = { ...(agent.meta || {}) };+ let ownerAddress = meta.solana_address;+ if (!ownerAddress) {+ const wallet = await generateSolanaAgentWallet();+ meta = {+ ...meta,+ solana_address: wallet.address,+ encrypted_solana_secret: wallet.encrypted_secret,+ solana_wallet_source: 'bulk_onchain',+ };+ ownerAddress = wallet.address;+ await sql`+ UPDATE agent_identities+ SET meta = ${JSON.stringify(meta)}::jsonb, updated_at = NOW()+ WHERE id = ${agent.id}+ `;+ onEvent?.('wallet', { agent_id: agent.id, name: agentName, owner: ownerAddress });+ }++ // 2. Media + manifest.+ const image = agent.thumbnail_key ? r2PublicUrl(agent.thumbnail_key) : '';+ const animationUrl = agent.storage_key ? r2PublicUrl(agent.storage_key) : '';+ const createdAt = new Date().toISOString();+ const manifest = buildAgentManifest({+ name: agentName,+ description: agent.description || '',+ avatarId: agent.avatar_id || null,+ image,+ animationUrl,+ externalUrl: agentHomeUrl(agent.id),+ ownerAddress,+ createdAt,+ });+ const { uri: metadataUri } = await pinManifest(manifest, agent.id);++ // 3. Mint the Core asset into the collection.+ const attributes = buildAgentOnchainAttributes({+ name: agentName,+ agentUrl: agentHomeUrl(agent.id),+ createdAt,+ });+ const royalty = agentRoyaltyConfig(ownerAddress);+ const ownerPk = umiPublicKey(ownerAddress);+ const assetSigner = generateSigner(umi);+ const createArgs = {+ asset: assetSigner,+ owner: ownerPk,+ name: agentName.slice(0, 32) || 'Agent',+ uri: metadataUri,+ plugins: [+ ...(attributes.length ? [{ type: 'Attributes', attributeList: attributes }] : []),+ ...(royalty+ ? [{+ type: 'Royalties',+ basisPoints: royalty.basisPoints,+ creators: royalty.creators.map((c) => ({ address: umiPublicKey(c.address), percentage: c.percentage })),+ ruleSet: ruleSet('None'),+ }]+ : []),+ ],+ };+ if (collectionPk) {+ createArgs.collection = collectionPk;+ createArgs.authority = authoritySigner;+ }+ const result = await create(umi, createArgs).sendAndConfirm(umi, {+ confirm: { commitment: 'confirmed' },+ });+ const asset = assetSigner.publicKey.toString();+ const signature = bs58.encode(result.signature);++ // 4. Persist. Mainnet writes the canonical fields every read path keys on;+ // devnet is isolated under meta.devnet so it never blocks a mainnet mint.+ const onchain = {+ chain: `solana:${SOLANA_REFS[network]}`,+ family: 'solana',+ cluster: network,+ onchain_id: asset,+ sol_asset: asset,+ contract_or_mint: asset,+ metadata_uri: metadataUri,+ owner: ownerAddress,+ custody: true,+ tx_hash: signature,+ ...(collectionAddr ? { collection: collectionAddr } : {}),+ confirmed_at: new Date().toISOString(),+ };+ const merged =+ network === 'mainnet'+ ? {+ ...meta,+ chain_type: 'solana',+ network,+ sol_mint_address: asset,+ ...(collectionAddr ? { collection: collectionAddr, update_authority: 'threews' } : {}),+ onchain,+ }+ : { ...meta, devnet: { sol_mint_address: asset, collection: collectionAddr || null, onchain } };++ await sql`+ UPDATE agent_identities+ SET meta = ${JSON.stringify(merged)}::jsonb, updated_at = NOW()+ WHERE id = ${agent.id}+ `;++ await sql`+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)+ VALUES (+ ${agent.id},+ ${'solana.deploy'},+ ${JSON.stringify({ asset, network, signature, collection: collectionAddr || null, owner: ownerAddress, source: 'bulk_onchain' })}::jsonb,+ ${'bulk_onchain'}+ )+ `.catch(() => {});++ // Truthful on-chain feed event — fired only after the tx confirms (mainnet).+ if (network === 'mainnet') {+ publishFeedEvent({+ type: 'agent-onchain',+ ts: Date.now(),+ actor: agentName,+ agentId: agent.id,+ name: agentName,+ chain: 'Solana',+ }).catch(() => {});+ }++ return { asset, signature, metadataUri, ownerAddress, image };+}diff --git a/api/admin/bulk-launch.js b/api/admin/bulk-launch.jsindex 2e2832f5a..005ffab3c 100644--- a/api/admin/bulk-launch.js+++ b/api/admin/bulk-launch.js@@ -5,14 +5,16 @@// • minted into the "three.ws Agents" Collection (authority-managed by three.ws),// • owned by the agent's own custodial Solana wallet (so the agent holds its// identity and can transfer/sell it later),-// • carrying an on-chain Attributes plugin (platform, links, $THREE) written-// into the asset account itself, plus an enforced 5% Royalties plugin,-// • pointing at a pinned manifest (Metaplex token-metadata + agent-manifest/0.1).+// • carrying an on-chain Attributes plugin (platform, links, $THREE) plus an+// enforced 5% Royalties plugin, pointing at a pinned manifest.//// One funded wallet does everything: it is the collection authority, the mint// fee payer, and — on first run — the deployer of the Collection account. The// agent wallets need no SOL (the owner of a Core asset does not sign the mint).//+// The on-chain work lives in api/_lib/onchain-deploy.js, shared with the CLI+// runner scripts/deploy-agents-onchain.mjs so both mint identical assets.+//// Query params:// network mainnet | devnet (default: mainnet)// limit max agents to process this run (default: 100, max 500)@@ -28,47 +30,20 @@// paused { funder_balance_sol, deployed, reason }// done { deployed, errors, skipped }-import { Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js';-import bs58 from 'bs58';-import { CID } from 'multiformats/cid';-import * as raw from 'multiformats/codecs/raw';-import { sha256 } from 'multiformats/hashes/sha2';-import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';-import { mplCore, create, createCollection, ruleSet } from '@metaplex-foundation/mpl-core';-import {- generateSigner,- publicKey as umiPublicKey,- createSignerFromKeypair,- signerIdentity,-} from '@metaplex-foundation/umi';-import { sql } from '../_lib/db.js';+import { LAMPORTS_PER_SOL } from '@solana/web3.js';+import { publicKey as umiPublicKey } from '@metaplex-foundation/umi';import { cors, method, error } from '../_lib/http.js';import { requireAdmin } from '../_lib/admin.js';-import { env } from '../_lib/env.js';-import { putObject, publicUrl as r2PublicUrl } from '../_lib/r2.js';import {- buildAgentManifest,- buildAgentOnchainAttributes,- agentRoyaltyConfig,- agentHomeUrl,-} from '../_lib/three-brand.js';-import { getAgentCollection } from '../_lib/solana-collection.js';-import { solanaRpcEndpoints } from '../_lib/solana/connection.js';-import { generateSolanaAgentWallet } from '../_lib/agent-wallet.js';-import { publishFeedEvent } from '../_lib/feed.js';--// Genesis-hash chain refs (CAIP-2) for the onchain block, mirroring the-// interactive deploy path in api/agents/onchain/[action].js.-const SOLANA_REFS = {- mainnet: '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',- devnet: 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1',-};--// A Core asset minted into a collection costs ~0.0037 SOL of rent + fee. Pause-// the run if the funder can't cover one more mint with a little headroom.-const EST_MINT_LAMPORTS = Math.floor(0.004 * LAMPORTS_PER_SOL);-// Deploying the Collection account on first run costs ~0.003 SOL of rent + fee.-const EST_COLLECTION_LAMPORTS = Math.floor(0.005 * LAMPORTS_PER_SOL);+ authoritySecret,+ buildAuthorityUmi,+ funderLamports,+ fetchUndeployedAgents,+ resolveAgentCollection,+ deployAgentOnce,+ explorerUrl,+ EST_MINT_LAMPORTS,+} from '../_lib/onchain-deploy.js';const sleep = (ms) => new Promise((r) => setTimeout(r, ms));@@ -78,110 +53,6 @@ function sse(res, event, data) {}}-function explorerUrl(asset, network) {- const suffix = network === 'devnet' ? '?cluster=devnet' : '';- return `https://solscan.io/account/${asset}${suffix}`;-}--// Pin the manifest. Try web3.storage for true IPFS pinning; otherwise fall back-// to R2 while computing the real CIDv1 (raw codec, sha2-256) from the bytes, so-// the content is verifiable IPFS content-addressing and the returned HTTPS URL-// is real and resolvable — never a stub. Mirrors api/agents/onchain/[action].js.-async function pinManifest(manifest, agentId) {- const bytes = Buffer.from(JSON.stringify(manifest), 'utf-8');- const token = process.env.WEB3_STORAGE_TOKEN;- if (token) {- try {- const r = await fetch('https://api.web3.storage/upload', {- method: 'POST',- headers: { Authorization: `Bearer ${token}` },- body: bytes,- });- if (r.ok) {- const data = await r.json();- if (data.cid) return { cid: data.cid, uri: `ipfs://${data.cid}` };- }- } catch {- /* fall through to R2 */- }- }- const digest = await sha256.digest(bytes);- const cid = CID.create(1, raw.code, digest).toString();- const key = `agent-manifests/bulk/${agentId}.json`;- await putObject({ key, body: bytes, contentType: 'application/json' });- return { cid, uri: r2PublicUrl(key) };-}--// Resolve the three.ws Agent Collection for this network: prefer the env var-// (keeps the interactive deploy + edit paths aligned), then a persisted setting,-// then deploy the Collection account on first run and persist its address.-async function resolveCollection({ umi, authoritySigner, network, dryRun, res }) {- const authority = authoritySigner.publicKey.toString();-- const envAddr = getAgentCollection(network);- if (envAddr) {- sse(res, 'collection', { address: envAddr, source: 'env', authority });- return envAddr;- }-- await sql`- CREATE TABLE IF NOT EXISTS app_settings (- key text PRIMARY KEY,- value jsonb NOT NULL,- updated_at timestamptz NOT NULL DEFAULT now()- )- `;- const settingKey = `solana_agent_collection_${network}`;- const [row] = await sql`SELECT value FROM app_settings WHERE key = ${settingKey}`;- if (row?.value?.address) {- sse(res, 'collection', { address: row.value.address, source: 'db', authority });- return row.value.address;- }-- if (dryRun) {- sse(res, 'collection', { address: null, source: 'none', authority, dry_run: true });- return null;- }-- // First run for this network: deploy the Collection account, funded +- // authority-signed by the funder. Needs ~0.003 SOL of rent + fee.- const bal = await umi.rpc.getBalance(authoritySigner.publicKey).then((b) => Number(b.basisPoints)).catch(() => 0);- if (bal < EST_COLLECTION_LAMPORTS) {- throw new Error(- `funder needs ~${(EST_COLLECTION_LAMPORTS / LAMPORTS_PER_SOL).toFixed(3)} SOL to deploy the three.ws Agents collection — top up ${authority} and re-run`,- );- }- const collectionSigner = generateSigner(umi);- const collectionUri = `${env.APP_ORIGIN}/api/agents/solana-collection-metadata?network=${network}`;- const result = await createCollection(umi, {- collection: collectionSigner,- name: 'three.ws Agents',- uri: collectionUri,- plugins: [- {- type: 'Attributes',- attributeList: [- { key: 'platform', value: 'three.ws' },- { key: 'url', value: env.APP_ORIGIN },- { key: 'standard', value: 'metaplex-core' },- { key: 'schema', value: 'agent-manifest/0.1' },- { key: 'chain', value: `solana:${SOLANA_REFS[network]}` },- ],- },- ],- }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });-- const address = collectionSigner.publicKey.toString();- const signature = bs58.encode(result.signature);- await sql`- INSERT INTO app_settings (key, value)- VALUES (${settingKey}, ${JSON.stringify({ address, authority, signature, deployed_at: new Date().toISOString() })}::jsonb)- ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()- `;- sse(res, 'collection', { address, source: 'deployed', authority, signature });- return address;-}-export default async function handler(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;@@ -194,13 +65,7 @@ export default async function handler(req, res) {const limit = Math.min(500, Math.max(1, Number(q.limit) || 100));const dryRun = q.dry_run === 'true';- // One funded wallet is the collection authority, the mint fee payer, and the- // collection deployer. Prefer the canonical collection-authority key so the- // interactive deploy/edit paths co-sign with the same authority; fall back to- // the launch funder key.- const signerSecret =- process.env.SOLANA_AGENT_COLLECTION_AUTHORITY_KEY || process.env.LAUNCH_FUNDER_SECRET;- if (!signerSecret) {+ if (!authoritySecret()) {return error(res,500,@@ -208,11 +73,11 @@ export default async function handler(req, res) {'Set SOLANA_AGENT_COLLECTION_AUTHORITY_KEY (or LAUNCH_FUNDER_SECRET) to the funded authority wallet secret.',);}- let authorityKeypair;+ let umi, authoritySigner;try {- authorityKeypair = Keypair.fromSecretKey(bs58.decode(signerSecret));- } catch {- return error(res, 500, 'config_error', 'authority/funder secret is not a valid base58 keypair');+ ({ umi, authoritySigner } = buildAuthorityUmi(network));+ } catch (e) {+ return error(res, 500, 'config_error', e.message);}// SSE headers@@ -225,52 +90,9 @@ export default async function handler(req, res) {let aborted = false;req.on('close', () => { aborted = true; });- // Umi with the authority as identity (payer) + signer.- const rpcUrl = solanaRpcEndpoints(network)[0];- const umi = createUmi(rpcUrl).use(mplCore());- const authoritySigner = createSignerFromKeypair(- umi,- umi.eddsa.createKeypairFromSecretKey(authorityKeypair.secretKey),- );- umi.use(signerIdentity(authoritySigner));const authorityPk = authoritySigner.publicKey;-- async function funderLamports() {- try {- const bal = await umi.rpc.getBalance(authorityPk);- return Number(bal.basisPoints);- } catch {- return 0;- }- }-- const startBalance = await funderLamports();-- // Agents needing an on-chain identity on this network. mainnet uses the- // canonical meta.sol_mint_address (what every read path keys on); devnet test- // runs are isolated under meta.devnet so they never block a real mainnet mint.- const agents =- network === 'mainnet'- ? await sql`- SELECT ai.id, ai.user_id, ai.name, ai.description, ai.meta, ai.avatar_id,- av.thumbnail_key, av.storage_key- FROM agent_identities ai- LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL- WHERE ai.deleted_at IS NULL- AND ai.meta->>'sol_mint_address' IS NULL- ORDER BY ai.created_at ASC- LIMIT ${limit}- `- : await sql`- SELECT ai.id, ai.user_id, ai.name, ai.description, ai.meta, ai.avatar_id,- av.thumbnail_key, av.storage_key- FROM agent_identities ai- LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL- WHERE ai.deleted_at IS NULL- AND ai.meta->'devnet'->>'sol_mint_address' IS NULL- ORDER BY ai.created_at ASC- LIMIT ${limit}- `;+ const startBalance = await funderLamports(umi, authorityPk);+ const agents = await fetchUndeployedAgents(network, limit);sse(res, 'init', {total: agents.length,@@ -283,7 +105,12 @@ export default async function handler(req, res) {// Resolve (or deploy) the collection up front.let collectionAddr;try {- collectionAddr = await resolveCollection({ umi, authoritySigner, network, dryRun, res });+ collectionAddr = await resolveAgentCollection({+ umi,+ authoritySigner,+ network,+ onEvent: dryRun ? undefined : (type, data) => sse(res, type, data),+ });} catch (err) {sse(res, 'error', { agent_id: null, name: 'collection', error: `collection: ${err.message}` });sse(res, 'done', { deployed: 0, errors: 1, skipped: 0 });@@ -293,63 +120,30 @@ export default async function handler(req, res) {let deployed = 0;let errors = 0;- let skipped = 0;+ const skipped = 0;for (const agent of agents) {if (aborted) break;const agentName = agent.name || 'Agent';- let meta = { ...(agent.meta || {}) };-- // 1. Owner = the agent's own custodial Solana wallet (generate if missing).- // The owner does not sign the mint, so it needs no SOL.- if (!meta.solana_address) {- if (!dryRun) {- try {- const wallet = await generateSolanaAgentWallet();- meta = {- ...meta,- solana_address: wallet.address,- encrypted_solana_secret: wallet.encrypted_secret,- solana_wallet_source: 'bulk_onchain',- };- await sql`- UPDATE agent_identities- SET meta = ${JSON.stringify(meta)}::jsonb, updated_at = NOW()- WHERE id = ${agent.id}- `;- } catch (err) {- sse(res, 'error', { agent_id: agent.id, name: agentName, error: `wallet: ${err.message}` });- errors++;- continue;- }- }- sse(res, 'wallet', { agent_id: agent.id, name: agentName, owner: meta.solana_address || '(dry run)' });- }- const ownerAddress = meta.solana_address;-- // 2. Media + manifest.- const image = agent.thumbnail_key ? r2PublicUrl(agent.thumbnail_key) : '';- const animationUrl = agent.storage_key ? r2PublicUrl(agent.storage_key) : '';- const createdAt = new Date().toISOString();if (dryRun) {sse(res, 'deployed', {agent_id: agent.id,name: agentName,asset: '(dry run)',- owner: ownerAddress || '(dry run)',+ owner: agent.meta?.solana_address || '(generated at mint)',metadata_uri: null,signature: null,explorer_url: null,- avatar_thumb: image || null,+ avatar_thumb: agent.thumbnail_key ? '' : null,dry_run: true,});deployed++;continue;}- // 3. Funder balance gate.- const bal = await funderLamports();+ // Funder balance gate.+ const bal = await funderLamports(umi, authorityPk);if (bal < EST_MINT_LAMPORTS + 5000) {sse(res, 'paused', {funder_balance_sol: bal / LAMPORTS_PER_SOL,@@ -360,123 +154,25 @@ export default async function handler(req, res) {}try {- // 4. Pin manifest.- const manifest = buildAgentManifest({- name: agentName,- description: agent.description || '',- avatarId: agent.avatar_id || null,- image,- animationUrl,- externalUrl: agentHomeUrl(agent.id),- ownerAddress,- createdAt,+ const r = await deployAgentOnce({+ umi,+ authoritySigner,+ collectionAddr,+ collectionPk,+ agent,+ network,+ onEvent: (type, data) => sse(res, type, data),});- const { uri: metadataUri } = await pinManifest(manifest, agent.id);-- // 5. Mint the Core asset into the collection.- const attributes = buildAgentOnchainAttributes({- name: agentName,- agentUrl: agentHomeUrl(agent.id),- createdAt,- });- const royalty = agentRoyaltyConfig(ownerAddress);- const ownerPk = umiPublicKey(ownerAddress);- const assetSigner = generateSigner(umi);-- const createArgs = {- asset: assetSigner,- owner: ownerPk,- name: agentName.slice(0, 32) || 'Agent',- uri: metadataUri,- plugins: [- ...(attributes.length ? [{ type: 'Attributes', attributeList: attributes }] : []),- ...(royalty- ? [{- type: 'Royalties',- basisPoints: royalty.basisPoints,- creators: royalty.creators.map((c) => ({ address: umiPublicKey(c.address), percentage: c.percentage })),- ruleSet: ruleSet('None'),- }]- : []),- ],- };- if (collectionPk) {- createArgs.collection = collectionPk;- createArgs.authority = authoritySigner;- }-- const result = await create(umi, createArgs).sendAndConfirm(umi, {- confirm: { commitment: 'confirmed' },- });- const asset = assetSigner.publicKey.toString();- const signature = bs58.encode(result.signature);-- // 6. Persist the on-chain identity. Mainnet writes the canonical fields- // every read path keys on; devnet is isolated under meta.devnet.- const onchain = {- chain: `solana:${SOLANA_REFS[network]}`,- family: 'solana',- cluster: network,- onchain_id: asset,- sol_asset: asset,- contract_or_mint: asset,- metadata_uri: metadataUri,- owner: ownerAddress,- custody: true,- tx_hash: signature,- ...(collectionAddr ? { collection: collectionAddr } : {}),- confirmed_at: new Date().toISOString(),- };- const merged =- network === 'mainnet'- ? {- ...meta,- chain_type: 'solana',- network,- sol_mint_address: asset,- ...(collectionAddr ? { collection: collectionAddr, update_authority: 'threews' } : {}),- onchain,- }- : { ...meta, devnet: { sol_mint_address: asset, collection: collectionAddr || null, onchain } };-- await sql`- UPDATE agent_identities- SET meta = ${JSON.stringify(merged)}::jsonb, updated_at = NOW()- WHERE id = ${agent.id}- `;-- await sql`- INSERT INTO agent_actions (agent_id, type, payload, source_skill)- VALUES (- ${agent.id},- ${'solana.deploy'},- ${JSON.stringify({ asset, network, signature, collection: collectionAddr || null, owner: ownerAddress, source: 'bulk_onchain' })}::jsonb,- ${'bulk_onchain'}- )- `.catch(() => {});-- // Truthful on-chain feed event — fired only after the tx confirms.- if (network === 'mainnet') {- publishFeedEvent({- type: 'agent-onchain',- ts: Date.now(),- actor: agentName,- agentId: agent.id,- name: agentName,- chain: 'Solana',- }).catch(() => {});- }-deployed++;sse(res, 'deployed', {agent_id: agent.id,name: agentName,- asset,- owner: ownerAddress,- metadata_uri: metadataUri,- signature,- explorer_url: explorerUrl(asset, network),- avatar_thumb: image || null,+ asset: r.asset,+ owner: r.ownerAddress,+ metadata_uri: r.metadataUri,+ signature: r.signature,+ explorer_url: explorerUrl(r.asset, network),+ avatar_thumb: r.image || null,});} catch (err) {sse(res, 'error', { agent_id: agent.id, name: agentName, error: `deploy: ${err.message}` });diff --git a/api/bounties/[id].js b/api/bounties/[id].jsindex 08f6bddc9..57df7e857 100644--- a/api/bounties/[id].js+++ b/api/bounties/[id].js@@ -1,5 +1,6 @@import { sql } from '../_lib/db.js';import { cors, json, error, wrap, method } from '../_lib/http.js';+import { isUuid } from '../_lib/validate.js';export default wrap(async (req, res) => {if (cors(req, res)) return;@@ -7,6 +8,10 @@ export default wrap(async (req, res) => {const id = req.query?.id || req.url?.split('/').pop()?.split('?')[0];if (!id) return error(res, 400, 'bad_request', 'bounty id required');+ // Non-UUID segments (scanner junk, or sibling routes like /leaderboard that+ // resolve here when their own file is missing) must not reach a uuid-typed+ // query — that throws NeonDbError and 500s. Treat non-uuid ids as not found.+ if (!isUuid(id)) return error(res, 404, 'not_found', 'bounty not found');const [bounty] = await sql`SELECT b.*,diff --git a/api/bounties/leaderboard.js b/api/bounties/leaderboard.jsnew file mode 100644index 000000000..5b728cb17--- /dev/null+++ b/api/bounties/leaderboard.js@@ -0,0 +1,48 @@+// GET /api/bounties/leaderboard — top earners and top spenders on the bounty+// board, consumed by /go (src/go.js → loadLeaderboards).+//+// earners — users who won accepted bounty submissions, ranked by total USD+// spenders — users who posted resolved (closed) bounties, ranked by total USD+//+// USD figures come from bounties.reward_usd; a bounty with no reward_usd set+// still counts toward payout_count but contributes $0, which is correct — the+// board ranks realised value, not promised value.++import { sql } from '../_lib/db.js';+import { cors, json, wrap, method } from '../_lib/http.js';++const LIMIT = 10;++export default wrap(async (req, res) => {+ if (cors(req, res)) return;+ if (!method(req, res, ['GET'])) return;++ const [earners, spenders] = await Promise.all([+ sql`+ SELECT bs.user_id,+ MAX(bs.username) AS username,+ COUNT(*)::int AS payout_count,+ COALESCE(SUM(b.reward_usd), 0)::float AS total_usd+ FROM bounty_submissions bs+ JOIN bounties b ON b.id = bs.bounty_id AND b.deleted_at IS NULL+ WHERE bs.status = 'accepted'+ GROUP BY bs.user_id+ ORDER BY total_usd DESC, payout_count DESC+ LIMIT ${LIMIT}+ `,+ sql`+ SELECT b.user_id,+ MAX(b.username) AS username,+ COUNT(*)::int AS payout_count,+ COALESCE(SUM(b.reward_usd), 0)::float AS total_usd+ FROM bounties b+ WHERE b.status = 'closed' AND b.deleted_at IS NULL+ GROUP BY b.user_id+ ORDER BY total_usd DESC, payout_count DESC+ LIMIT ${LIMIT}+ `,+ ]);++ res.setHeader('cache-control', 's-maxage=60, stale-while-revalidate=300');+ return json(res, 200, { earners, spenders });+});diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex a3d3cf513..b6fa99d6f 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -764,19 +764,31 @@ async function handlePreview(req, res, id) {const history = body.history.map((m) => ({ role: m.role, content: m.content }));history.push({ role: 'user', content: body.message });+ // Bound the entire handler — failover attempts AND the token stream — to a+ // budget safely under Vercel's 30s function timeout. Without this, a slow+ // failover (one upstream times out, the next starts) or a slow-streaming+ // model pushes the request past 30s and Vercel kills it with a "Task timed+ // out" error instead of us flushing a clean `done`.+ const HANDLER_DEADLINE = Date.now() + 27_000;+ const budgetLeft = () => HANDLER_DEADLINE - Date.now();+// Try each configured provider in order; fail over on rate-limit (429) or- // provider errors (5xx). Each attempt is capped at 22s so a hung upstream- // can never push the request into Vercel's 30s function timeout.+ // provider errors (5xx). Each attempt is capped at 22s OR the remaining+ // handler budget, whichever is smaller.let upstream;let route;for (let i = 0; i < routes.length; i++) {route = routes[i];+ if (budgetLeft() <= 2_000) {+ if (!upstream) return error(res, 504, 'preview_timeout', 'preview timed out — try again');+ break;+ }try {upstream = await fetch(route.url, {method: 'POST',headers: route.headers,body: JSON.stringify(route.buildPayload({ systemPrompt, history })),- signal: AbortSignal.timeout(22_000),+ signal: AbortSignal.timeout(Math.min(22_000, budgetLeft())),});} catch (fetchErr) {const reason = fetchErr?.name === 'TimeoutError' ? 'timed out' : fetchErr.message;@@ -805,8 +817,8 @@ async function handlePreview(req, res, id) {const started = Date.now();const out = route.style === 'anthropic'- ? await streamAnthropicPreview(upstream, sendSSE)- : await streamOpenAIPreview(upstream, sendSSE);+ ? await streamAnthropicPreview(upstream, sendSSE, HANDLER_DEADLINE)+ : await streamOpenAIPreview(upstream, sendSSE, HANDLER_DEADLINE);if (out.error) {sendSSE({ type: 'error', code: 'stream_error', message: 'stream interrupted' });@@ -879,13 +891,19 @@ function buildPreviewRoutes() {return routes;}-async function streamAnthropicPreview(upstream, sendSSE) {+async function streamAnthropicPreview(upstream, sendSSE, deadline = Infinity) {const reader = upstream.body.getReader();const decoder = new TextDecoder();let buf = '';let reply = '';try {while (true) {+ // Stop reading before the handler's deadline so we can flush a clean+ // `done` instead of being hard-killed at the Vercel function timeout.+ if (Date.now() >= deadline) {+ reader.cancel().catch(() => {});+ break;+ }const { value, done } = await reader.read();if (done) break;buf += decoder.decode(value, { stream: true });@@ -909,13 +927,19 @@ async function streamAnthropicPreview(upstream, sendSSE) {return { reply };}-async function streamOpenAIPreview(upstream, sendSSE) {+async function streamOpenAIPreview(upstream, sendSSE, deadline = Infinity) {const reader = upstream.body.getReader();const decoder = new TextDecoder();let buf = '';let reply = '';try {while (true) {+ // Stop reading before the handler's deadline so we can flush a clean+ // `done` instead of being hard-killed at the Vercel function timeout.+ if (Date.now() >= deadline) {+ reader.cancel().catch(() => {});+ break;+ }const { value, done } = await reader.read();if (done) break;buf += decoder.decode(value, { stream: true });diff --git a/api/pump/[action].js b/api/pump/[action].jsindex 0de7526a1..dea0e4589 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -58,7 +58,7 @@ import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';import { putObject, publicUrl as r2PublicUrl } from '../_lib/r2.js';import { env } from '../_lib/env.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { parse } from '../_lib/validate.js';+import { parse, isUuid } from '../_lib/validate.js';import { randomToken } from '../_lib/crypto.js';import { publishFeedEvent } from '../_lib/feed.js';import { normalizeGatewayURL } from '../../src/ipfs.js';@@ -1824,6 +1824,7 @@ async function handlePortfolio(req, res) {const agentId = url.searchParams.get('agentId');const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';if (!agentId) return error(res, 400, 'validation_error', 'agentId required');+ if (!isUuid(agentId)) return error(res, 404, 'not_found', 'agent not found');const [agent] = await sql`SELECT user_id, meta FROM agent_identities@@ -1925,6 +1926,8 @@ async function handleByAgent(req, res) {const avatarId = url.searchParams.get('avatar_id');if (!agentId && !avatarId)return error(res, 400, 'validation_error', 'agent_id or avatar_id required');+ if (agentId && !isUuid(agentId)) return error(res, 404, 'not_found', 'agent not found');+ if (avatarId && !isUuid(avatarId)) return error(res, 404, 'not_found', 'agent not found');let row;if (agentId) {@@ -2584,17 +2587,28 @@ async function handleLiveStream(req, res) {res.setHeader('connection', 'keep-alive');res.setHeader('x-accel-buffering', 'no');+ // EventSource auto-reconnects when the stream ends; hint a 1s backoff so the+ // rotation below is near-seamless rather than the browser's ~3s default.+ res.write('retry: 1000\n\n');+const ping = setInterval(() => {if (!res.writableEnded) res.write(': ping\n\n');}, 15_000);+ // Rotate the stream a few seconds BEFORE the Vercel function maxDuration+ // (60s — see vercel.json → functions["api/pump/[action].js"]). Ending the+ // response ourselves emits a clean `end` event and lets EventSource+ // reconnect; letting Vercel hit the hard limit instead kills the function+ // and logs a "Task timed out" error on every long-lived client connection.+ const STREAM_BUDGET_MS = 55_000;const maxDuration = setTimeout(() => {clearInterval(ping);+ stop?.();if (!res.writableEnded) {- res.write(`event: end\ndata: ${JSON.stringify({ reason: 'max-duration' })}\n\n`);+ res.write(`event: end\ndata: ${JSON.stringify({ reason: 'rotate' })}\n\n`);res.end();}- }, 60 * 60 * 1_000);+ }, STREAM_BUDGET_MS);const stop = connectPumpFunFeed({kind,diff --git a/scripts/deploy-agents-onchain.mjs b/scripts/deploy-agents-onchain.mjsnew file mode 100644index 000000000..56133030d--- /dev/null+++ b/scripts/deploy-agents-onchain.mjs@@ -0,0 +1,123 @@+#!/usr/bin/env node+/**+ * Deploy three.ws agents on-chain as Metaplex Core assets — CLI runner.+ * ---------------------------------------------------------------------------+ * Shares the exact mint logic with the live dashboard (api/admin/bulk-launch.js)+ * via api/_lib/onchain-deploy.js, so both produce identical on-chain assets.+ *+ * Start small (a 2-3 agent canary), verify on Solscan, then scale up.+ *+ * Usage (env comes from .env via Node's --env-file):+ * # preview which agents would deploy — no SOL, no writes:+ * node --env-file=.env scripts/deploy-agents-onchain.mjs --limit 3 --dry-run+ *+ * # real devnet run:+ * node --env-file=.env scripts/deploy-agents-onchain.mjs --network devnet --limit 3 --confirm+ *+ * # real mainnet run (spends SOL — requires --confirm):+ * node --env-file=.env scripts/deploy-agents-onchain.mjs --limit 3 --confirm+ *+ * Re-runs are safe: already-deployed agents are skipped automatically.+ */++import { LAMPORTS_PER_SOL } from '@solana/web3.js';+import { publicKey as umiPublicKey } from '@metaplex-foundation/umi';+import {+ authoritySecret,+ buildAuthorityUmi,+ funderLamports,+ fetchUndeployedAgents,+ resolveAgentCollection,+ deployAgentOnce,+ explorerUrl,+ EST_MINT_LAMPORTS,+} from '../api/_lib/onchain-deploy.js';++function arg(name, fallback) {+ const i = process.argv.indexOf(name);+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback;+}+function flag(name) {+ return process.argv.includes(name);+}++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+const sol = (lamports) => (lamports / LAMPORTS_PER_SOL).toFixed(4);++async function main() {+ const network = arg('--network', 'mainnet') === 'devnet' ? 'devnet' : 'mainnet';+ const limit = Math.min(500, Math.max(1, Number(arg('--limit', '3'))));+ const dryRun = flag('--dry-run');+ const confirmed = flag('--confirm');++ console.log('\nthree.ws — on-chain agent deploy (Metaplex Core)');+ console.log(` network: ${network} limit: ${limit} ${dryRun ? 'DRY RUN' : 'LIVE'}`);++ if (!authoritySecret()) {+ console.error('\n✗ Set SOLANA_AGENT_COLLECTION_AUTHORITY_KEY (or LAUNCH_FUNDER_SECRET) in .env.');+ process.exit(1);+ }++ const { umi, authoritySigner } = buildAuthorityUmi(network);+ const authorityPk = authoritySigner.publicKey;+ const balance = await funderLamports(umi, authorityPk);+ console.log(` funder: ${authorityPk.toString()} (${sol(balance)} SOL)\n`);++ const agents = await fetchUndeployedAgents(network, limit);+ console.log(`Found ${agents.length} agent(s) without an on-chain identity on ${network}:`);+ for (const a of agents) console.log(` • ${a.name || 'Agent'} (${String(a.id).slice(0, 8)})`);++ if (agents.length === 0) {+ console.log('\nNothing to do — every agent is already on-chain.');+ return;+ }++ if (dryRun) {+ console.log('\nDry run — no SOL spent, no writes. Re-run with --confirm to deploy.');+ return;+ }++ if (!confirmed) {+ console.error('\n✗ Refusing a live run without --confirm (it spends real SOL). Add --confirm to proceed.');+ process.exit(1);+ }++ // Resolve (or deploy) the collection up front.+ const collectionAddr = await resolveAgentCollection({+ umi,+ authoritySigner,+ network,+ onEvent: (_t, d) => console.log(`Collection [${d.source}]: ${d.address}${d.signature ? ` (deploy sig ${d.signature.slice(0, 12)}…)` : ''}`),+ });+ const collectionPk = umiPublicKey(collectionAddr);+ console.log('');++ let deployed = 0, errors = 0;+ for (const agent of agents) {+ const name = agent.name || 'Agent';+ const bal = await funderLamports(umi, authorityPk);+ if (bal < EST_MINT_LAMPORTS + 5000) {+ console.log(`\n⏸ Paused — funder low on SOL (${sol(bal)}). Top up and re-run.`);+ break;+ }+ process.stdout.write(`[${deployed + errors + 1}/${agents.length}] ${name} … `);+ try {+ const r = await deployAgentOnce({ umi, authoritySigner, collectionAddr, collectionPk, agent, network });+ deployed++;+ console.log(`✓ ${r.asset}`);+ console.log(` ${explorerUrl(r.asset, network)}`);+ } catch (err) {+ errors++;+ console.log(`✗ ${err.message}`);+ }+ await sleep(400);+ }++ console.log(`\nDone — deployed: ${deployed}, errors: ${errors}.`);+ if (deployed > 0) console.log(`Collection: ${explorerUrl(collectionAddr, network)}`);+}++main().catch((err) => {+ console.error('\n✗ Fatal:', err?.stack || err?.message || err);+ process.exit(1);+});