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
pump trade quote signers + relayer balance cron, erc8004 validation report/card, changelog sync
nirholas70a6b78a1e08
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f17283d2b..75c21e8a4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-15+- **Autonomous coin buybacks and creator-fee distributions now run on schedule** — Coins launched through three.ws with autopilot enabled now have their buybacks and creator-fee distributions executed automatically on an hourly schedule, instead of waiting for a manual trigger. A new balance watchdog checks every Solana signer the platform uses to pay on-chain fees and alerts the team the moment one runs low, so autopilot never silently stalls for lack of gas. No action needed from coin owners — it just works in the background. `[improvement, infra]`- **Launchpad Studio: pick your avatar from your own agents and the gallery** — Building a launchpad in Launchpad Studio (three.ws/launchpad) no longer means hunting down a model URL by hand. The avatar picker now shows three sections: your own three.ws agents (when you're signed in), the platform avatar gallery with a Show more button to browse deeper, and a collapsed Or enter a URL field for power users who want to paste a custom .glb. Thumbnails load lazily, the selected avatar updates the live 3D preview instantly, and your choice is saved with the published page. (`/launchpad`) `[feature, improvement]`- **Pump Visualizer’s Trending view fixed — spheres now sized by real market cap** — The Trending mode of the 3D Pump Visualizer (three.ws/pump-visualizer) now renders correctly: every coin appears as a sphere sized by its real USD market cap, textured with its actual logo, with a full detail panel showing market cap, all-time-high, replies, age, and socials. Previously Trending failed to load because the market data it relied on wasn’t reaching the scene. Click a sphere to inspect it, or double-click to open the full 3D coin page. The live Firehose and Migrations modes are unchanged. (`/pump-visualizer`) `[fix, improvement]`@@ -376,7 +377,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Community** (`/community`) — Featured creators, builds, and conversations from the three.ws community.- **How to Embed 3D On-Chain Agents on Your Site** (`/blog/how-to-embed-3d-onchain-agents`) — A complete walkthrough for embedding a three.ws 3D on-chain agent on any website using the <agent-3d> web component — from setup to CORS configuration and page integration.- **Pump Dashboard** (`/pump-dashboard`) — Pump.fun trading desk: watchlists, scanner, quotes, portfolio, and live charts.-- **Pump Live** (`/pump-live`) — Real-time SSE feed of every pump.fun launch as it happens.+- **Pump Live** (`/pump-live`) — Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.- **Pump Visualizer** (`/pump-visualizer`) — 3D visualizer of trending pump.fun tokens — live market data rendered as an interactive scene.- **Tutorials** (`/tutorials`) — Step-by-step build guides.- **Avatar reactions to market events** — Community and personal avatar selection with real-time gesture animations during market events. `[improvement]`diff --git a/api/_lib/migrations/2026-06-14-pump-trades-quote.sql b/api/_lib/migrations/2026-06-14-pump-trades-quote.sqlnew file mode 100644index 000000000..7f2ed87d1--- /dev/null+++ b/api/_lib/migrations/2026-06-14-pump-trades-quote.sql@@ -0,0 +1,34 @@+-- Migration: record the quote (pairing) asset on every pump.fun trade.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-06-14-pump-trades-quote.sql+-- Idempotent.+--+-- pump_agent_trades originally modelled SOL only: a `sol_amount` lamports column+-- and nothing recording which quote currency a trade settled in. pump.fun v2+-- coins can be USDC-paired (buy_v2/sell_v2 against a USDC curve), and our launch,+-- wallet-signed, and custodial trade paths all support that now. These columns+-- make the trade row self-describing for both quote assets:+-- quote_mint → the quote SPL mint (WSOL mint for SOL-paired, USDC mint for USDC).+-- quote_symbol → 'SOL' | 'USDC' | 'OTHER' — a stable display label.+-- quote_amount → atomic units of the quote asset spent (buy) / received (sell).+-- For SOL trades this equals sol_amount (lamports); for USDC it+-- is 6-decimal USDC atomics. New code reads quote_amount.+-- sol_amount is kept (not dropped) for backward compatibility.++begin;++alter table pump_agent_trades+ add column if not exists quote_mint text;+alter table pump_agent_trades+ add column if not exists quote_symbol text;+alter table pump_agent_trades+ add column if not exists quote_amount numeric(40, 0);++-- Backfill legacy rows: every pre-existing trade is SOL-paired, so the quote is+-- wrapped SOL and the quote amount is the lamports already stored in sol_amount.+update pump_agent_trades+ set quote_mint = 'So11111111111111111111111111111111111111112',+ quote_symbol = 'SOL',+ quote_amount = sol_amount+ where quote_mint is null;++commit;diff --git a/api/_lib/pump-trade-args.js b/api/_lib/pump-trade-args.jsindex 2893303dd..4931127b5 100644--- a/api/_lib/pump-trade-args.js+++ b/api/_lib/pump-trade-args.js@@ -19,9 +19,22 @@import { PublicKey } from '@solana/web3.js';+import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';+export const SPL_TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');export const TOKEN_2022_PROGRAM_ID = new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');+// Wrapped SOL — the canonical quote mint for SOL-paired v2 coins. On-chain SOL+// curves store `bonding_curve.quote_mint` as the system-default pubkey (all+// zeros); both that and the explicit WSOL mint mean "SOL-paired".+export const WSOL_MINT = 'So11111111111111111111111111111111111111112';+const SYSTEM_DEFAULT_PUBKEY = '11111111111111111111111111111111';++/** The USDC mint for a network ('mainnet' | 'devnet'). */+export function usdcMintForNetwork(network) {+ return network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;+}+const KNOWN_TOKEN_PROGRAMS = new Set([SPL_TOKEN_PROGRAM_ID.toBase58(),TOKEN_2022_PROGRAM_ID.toBase58(),@@ -59,3 +72,42 @@ export function resolveTokenProgramForMintOwner(owner) {}return ownerPk.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : SPL_TOKEN_PROGRAM_ID;}++/**+ * Resolve the quote asset for a custodial (server-signed) pump.fun trade from the+ * coin's on-chain bonding-curve quote mint. Mirrors the wallet-signed resolution+ * in api/pump/[action].js (handleBuyPrep / handleSellPrep) so the autonomous and+ * wallet paths always agree on which currency a coin trades in.+ *+ * A SOL-paired curve stores `quote_mint` as null/undefined (older fetches) or the+ * system-default pubkey (all zeros); the explicit WSOL mint means the same thing.+ * Anything else is a stable/SPL quote: USDC when it matches the network USDC mint,+ * otherwise OTHER.+ *+ * Pure — no chain access — so it is unit-testable in isolation.+ *+ * @param {import('@solana/web3.js').PublicKey|string|null|undefined} curveQuoteMint+ * `bondingCurve.quoteMint` from the on-chain curve.+ * @param {'mainnet'|'devnet'} [network='mainnet']+ * @returns {{ isSol: boolean, isUsdc: boolean, quoteSymbol: 'SOL'|'USDC'|'OTHER', quoteMint: string }}+ * - `isSol`: SOL-paired — trade in native SOL, no quote ATA needed.+ * - `isUsdc`: USDC-paired — trade in USDC, requires the agent's USDC ATA.+ * - `quoteMint`: canonical mint string to build/record against (WSOL for SOL).+ * - `quoteSymbol`: stable display/record label.+ */+export function resolveCustodialQuote(curveQuoteMint, network = 'mainnet') {+ const raw =+ curveQuoteMint == null+ ? ''+ : curveQuoteMint instanceof PublicKey+ ? curveQuoteMint.toBase58()+ : String(curveQuoteMint).trim();++ if (!raw || raw === WSOL_MINT || raw === SYSTEM_DEFAULT_PUBKEY) {+ return { isSol: true, isUsdc: false, quoteSymbol: 'SOL', quoteMint: WSOL_MINT };+ }+ if (raw === usdcMintForNetwork(network)) {+ return { isSol: false, isUsdc: true, quoteSymbol: 'USDC', quoteMint: raw };+ }+ return { isSol: false, isUsdc: false, quoteSymbol: 'OTHER', quoteMint: raw };+}diff --git a/api/_lib/pumpfun-mcp.js b/api/_lib/pumpfun-mcp.jsindex f7377ed9d..e97e1015e 100644--- a/api/_lib/pumpfun-mcp.js+++ b/api/_lib/pumpfun-mcp.js@@ -1,13 +1,19 @@// Pumpfun MCP client — HTTP jsonrpc transport.//-// Makes JSON-RPC calls to a MCP bot server (PUMPFUN_BOT_URL) for real-time-// pump.fun intelligence. Falls back to Redis for graduations when bot not configured.+// Makes JSON-RPC calls to an optional upstream MCP bot (PUMPFUN_BOT_URL) for+// claims / token-intel / creator-intel enrichment. The bot is an OPTIONAL+// enrichment layer: when it is unset (the prod default) or unreachable,+// graduations are served from the live, WS-fed `pumpfun_graduations` Postgres+// table — the same source /api/pump/recent-graduations reads — so the+// graduations tool never silently degrades to empty. A legacy `pf:graduations`+// Redis list is kept only as a last-resort fallback.//// Env:-// PUMPFUN_BOT_URL HTTP endpoint for the MCP bot (enables bot-backed calls)+// PUMPFUN_BOT_URL HTTP endpoint for the upstream MCP bot (optional enrichment)// PUMPFUN_BOT_TOKEN Optional Bearer token for MCP bot auth-// UPSTASH_REDIS_REST_URL required for Redis graduation feed fallback-// UPSTASH_REDIS_REST_TOKEN required for Redis graduation feed fallback+// DATABASE_URL live graduation source (pumpfun_graduations, via ws-feed)+// UPSTASH_REDIS_REST_URL legacy Redis graduation feed fallback+// UPSTASH_REDIS_REST_TOKEN legacy Redis graduation feed fallback// GRADUATIONS_LIST_KEY default: pf:graduationsimport { env } from './env.js';@@ -21,6 +27,22 @@ export function pumpfunBotEnabled() {return !!(process.env.PUMPFUN_BOT_URL);}+// Live graduation source, newest-first. Reads the WS-fed `pumpfun_graduations`+// Postgres table (kept fresh by the live SSE feed + the pumpfun-graduations-sync+// cron). Falls back to the legacy `pf:graduations` Redis list only when the DB+// path yields nothing, so the graduations tool returns real data whether or not+// the optional upstream bot is configured.+async function liveGraduations(limit = 20) {+ try {+ const { recentGraduations } = await import('./pumpfun-ws-feed.js');+ const items = await recentGraduations({ limit });+ if (Array.isArray(items) && items.length) return items;+ } catch (err) {+ console.error('[pumpfun-mcp] live graduations read failed:', err?.message || err);+ }+ return readGraduations(limit);+}+async function readGraduations(limit = 20) {const r = redis();if (!r) return [];@@ -80,8 +102,14 @@ export const pumpfunMcp = {return jsonrpc('getTokenIntel', { mint });},async graduations({ limit = 20 } = {}) {- if (pumpfunBotEnabled()) return jsonrpc('getGraduations', { limit });- const items = await readGraduations(limit);+ if (pumpfunBotEnabled()) {+ const r = await jsonrpc('getGraduations', { limit });+ const arr = Array.isArray(r.data) ? r.data : r.data?.items;+ if (r.ok && Array.isArray(arr) && arr.length) return { ok: true, data: arr };+ // Bot configured but unreachable / empty — fall through to the live+ // WS-fed table rather than surfacing an error or empty result.+ }+ const items = await liveGraduations(limit);return { ok: true, data: items };},async creatorIntel({ wallet } = {}) {diff --git a/api/_lib/solana-signers.js b/api/_lib/solana-signers.jsnew file mode 100644index 000000000..eab648bad--- /dev/null+++ b/api/_lib/solana-signers.js@@ -0,0 +1,161 @@+// @ts-check+// Single source of truth for every Solana fee-paying signer the platform reads.+//+// Each signer is a keypair stored in an env var (NEVER committed). The platform+// loads it to pay transaction fees / rent for an on-chain flow. If one silently+// runs dry, that flow stops working with no warning — so the balance-check cron+// (api/cron/relayer-balance-check.js) and the operator script+// (scripts/check-relayer-balances.mjs) both read this registry, derive each+// pubkey, and compare its SOL balance against `minSol`.+//+// The human-readable companion (purpose, network, encoding, funding runbook) is+// tasks/onchain-deployment/SOLANA-SIGNERS.md — keep the two in sync.+//+// Encodings differ across signers (base64 of 64 raw bytes, base58, JSON array).+// `loadKeypairFromSecret` auto-detects, so callers never need to know which.++/**+ * @typedef {Object} SignerSpec+ * @property {string} name human label for alerts/logs+ * @property {string} env the env var holding the secret+ * @property {number} minSol alert/refill threshold in SOL (mainnet)+ * @property {string} purpose what this keypair pays for+ * @property {'mainnet'|'devnet'|'both'} network where it spends real SOL+ */++/** @type {SignerSpec[]} */+export const SOLANA_SIGNERS = [+ {+ name: 'pump-cron-relayer',+ env: 'PUMP_CRON_RELAYER_SECRET_KEY_B64',+ minSol: 0.1,+ purpose: 'pays fees + swap gas for the buyback and distribute-payments crons',+ network: 'both',+ },+ {+ name: 'pump-x402-launcher',+ env: 'PUMP_X402_LAUNCHER_SECRET_KEY_B64',+ minSol: 0.1,+ purpose: 'fronts the ~0.022 SOL deploy cost for x402 pay-per-call pump.fun launches',+ network: 'mainnet',+ },+ {+ name: 'sns-parent-owner',+ env: 'THREEWS_SOL_PARENT_SECRET_BASE58',+ minSol: 0.05,+ purpose: 'owns threews.sol; pays rent/fees minting *.threews.sol subdomains',+ network: 'mainnet',+ },+ {+ name: 'coin-treasury',+ env: 'COIN_TREASURY_SECRET_KEY_B64',+ minSol: 0.05,+ purpose: 'signs lottery/reflection distribution txs for launched coins',+ network: 'mainnet',+ },+ {+ name: 'club-treasury',+ env: 'CLUB_SOLANA_TREASURY_SECRET_KEY_B64',+ minSol: 0.05,+ purpose: 'pays USDC tip-sweep transfers + recipient ATA rent (club-payouts cron)',+ network: 'mainnet',+ },+ {+ name: 'platform-treasury',+ env: 'PLATFORM_TREASURY_KEYPAIR',+ fallbackEnv: 'TREASURY_KEYPAIR',+ minSol: 0.05,+ purpose: 'pays SPL withdrawal gas (process-withdrawals cron)',+ network: 'mainnet',+ },+ {+ name: 'a2a-payer',+ env: 'A2A_PAYER_SOLANA_SECRET',+ fallbackEnv: 'A2A_PAYER_SOLANA_PRIVATE_KEY',+ minSol: 0.02,+ purpose: 'co-signs SPL TransferChecked for agent-to-agent mandate settlements',+ network: 'mainnet',+ },+ {+ name: 'collection-authority',+ env: 'SOLANA_AGENT_COLLECTION_AUTHORITY_KEY',+ minSol: 0.02,+ purpose: 'creates/manages the three.ws agent NFT collection',+ network: 'both',+ },+];++/**+ * Decode a Solana secret key from any of the encodings used across the env:+ * - JSON array of 64 ints (Solana CLI keypair file contents)+ * - base64 of the 64 raw secret-key bytes (…_B64 vars)+ * - base58 of the 64 raw secret-key bytes (…_BASE58 vars)+ * Returns the 64-byte Uint8Array, or null if it can't be decoded.+ * @param {string} secret+ * @returns {Promise<Uint8Array|null>}+ */+export async function decodeSecretKey(secret) {+ const raw = (secret || '').trim();+ if (!raw) return null;++ // JSON array form+ if (raw.startsWith('[')) {+ try {+ const arr = JSON.parse(raw);+ if (Array.isArray(arr) && (arr.length === 64 || arr.length === 32)) {+ return Uint8Array.from(arr);+ }+ } catch {+ /* fall through */+ }+ }++ // base64 form (…_B64). Buffer.from is lenient, so validate the byte length.+ try {+ const buf = Buffer.from(raw, 'base64');+ if (buf.length === 64 || buf.length === 32) {+ // Guard against base58 strings that happen to base64-decode to 64 bytes:+ // re-encode and compare, accept only on round-trip match.+ if (buf.toString('base64').replace(/=+$/, '') === raw.replace(/=+$/, '')) {+ return new Uint8Array(buf);+ }+ }+ } catch {+ /* fall through */+ }++ // base58 form (…_BASE58)+ try {+ const bs58mod = await import('bs58');+ const bs58 = bs58mod.default || bs58mod;+ const bytes = bs58.decode(raw);+ if (bytes.length === 64 || bytes.length === 32) return Uint8Array.from(bytes);+ } catch {+ /* fall through */+ }++ return null;+}++/**+ * Resolve a SignerSpec to a loaded keypair pubkey (base58) using whichever env+ * var (primary or fallback) is set. Returns null when neither is configured or+ * the secret can't be decoded.+ * @param {SignerSpec & { fallbackEnv?: string }} spec+ * @returns {Promise<{ configured: boolean, pubkey: string|null, decodeError: boolean }>}+ */+export async function resolveSignerPubkey(spec) {+ const secret = process.env[spec.env] || (spec.fallbackEnv ? process.env[spec.fallbackEnv] : '');+ if (!secret) return { configured: false, pubkey: null, decodeError: false };++ const bytes = await decodeSecretKey(secret);+ if (!bytes) return { configured: true, pubkey: null, decodeError: true };++ const { Keypair } = await import('@solana/web3.js');+ try {+ const kp = Keypair.fromSecretKey(bytes);+ return { configured: true, pubkey: kp.publicKey.toBase58(), decodeError: false };+ } catch {+ return { configured: true, pubkey: null, decodeError: true };+ }+}diff --git a/api/agents/pumpfun/[action].js b/api/agents/pumpfun/[action].jsindex 684b43121..18b3d0d9b 100644--- a/api/agents/pumpfun/[action].js+++ b/api/agents/pumpfun/[action].js@@ -63,12 +63,21 @@ export default wrap(async (req, res) => {// ── buy ────────────────────────────────────────────────────────────────────-const buyBodySchema = z.object({- mint: z.string().min(32).max(64),- solAmount: z.number().positive().max(1000),- slippageBps: z.number().int().min(0).max(10_000).default(500),- network: z.enum(['mainnet', 'devnet']).default('mainnet'),-});+const buyBodySchema = z+ .object({+ mint: z.string().min(32).max(64),+ // A coin is paired against exactly one quote asset on-chain. SOL-paired+ // coins spend SOL; USDC-paired coins spend USDC. The curve decides which,+ // so the caller supplies the matching amount and the server validates it.+ solAmount: z.number().positive().max(1000).optional(),+ usdcAmount: z.number().positive().max(1_000_000).optional(),+ slippageBps: z.number().int().min(0).max(10_000).default(500),+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),+ })+ .refine((v) => (v.solAmount ?? 0) > 0 || (v.usdcAmount ?? 0) > 0, {+ message: 'solAmount or usdcAmount required',+ path: ['solAmount'],+ });async function handleBuy(req, res, id) {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;@@ -90,21 +99,21 @@ async function handleBuy(req, res, id) {if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);const { keypair, meta } = loaded;- const [{ PumpSdk, OnlinePumpSdk, getBuyTokenAmountFromSolAmount, isLegacyQuoteMint }, BN] =- await Promise.all([- import('@pump-fun/pump-sdk'),- import('bn.js').then((m) => m.default || m),- ]);- const { slippagePercentFromBps, resolveTokenProgramForMintOwner } =+ const [{ PumpSdk, OnlinePumpSdk, getBuyTokenAmountFromSolAmount }, BN] = await Promise.all([+ import('@pump-fun/pump-sdk'),+ import('bn.js').then((m) => m.default || m),+ ]);+ const { slippagePercentFromBps, resolveTokenProgramForMintOwner, resolveCustodialQuote } =await import('../../_lib/pump-trade-args.js');const conn = solanaConnection(body.network);const online = new OnlinePumpSdk(conn);const sdk = new PumpSdk();const mint = new PublicKey(body.mint);- const solLamports = new BN(Math.floor(body.solAmount * 1e9));let instructions;+ let quote; // resolved quote asset { isSol, isUsdc, quoteSymbol, quoteMint }+ let quoteAtomics; // BN — units of the quote asset this buy spendstry {// base_token_program must match the mint owner — Token-2022 for create_v2// coins (every coin pump.fun mints today), SPL Token for legacy coins.@@ -117,41 +126,118 @@ async function handleBuy(req, res, id) {online.fetchFeeConfig().catch(() => null),online.fetchBuyState(mint, keypair.publicKey, tokenProgram),]);- // This endpoint spends the custodial wallet's SOL — a USDC-paired coin- // cannot be bought with solAmount. Reject cleanly instead of building a- // transaction the program will refuse.- if (state.bondingCurve.quoteMint && !isLegacyQuoteMint(state.bondingCurve.quoteMint)) {++ // Resolve the coin's quote asset from the on-chain curve before building+ // anything — the same resolution the wallet-signed path uses — so a+ // USDC-paired coin is bought with USDC, not a SOL trade the curve refuses.+ quote = resolveCustodialQuote(state.bondingCurve?.quoteMint, body.network);+ if (!quote.isSol && !quote.isUsdc) {return error(res,409,- 'usdc_paired_coin',- 'coin is stable-paired (non-SOL quote) — custodial buys are SOL-denominated; use /api/pump/buy-prep with usdc_amount',+ 'unsupported_quote',+ `coin is ${quote.quoteSymbol}-paired — custodial trading supports SOL and USDC quote assets only`,);}- const expected = getBuyTokenAmountFromSolAmount({- global,- feeConfig,- mintSupply: state.bondingCurve.tokenTotalSupply,- bondingCurve: state.bondingCurve,- amount: solLamports,- });- if (!expected.gt(new BN(0)))- return error(res, 400, 'amount_too_small', 'solAmount too small to buy any tokens');- // Unified v2 buy (UPSTREAM-buy-sell-v2-announcement.md): works for all- // coins, SDK derives the wSOL quote from the curve, applies the percent- // slippage pad to max_quote_cost, and handles the mayhem fee pool.- instructions = await sdk.buyV2Instructions({- global,- bondingCurveAccountInfo: state.bondingCurveAccountInfo,- bondingCurve: state.bondingCurve,- associatedUserAccountInfo: state.associatedUserAccountInfo,- mint,- user: keypair.publicKey,- amount: expected,- quoteAmount: solLamports,- slippage: slippagePercentFromBps(body.slippageBps, { defaultBps: 500 }),- tokenProgram,- });++ if (quote.isUsdc) {+ if (body.usdcAmount == null)+ return error(res, 400, 'validation_error', 'usdcAmount required for USDC-paired coin');+ const quoteMintPk = new PublicKey(quote.quoteMint);+ // quote_token_program must match the quote mint's owner (USDC is SPL+ // Token today; read it from chain so a future quote can't break us).+ const quoteInfo = await conn.getAccountInfo(quoteMintPk);+ if (!quoteInfo)+ return error(+ res,+ 404,+ 'quote_mint_not_found',+ `quote mint ${quote.quoteMint} not found on ${body.network}`,+ );+ const quoteTokenProgram = resolveTokenProgramForMintOwner(quoteInfo.owner);+ quoteAtomics = new BN(Math.round(body.usdcAmount * 1_000_000));++ // Custodial USDC buys spend from the agent wallet's USDC ATA. Confirm+ // it holds enough up front so the trade fails here with a clear error+ // instead of a cryptic on-chain insufficient-funds revert.+ const { getAssociatedTokenAddressSync } = await import('@solana/spl-token');+ const usdcAta = getAssociatedTokenAddressSync(+ quoteMintPk,+ keypair.publicKey,+ true,+ quoteTokenProgram,+ );+ let haveAtomics = 0n;+ try {+ const bal = await conn.getTokenAccountBalance(usdcAta);+ haveAtomics = BigInt(bal?.value?.amount ?? 0);+ } catch {+ haveAtomics = 0n; // missing/closed ATA → treat as zero balance+ }+ if (haveAtomics < BigInt(quoteAtomics.toString()))+ return error(+ res,+ 402,+ 'insufficient_usdc',+ `agent wallet holds ${Number(haveAtomics) / 1e6} USDC, needs ${body.usdcAmount}`,+ );++ // buy_v2's `amount` is the base-token quantity to buy and must be > 0;+ // derive it from the USDC input against the curve, passing quoteMint so+ // the SDK prices in USDC (mirrors handleBuyPrep in api/pump/[action].js).+ const tokenAmount = getBuyTokenAmountFromSolAmount({+ global,+ feeConfig,+ mintSupply: state.bondingCurve.tokenTotalSupply,+ bondingCurve: state.bondingCurve,+ amount: quoteAtomics,+ quoteMint: quoteMintPk,+ });+ if (!tokenAmount.gt(new BN(0)))+ return error(res, 400, 'amount_too_small', 'usdcAmount too small to buy any tokens');+ instructions = await sdk.buyV2Instructions({+ global,+ bondingCurveAccountInfo: state.bondingCurveAccountInfo,+ bondingCurve: state.bondingCurve,+ associatedUserAccountInfo: state.associatedUserAccountInfo,+ mint,+ user: keypair.publicKey,+ amount: tokenAmount,+ quoteAmount: quoteAtomics,+ slippage: slippagePercentFromBps(body.slippageBps, { defaultBps: 500 }),+ tokenProgram,+ quoteTokenProgram,+ });+ } else {+ // SOL-paired buy (unchanged behaviour).+ if (body.solAmount == null)+ return error(res, 400, 'validation_error', 'solAmount required for SOL-paired coin');+ quoteAtomics = new BN(Math.floor(body.solAmount * 1e9));+ const expected = getBuyTokenAmountFromSolAmount({+ global,+ feeConfig,+ mintSupply: state.bondingCurve.tokenTotalSupply,+ bondingCurve: state.bondingCurve,+ amount: quoteAtomics,+ });+ if (!expected.gt(new BN(0)))+ return error(res, 400, 'amount_too_small', 'solAmount too small to buy any tokens');+ // Unified v2 buy (UPSTREAM-buy-sell-v2-announcement.md): SDK derives the+ // wSOL quote from the curve, applies the percent slippage pad to+ // max_quote_cost, and handles the mayhem fee pool.+ instructions = await sdk.buyV2Instructions({+ global,+ bondingCurveAccountInfo: state.bondingCurveAccountInfo,+ bondingCurve: state.bondingCurve,+ associatedUserAccountInfo: state.associatedUserAccountInfo,+ mint,+ user: keypair.publicKey,+ amount: expected,+ quoteAmount: quoteAtomics,+ slippage: slippagePercentFromBps(body.slippageBps, { defaultBps: 500 }),+ tokenProgram,+ });+ }} catch (err) {console.error('[pumpfun/buy] build failed', err);return error(@@ -162,17 +248,23 @@ async function handleBuy(req, res, id) {);}- // Atomically reserve this spend against the daily cap BEFORE sending so two- // concurrent buys on a stolen session can't both slip past the limit.- const reservation = await reserveSpend({- agentId: id,- meta,- mint: body.mint,- solAmount: body.solAmount,- type: 'pumpfun.buy',- payload: { slippageBps: body.slippageBps, network: body.network },- });- if (!reservation.ok) return error(res, reservation.status, reservation.code, reservation.msg);+ // Reserve against the daily SOL cap for SOL spends only — atomically, BEFORE+ // sending, so two concurrent buys on a stolen session can't both slip past+ // the limit. USDC buys move USDC, not SOL, so they are gated by the up-front+ // USDC balance check above instead of the SOL cap.+ let reservation = null;+ if (quote.isSol) {+ reservation = await reserveSpend({+ agentId: id,+ meta,+ mint: body.mint,+ solAmount: body.solAmount,+ type: 'pumpfun.buy',+ payload: { slippageBps: body.slippageBps, network: body.network },+ });+ if (!reservation.ok)+ return error(res, reservation.status, reservation.code, reservation.msg);+ }const tx = new Transaction().add(...instructions);tx.feePayer = keypair.publicKey;@@ -186,17 +278,39 @@ async function handleBuy(req, res, id) {await conn.confirmTransaction(signature, 'confirmed');} catch (err) {console.error('[pumpfun/buy] send failed', err);- await releaseSpend(reservation.reservationId);+ if (reservation) await releaseSpend(reservation.reservationId);return error(res, 502, 'rpc_error', err.message || 'transaction failed');}- await finalizeSpend(reservation.reservationId, {- mint: body.mint,- solAmount: body.solAmount,- slippageBps: body.slippageBps,- signature,- network: body.network,- });+ if (reservation) {+ await finalizeSpend(reservation.reservationId, {+ mint: body.mint,+ solAmount: body.solAmount,+ slippageBps: body.slippageBps,+ signature,+ network: body.network,+ });+ } else {+ // USDC buy: no SOL reservation row to finalize — record the action directly+ // so it still appears in the agent's activity/audit trail.+ await sql`+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)+ VALUES (+ ${id},+ ${'pumpfun.buy'},+ ${JSON.stringify({+ mint: body.mint,+ usdcAmount: body.usdcAmount,+ quoteMint: quote.quoteMint,+ quoteSymbol: quote.quoteSymbol,+ slippageBps: body.slippageBps,+ signature,+ network: body.network,+ })}::jsonb,+ ${'pumpfun'}+ )+ `.catch((e) => console.error('[pumpfun/buy] log failed', e));+ }// Mirror into pump_agent_trades for cross-feature analytics (reputation,// admin health, strategy backtests). Best-effort — agent may not have a@@ -206,14 +320,20 @@ async function handleBuy(req, res, id) {select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1`;if (m) {- const lamports = BigInt(Math.floor(body.solAmount * 1_000_000_000));+ // sol_amount stays lamports (SOL buys only); quote_amount carries the+ // spent amount in the coin's own quote asset for both SOL and USDC.+ const solLamports = quote.isSol+ ? BigInt(Math.floor(body.solAmount * 1_000_000_000)).toString()+ : null;await sql`INSERT INTO pump_agent_trades- (mint_id, user_id, wallet, direction, route, sol_amount, slippage_bps, tx_signature, network)+ (mint_id, user_id, wallet, direction, route, sol_amount, slippage_bps, tx_signature, network,+ quote_mint, quote_symbol, quote_amount)VALUES(${m.id}, ${auth.userId}, ${keypair.publicKey.toBase58()}, 'buy',- 'bonding_curve', ${lamports.toString()}, ${body.slippageBps || null},- ${signature}, ${body.network})+ 'bonding_curve', ${solLamports}, ${body.slippageBps || null},+ ${signature}, ${body.network},+ ${quote.quoteMint}, ${quote.quoteSymbol}, ${quoteAtomics.toString()})ON CONFLICT (tx_signature, network) DO NOTHING`;}@@ -225,7 +345,9 @@ async function handleBuy(req, res, id) {data: {signature,mint: body.mint,- solAmount: body.solAmount,+ ...(quote.isSol+ ? { solAmount: body.solAmount }+ : { usdcAmount: body.usdcAmount, quoteMint: quote.quoteMint }),explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,},});diff --git a/api/cron/[name].js b/api/cron/[name].jsindex baa8b3638..02a68a62c 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -14,6 +14,7 @@* pump-agent-stats → handlePumpAgentStats* pumpfun-monitor → handlePumpfunMonitor* pumpfun-signals → handlePumpfunSignals+ * pumpfun-graduations-sync → handlePumpfunGraduationsSync* run-buyback → handleRunBuyback* run-dca → handleRunDca* run-distribute-payments → handleRunDistributePayments@@ -85,6 +86,7 @@ const HANDLERS = {'pump-agent-stats': handlePumpAgentStats,'pumpfun-monitor': handlePumpfunMonitor,'pumpfun-signals': handlePumpfunSignals,+ 'pumpfun-graduations-sync': handlePumpfunGraduationsSync,'run-buyback': handleRunBuyback,'run-dca': handleRunDca,'run-distribute-payments': handleRunDistributePayments,@@ -1355,16 +1357,20 @@ async function handlePumpfunSignals(req, res) {if (!requireCron(req, res)) return;- if (!pumpfunBotEnabled()) {- return json(res, 200, { skipped: 'pumpfun bot not configured' });- }+ // Graduations come from the live WS-fed table (pumpfunMcp.graduations falls+ // back to Postgres), so the graduation→signal path runs with or without the+ // optional upstream bot. Claims enrichment still requires the bot, so it's+ // skipped cleanly when the bot is unset.+ const botEnabled = pumpfunBotEnabled();const [claims, grads] = await Promise.all([- pumpfunMcp.recentClaims({ limit: CLAIMS_PER_RUN }),+ botEnabled+ ? pumpfunMcp.recentClaims({ limit: CLAIMS_PER_RUN })+ : Promise.resolve({ ok: true, data: [] }),pumpfunMcp.graduations({ limit: GRADS_PER_RUN }),]);- const report = { claims: 0, graduations: 0, inserted: 0, skipped: 0, errors: [] };+ const report = { bot: botEnabled, claims: 0, graduations: 0, inserted: 0, skipped: 0, errors: [] };const claimItems = pumpfunArr(claims.ok ? claims.data : null);const gradItems = pumpfunArr(grads.ok ? grads.data : null);@@ -1422,6 +1428,77 @@ async function handlePumpfunSignals(req, res) {return json(res, 200, report);}+// ═══════════════════════════════════════════════════════════════════════════+// pumpfun-graduations-sync+// ═══════════════════════════════════════════════════════════════════════════+//+// Keeps the `pumpfun_graduations` table fresh independently of browser traffic.+//+// The live feed (api/_lib/pumpfun-ws-feed.js) only persists graduations while a+// /api/pump SSE stream is open — on a serverless platform that means the table+// goes stale whenever nobody is watching the feed. This cron opens the same+// real PumpPortal migration stream for a bounded window each run; the feed's+// own persistGraduation() writes any graduations it observes, so+// /api/pump/recent-graduations and the MCP graduations tool stay live. No+// external bot or API key required — it's the public PumpPortal WebSocket.++const GRAD_SYNC_WINDOW_MS = 100_000;++async function handlePumpfunGraduationsSync(req, res) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;++ if (!requireCron(req, res)) return;++ const { connectPumpFunFeed } = await import('../_lib/pumpfun-ws-feed.js');++ const controller = new AbortController();+ const seen = new Map(); // tx signature → { mint, symbol }++ const stop = connectPumpFunFeed({+ kind: 'graduation',+ signal: controller.signal,+ onEvent: ({ kind, data }) => {+ if (kind !== 'graduation') return;+ const sig = data?.tx_signature || data?.signature;+ if (sig && !seen.has(sig)) seen.set(sig, { mint: data.mint, symbol: data.symbol || null });+ },+ });++ const before = await gradTableCount();+ await sleep(GRAD_SYNC_WINDOW_MS);+ controller.abort();+ try {+ stop?.();+ } catch {+ // stop() is best-effort — the abort already halted the feed.+ }+ // Let any in-flight enrich→persist writes settle before counting rows.+ await sleep(750);+ const after = await gradTableCount();++ return json(res, 200, {+ windowMs: GRAD_SYNC_WINDOW_MS,+ observed: seen.size,+ mints: [...seen.values()].map((v) => v.symbol || v.mint).slice(0, 25),+ table_total: after,+ inserted: before == null || after == null ? null : Math.max(0, after - before),+ });+}++async function gradTableCount() {+ try {+ const rows = await sql`select count(*)::int as n from pumpfun_graduations`;+ return rows?.[0]?.n ?? null;+ } catch (err) {+ console.warn('[pumpfun-graduations-sync] count failed:', err?.message);+ return null;+ }+}++function sleep(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}+function pumpfunArr(x) {if (!x) return [];return Array.isArray(x) ? x : x.items || [];diff --git a/api/cron/relayer-balance-check.js b/api/cron/relayer-balance-check.jsnew file mode 100644index 000000000..6d8b45c52--- /dev/null+++ b/api/cron/relayer-balance-check.js@@ -0,0 +1,115 @@+// @ts-check+// GET /api/cron/relayer-balance-check — Solana signer low-balance watchdog.+//+// Every Solana fee-paying signer (the pump buyback/distribute relayer, the SNS+// parent owner, the x402 launcher, the coin/club treasuries, …) pays real SOL+// for fees and rent. If one silently runs dry, its flow stops working with no+// error anyone sees — buybacks stop confirming, subdomain mints 502, withdrawals+// stall. This cron checks each configured signer's mainnet SOL balance against+// the documented minimum in api/_lib/solana-signers.js and fires a Telegram ops+// alert the moment one drops below it, so signers never silently run dry.+//+// Runs every 6 hours — slow on purpose. It only reads on-chain balances (one+// getBalance RPC per configured signer) and touches the Redis-backed alert+// dedup, so it adds negligible load and cannot burn the Upstash request quota.+//+// Env (reuses existing infra; no new secrets):+// CRON_SECRET — Vercel cron bearer auth (shared with other crons)+// TELEGRAM_BOT_TOKEN — ops alert bot (via sendOpsAlert)+// TELEGRAM_ALERTS_CHAT_ID — private ops channel (via sendOpsAlert)+// SOLANA_RPC_URL — mainnet RPC (defaults to api.mainnet-beta)+// Signer secrets themselves are optional: an unconfigured signer is skipped, not+// flagged — only configured-but-underfunded signers alert.++import { error, json, method, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sendOpsAlert } from '../_lib/alerts.js';+import { SOLANA_SIGNERS, resolveSignerPubkey } from '../_lib/solana-signers.js';++const LAMPORTS_PER_SOL = 1_000_000_000;++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) {+ error(res, 503, 'not_configured', 'CRON_SECRET unset');+ return false;+ }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) {+ error(res, 401, 'unauthorized', 'invalid cron secret');+ return false;+ }+ return true;+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+ const { Connection, PublicKey } = await import('@solana/web3.js');+ const connection = new Connection(rpcUrl, 'confirmed');++ const checked = [];+ const low = [];+ const errors = [];++ for (const spec of SOLANA_SIGNERS) {+ const resolved = await resolveSignerPubkey(spec);+ if (!resolved.configured) {+ checked.push({ name: spec.name, status: 'unconfigured' });+ continue;+ }+ if (resolved.decodeError || !resolved.pubkey) {+ errors.push({ name: spec.name, env: spec.env, reason: 'secret_decode_failed' });+ continue;+ }++ let lamports;+ try {+ lamports = await connection.getBalance(new PublicKey(resolved.pubkey), 'confirmed');+ } catch (e) {+ errors.push({ name: spec.name, pubkey: resolved.pubkey, reason: `rpc_error: ${e.message}` });+ continue;+ }++ const sol = lamports / LAMPORTS_PER_SOL;+ const entry = {+ name: spec.name,+ pubkey: resolved.pubkey,+ sol: Number(sol.toFixed(6)),+ minSol: spec.minSol,+ ok: sol >= spec.minSol,+ };+ checked.push(entry);+ if (!entry.ok) low.push({ ...entry, purpose: spec.purpose });+ }++ // One alert per underfunded signer (deduped hourly by pubkey, so a chronically+ // low signer pings once an hour, not on every run). A decode/RPC failure also+ // alerts — a signer we can't even read is itself an outage.+ for (const s of low) {+ await sendOpsAlert(+ `⛽ Solana signer low: ${s.name} ${s.sol} < ${s.minSol} SOL`,+ `${s.purpose}\npubkey: ${s.pubkey}\nFund it on mainnet, then this clears within 6h.`,+ { signature: `relayer-low:${s.pubkey}` },+ );+ }+ for (const e of errors) {+ await sendOpsAlert(+ `⛽ Solana signer unreadable: ${e.name}`,+ `reason: ${e.reason}${e.pubkey ? `\npubkey: ${e.pubkey}` : `\nenv: ${e.env}`}`,+ { signature: `relayer-err:${e.name}` },+ );+ }++ return json(res, 200, {+ ok: true,+ rpc: rpcUrl,+ checked,+ low_count: low.length,+ error_count: errors.length,+ });+});diff --git a/data/changelog.json b/data/changelog.jsonindex f6b9e652f..4e8eb8ab0 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,12 @@{"$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. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-15",+ "title": "Autonomous coin buybacks and creator-fee distributions now run on schedule",+ "summary": "Coins launched through three.ws with autopilot enabled now have their buybacks and creator-fee distributions executed automatically on an hourly schedule, instead of waiting for a manual trigger. A new balance watchdog checks every Solana signer the platform uses to pay on-chain fees and alerts the team the moment one runs low, so autopilot never silently stalls for lack of gas. No action needed from coin owners — it just works in the background.",+ "tags": ["improvement", "infra"]+ },{"date": "2026-06-15","title": "Launchpad Studio: pick your avatar from your own agents and the gallery",diff --git a/data/pages.json b/data/pages.jsonindex 44bc6c4eb..6a7be764a 100644--- a/data/pages.json+++ b/data/pages.json@@ -451,7 +451,7 @@{"path": "/pump-live","title": "Pump Live",- "description": "Real-time SSE feed of every pump.fun launch as it happens.",+ "description": "Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.","priority": 0.7,"changefreq": "daily","added": "2026-05-04"diff --git a/pages/pump-live.html b/pages/pump-live.htmlindex 5de4abb90..39b67799c 100644--- a/pages/pump-live.html+++ b/pages/pump-live.html@@ -260,16 +260,16 @@<meta property="og:type" content="website"><meta property="og:site_name" content="three.ws"><meta property="og:title" content="Pump Live · three.ws">- <meta property="og:description" content="Real-time SSE feed of every pump.fun launch as it happens.">+ <meta property="og:description" content="Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live."><meta property="og:url" content="https://three.ws/pump-live"><meta property="og:image" content="https://three.ws/og-image.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="Pump Live · three.ws">- <meta name="twitter:description" content="Real-time SSE feed of every pump.fun launch as it happens.">+ <meta name="twitter:description" content="Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live."><meta name="twitter:image" content="https://three.ws/og-image.png">- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Pump Live","description":"Real-time SSE feed of every pump.fun launch as it happens.","url":"https://three.ws/pump-live","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Pump Live","description":"Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.","url":"https://three.ws/pump-live","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script></head><body><header><div id="nav-container"></div></header>diff --git a/public/.well-known/3d-agent-card.json b/public/.well-known/3d-agent-card.jsonnew file mode 100644index 000000000..9673bb56f--- /dev/null+++ b/public/.well-known/3d-agent-card.json@@ -0,0 +1,51 @@+{+ "type": [+ "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",+ "https://three.ws/specs/3d-agent-card-v1"+ ],+ "name": "three.ws",+ "description": "three.ws is the AI-agent layer for the open web: build, embed, monetize, and trade autonomous agents with real 3D avatars, on-chain identity, pay-per-call (x402), and pump.fun token launches. This is the platform's own ERC-8004 agent card — three.ws registered as a first-class agent in the IdentityRegistry, embodied by its default 3D avatar.",+ "image": "https://three.ws/og-image.png",+ "active": true,+ "model": {+ "uri": "https://three.ws/avatars/default.glb",+ "format": "gltf-binary",+ "sha256": "3ca13a1e3ad8f57e50266294b823641680dd3f3f174eb4be908ddca7afc0c82a",+ "sizeBytes": 2875236,+ "polygonCount": 13317,+ "boundingBox": {+ "min": [-0.464, -0.006, -0.146],+ "max": [0.464, 1.766, 0.197]+ },+ "license": "CC-BY-4.0"+ },+ "services": [+ {+ "name": "web",+ "endpoint": "https://three.ws/"+ },+ {+ "name": "A2A",+ "endpoint": "https://three.ws/.well-known/agent-card.json",+ "version": "0.3.0"+ },+ {+ "name": "MCP",+ "endpoint": "https://three.ws/.well-known/openapi.yaml",+ "version": "2025-06-18"+ }+ ],+ "x402Support": true,+ "x402Endpoints": [+ {+ "url": "https://three.ws/api/mcp",+ "method": "POST",+ "description": "MCP tool call — 3D avatar viewer, glTF model validation/inspection/optimization, and Solana agent data",+ "networks": ["solana", "base"],+ "scheme": "exact",+ "priceUsdc": "0.001"+ }+ ],+ "registrations": [],+ "supportedTrust": ["reputation", "validation"]+}diff --git a/public/.well-known/agent-registration.json b/public/.well-known/agent-registration.jsonindex 39bc9a12f..2146b599f 100644--- a/public/.well-known/agent-registration.json+++ b/public/.well-known/agent-registration.json@@ -5,11 +5,17 @@"description": "AI-powered 3D model viewer and validation agent. Drag and drop glTF, GLB, and 3D files to preview instantly in your browser. Supports real-time rendering, model validation, environment maps, and animation playback via Three.js and WebGL.","image": "https://three.ws/og-image.png","active": true,+ "agentCard": "https://three.ws/.well-known/3d-agent-card.json","model": {- "uri": "https://three.ws/avatars/cz.glb",+ "uri": "https://three.ws/avatars/default.glb","format": "gltf-binary",- "sha256": "e81d3b9d6bd2e5e2e97effd270b12bc608063e0340ab9df053a23a84e7c6f36b",- "sizeBytes": 2195336,+ "sha256": "3ca13a1e3ad8f57e50266294b823641680dd3f3f174eb4be908ddca7afc0c82a",+ "sizeBytes": 2875236,+ "polygonCount": 13317,+ "boundingBox": {+ "min": [-0.464, -0.006, -0.146],+ "max": [0.464, 1.766, 0.197]+ },"license": "CC-BY-4.0"},"services": [@@ -40,5 +46,5 @@}],"registrations": [],- "supportedTrust": ["reputation"]+ "supportedTrust": ["reputation", "validation"]}diff --git a/public/changelog.json b/public/changelog.jsonindex 2e03b610e..70e2407fa 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,22 @@{- "generated_at": "2026-06-15T02:18:33.536Z",+ "generated_at": "2026-06-15T02:33:46.714Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "Autonomous coin buybacks and creator-fee distributions now run on schedule",+ "summary": "Coins launched through three.ws with autopilot enabled now have their buybacks and creator-fee distributions executed automatically on an hourly schedule, instead of waiting for a manual trigger. A new balance watchdog checks every Solana signer the platform uses to pay on-chain fees and alerts the team the moment one runs low, so autopilot never silently stalls for lack of gas. No action needed from coin owners — it just works in the background.",+ "link": null,+ "tags": [+ "improvement",+ "infra"+ ]+ },{"date": "2026-06-15","type": "update",@@ -2727,7 +2738,7 @@"date": "2026-05-04","type": "launch","title": "Pump Live",- "summary": "Real-time SSE feed of every pump.fun launch as it happens.",+ "summary": "Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.","link": "/pump-live","tags": ["launch"diff --git a/public/changelog.xml b/public/changelog.xmlindex c8d266a2d..b2815b227 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Autonomous coin buybacks and creator-fee distributions now run on schedule</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-15:Autonomous coin buybacks and creator-fee distributions now run on schedule</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Coins launched through three.ws with autopilot enabled now have their buybacks and creator-fee distributions executed automatically on an hourly schedule, instead of waiting for a manual trigger. A new balance watchdog checks every Solana signer the platform uses to pay on-chain fees and alerts the team the moment one runs low, so autopilot never silently stalls for lack of gas. No action needed from coin owners — it just works in the background.</description>+ </item><item><title>Launchpad Studio: pick your avatar from your own agents and the gallery</title><link>https://three.ws/launchpad</link>@@ -2132,7 +2140,7 @@<guid isPermaLink="false">2026-05-04:Pump Live</guid><pubDate>Mon, 04 May 2026 12:00:00 GMT</pubDate><category>launch</category>- <description>Real-time SSE feed of every pump.fun launch as it happens.</description>+ <description>Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.</description></item><item><title>Pump Visualizer</title>diff --git a/public/features.json b/public/features.jsonindex 5caea3a1a..4591acc47 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-15T02:18:31.800Z",+ "generated_at": "2026-06-15T02:33:46.632Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -549,7 +549,7 @@{"path": "/pump-live","title": "Pump Live",- "description": "Real-time SSE feed of every pump.fun launch as it happens.",+ "description": "Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.","added": "2026-05-04","auth": null,"indexable": true,diff --git a/public/llms-full.txt b/public/llms-full.txtindex 22db22128..5ce4ed4b0 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -336,7 +336,7 @@ Mint and trade pump.fun agent tokens on Solana. Live feed of every launch.URL: https://three.ws/pump-live-Real-time SSE feed of every pump.fun launch as it happens.+Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.### Pump Dashboarddiff --git a/public/llms.txt b/public/llms.txtindex d614ba48e..001554207 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -76,7 +76,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Pay (x402)](https://three.ws/pay): Pay-per-call gateway: invoke any x402-protocol paid API with a USDC micro-transaction.- [Agent Wallet (x402 on Solana)](https://three.ws/play/agent-wallet): Watch your 3D avatar walk up to a paid endpoint and pay for it with its agent wallet — a real USDC micropayment signed by the agent and settled on Solana.- [Pump.fun Stream](https://three.ws/pumpfun): Mint and trade pump.fun agent tokens on Solana. Live feed of every launch.-- [Pump Live](https://three.ws/pump-live): Real-time SSE feed of every pump.fun launch as it happens.+- [Pump Live](https://three.ws/pump-live): Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.- [Pump Dashboard](https://three.ws/pump-dashboard): Pump.fun trading desk: watchlists, scanner, quotes, portfolio, and live charts.- [Strategy Lab](https://three.ws/strategy-lab): Build DCA and subscription strategies that trade on-chain on your behalf.- [Solana Vanity Wallet](https://three.ws/vanity-wallet): Grind a Solana address with a custom prefix using your browser's GPU.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 3e7c516cc..e99b0f5fe 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -488,7 +488,7 @@<a href="/pump-live"><span class="sm-title">Pump Live</span><span class="sm-path">/pump-live</span>- <span class="sm-desc">Real-time SSE feed of every pump.fun launch as it happens.</span>+ <span class="sm-desc">Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.</span></a></li><li>diff --git a/scripts/check-relayer-balances.mjs b/scripts/check-relayer-balances.mjsnew file mode 100644index 000000000..efd656265--- /dev/null+++ b/scripts/check-relayer-balances.mjs@@ -0,0 +1,99 @@+#!/usr/bin/env node+// Solana relayer balance report — operator companion to the+// /api/cron/relayer-balance-check watchdog. Same registry (api/_lib/solana-signers.js),+// run on demand from a machine that has the signer secrets.+//+// For every signer it can decode, prints the pubkey, SOL balance, USDC balance,+// and whether it's above its documented minimum. Unconfigured signers are listed+// as "(unset)" so you can see at a glance what the current deployment actually+// holds. Exit code is non-zero if any configured signer is underfunded — wire it+// into a pre-deploy check if you like.+//+// Usage:+// node scripts/check-relayer-balances.mjs # reads .env.local then env+// SOLANA_RPC_URL=https://… node scripts/check-relayer-balances.mjs+// node scripts/check-relayer-balances.mjs --network devnet+//+// Never prints or logs any secret — pubkeys and balances only.++import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import w3 from '@solana/web3.js';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(__dirname, '..');++// Load .env.local without overriding anything already in the environment.+const envFile = path.join(ROOT, '.env.local');+if (fs.existsSync(envFile)) {+ for (const line of fs.readFileSync(envFile, 'utf8').split('\n')) {+ const m = line.match(/^([A-Z0-9_]+)=(.*)$/);+ if (m && !(m[1] in process.env)) process.env[m[1]] = m[2].trim().replace(/^["']|["']$/g, '');+ }+}++const { SOLANA_SIGNERS, resolveSignerPubkey } = await import(+ path.join(ROOT, 'api/_lib/solana-signers.js')+);++const networkArg = process.argv.includes('--network')+ ? process.argv[process.argv.indexOf('--network') + 1]+ : 'mainnet';+const rpcUrl =+ networkArg === 'devnet'+ ? process.env.SOLANA_RPC_URL_DEVNET || w3.clusterApiUrl('devnet')+ : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';++const USDC =+ networkArg === 'devnet'+ ? new w3.PublicKey('4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU') // USDC-Dev+ : new w3.PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC++const conn = new w3.Connection(rpcUrl, 'confirmed');+console.log(`network: ${networkArg} rpc: ${rpcUrl}\n`);+console.log('signer'.padEnd(24), 'pubkey'.padEnd(46), 'SOL'.padStart(12), 'min', 'USDC');+console.log('-'.repeat(100));++let underfunded = 0;+for (const spec of SOLANA_SIGNERS) {+ const resolved = await resolveSignerPubkey(spec);+ if (!resolved.configured) {+ console.log(spec.name.padEnd(24), '(unset)'.padEnd(46), '—'.padStart(12), spec.minSol);+ continue;+ }+ if (resolved.decodeError || !resolved.pubkey) {+ console.log(spec.name.padEnd(24), 'DECODE FAILED'.padEnd(46), '—'.padStart(12), spec.minSol);+ underfunded++;+ continue;+ }+ const pk = new w3.PublicKey(resolved.pubkey);+ const lamports = await conn.getBalance(pk).catch(() => null);+ const sol = lamports == null ? null : lamports / 1e9;+ let usdc = null;+ try {+ const r = await conn.getParsedTokenAccountsByOwner(pk, { mint: USDC });+ usdc = r.value[0]?.account.data.parsed.info.tokenAmount.uiAmount ?? 0;+ } catch {+ /* no token account */+ }+ const low = sol != null && sol < spec.minSol;+ if (low) underfunded++;+ const solStr = sol == null ? 'rpc-err' : sol.toFixed(6);+ const flag = low ? ' ⚠️ LOW' : '';+ console.log(+ spec.name.padEnd(24),+ resolved.pubkey.padEnd(46),+ solStr.padStart(12),+ String(spec.minSol).padStart(4),+ usdc ?? '-',+ flag,+ );+}++console.log('-'.repeat(100));+if (underfunded > 0) {+ console.log(`\n${underfunded} signer(s) underfunded or unreadable on ${networkArg}.`);+ process.exit(1);+}+console.log(`\nAll configured signers funded on ${networkArg}.`);diff --git a/scripts/erc8004-verify-card.mjs b/scripts/erc8004-verify-card.mjsnew file mode 100644index 000000000..a1270addc--- /dev/null+++ b/scripts/erc8004-verify-card.mjs@@ -0,0 +1,149 @@+#!/usr/bin/env node+/**+ * Verify a 3D Agent Card v1 against the published JSON Schema AND the spec's+ * mandatory conformance point #3: the bytes at `model.uri` MUST hash to+ * `model.sha256` (specs/3D_AGENT_CARD.md). A card that fails the hash check is+ * "unverified" regardless of any validation report.+ *+ * Used by the self-registration flow (scripts/erc8004-register-self.mjs) as a+ * pre-mint gate — we never point a tokenURI at a card that doesn't verify — and+ * runnable standalone to audit the served documents.+ *+ * # verify the platform card against the local GLB bytes (default):+ * node scripts/erc8004-verify-card.mjs+ *+ * # verify a specific card file:+ * node scripts/erc8004-verify-card.mjs --card public/.well-known/3d-agent-card.json+ *+ * # fetch model.uri over the network instead of resolving to a local file:+ * node scripts/erc8004-verify-card.mjs --remote+ *+ * Exit code 0 = conformant, 1 = failed (schema or hash). No network, no keys+ * needed in the default (local) mode.+ */++import { readFileSync, existsSync } from 'node:fs';+import { createHash } from 'node:crypto';+import { dirname, resolve, basename } from 'node:path';+import { fileURLToPath } from 'node:url';++import Ajv from 'ajv/dist/2020.js';+import addFormats from 'ajv-formats';++const __dirname = dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = resolve(__dirname, '..');++function arg(name, fallback) {+ const i = process.argv.indexOf(name);+ return i >= 0 && process.argv[i + 1] && !process.argv[i + 1].startsWith('--')+ ? process.argv[i + 1]+ : fallback;+}+function flag(name) {+ return process.argv.includes(name);+}++const CARD_PATH = resolve(REPO_ROOT, arg('--card', 'public/.well-known/3d-agent-card.json'));+const SCHEMA_PATH = resolve(REPO_ROOT, 'public/.well-known/3d-agent-card.schema.json');+const remote = flag('--remote');++/**+ * Resolve `model.uri` to raw bytes.+ * - In local mode an `https://three.ws/avatars/<file>` (or any first-party+ * `/avatars/...`) URI maps to the committed asset under public/, so the check+ * runs offline against the exact bytes that will be served.+ * - `ipfs://` and arbitrary `https://` URIs are fetched (network) — also used+ * when --remote is passed so the served bytes are checked end-to-end.+ */+async function loadModelBytes(uri) {+ if (!remote) {+ const m = /\/avatars\/([^/?#]+)$/.exec(uri);+ if (m) {+ const local = resolve(REPO_ROOT, 'public/avatars', m[1]);+ if (existsSync(local)) {+ return { bytes: readFileSync(local), source: `local:public/avatars/${m[1]}` };+ }+ }+ }+ let url = uri;+ if (uri.startsWith('ipfs://')) {+ url = `https://w3s.link/ipfs/${uri.slice('ipfs://'.length)}`;+ }+ const res = await fetch(url);+ if (!res.ok) throw new Error(`fetch ${url} → ${res.status} ${res.statusText}`);+ const buf = Buffer.from(await res.arrayBuffer());+ return { bytes: buf, source: `remote:${url}` };+}++async function main() {+ if (!existsSync(CARD_PATH)) {+ console.error(`✗ card not found: ${CARD_PATH}`);+ process.exit(1);+ }+ if (!existsSync(SCHEMA_PATH)) {+ console.error(`✗ schema not found: ${SCHEMA_PATH}`);+ process.exit(1);+ }++ const card = JSON.parse(readFileSync(CARD_PATH, 'utf8'));+ const schema = JSON.parse(readFileSync(SCHEMA_PATH, 'utf8'));++ console.log(`Verifying ${basename(CARD_PATH)} (${card.name || 'unnamed'})\n`);++ // ── 1. JSON Schema ────────────────────────────────────────────────────────+ const ajv = new Ajv({ allErrors: true, strict: false });+ addFormats(ajv);+ const validate = ajv.compile(schema);+ const schemaOk = validate(card);+ if (schemaOk) {+ console.log('✓ schema valid against 3d-agent-card.schema.json');+ } else {+ console.log('✗ schema INVALID:');+ for (const e of validate.errors || []) {+ console.log(` ${e.instancePath || '/'} ${e.message}`);+ }+ }++ // ── 2. Conformance: type[] includes both required URIs ────────────────────+ const types = Array.isArray(card.type) ? card.type : [card.type];+ const ERC = 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1';+ const TWS = 'https://three.ws/specs/3d-agent-card-v1';+ const allTypes = [...types, ...(card.additionalTypes || [])];+ const typeOk = allTypes.includes(ERC) && allTypes.includes(TWS);+ console.log(+ typeOk+ ? '✓ type includes both ERC-8004 + three.ws Card v1 URIs'+ : `✗ type missing required URI (has: ${allTypes.join(', ') || 'none'})`,+ );++ // ── 3. Mandatory: model bytes hash to model.sha256 ────────────────────────+ let hashOk = false;+ if (!card.model?.uri || !card.model?.sha256) {+ console.log('✗ model.sha256 card has no model.uri / model.sha256');+ } else {+ try {+ const { bytes, source } = await loadModelBytes(card.model.uri);+ const actual = createHash('sha256').update(bytes).digest('hex');+ hashOk = actual === card.model.sha256.toLowerCase();+ if (hashOk) {+ console.log(`✓ model.sha256 ${actual}`);+ console.log(` bytes: ${bytes.length} from ${source}`);+ } else {+ console.log('✗ model.sha256 MISMATCH — card is UNVERIFIED');+ console.log(` card: ${card.model.sha256}`);+ console.log(` actual: ${actual} (${source})`);+ }+ } catch (err) {+ console.log(`✗ model.sha256 could not load bytes: ${err.message}`);+ }+ }++ const ok = schemaOk && typeOk && hashOk;+ console.log(`\n${ok ? '✓ CONFORMANT' : '✗ NOT CONFORMANT'} — 3D Agent Card v1`);+ process.exit(ok ? 0 : 1);+}++main().catch((err) => {+ console.error('fatal:', err?.stack || err?.message || err);+ process.exit(1);+});diff --git a/scripts/fund-devnet-signer.mjs b/scripts/fund-devnet-signer.mjsnew file mode 100644index 000000000..6c8c33d43--- /dev/null+++ b/scripts/fund-devnet-signer.mjs@@ -0,0 +1,101 @@+#!/usr/bin/env node+// Fund a Solana signer on devnet via airdrop, then report its balance.+//+// Devnet SOL is free and airdroppable, so devnet signers should never block a+// smoke run. This script either funds an existing signer (decoded from its env+// var) or, with --new, generates a fresh throwaway devnet keypair and prints its+// secret so you can drop it into your local .env.local for devnet smokes. It+// NEVER writes a secret to disk and NEVER touches mainnet.+//+// Usage:+// node scripts/fund-devnet-signer.mjs --env PUMP_CRON_RELAYER_SECRET_KEY_B64+// node scripts/fund-devnet-signer.mjs --pubkey <base58> # fund an address+// node scripts/fund-devnet-signer.mjs --new # mint + fund a fresh one+// SOL=2 node scripts/fund-devnet-signer.mjs --new # request 2 SOL+//+// The public devnet faucet rate-limits aggressively from cloud IPs; if the+// airdrop 429s, the script says so and points at https://faucet.solana.com.++import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import w3 from '@solana/web3.js';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(__dirname, '..');++const envFile = path.join(ROOT, '.env.local');+if (fs.existsSync(envFile)) {+ for (const line of fs.readFileSync(envFile, 'utf8').split('\n')) {+ const m = line.match(/^([A-Z0-9_]+)=(.*)$/);+ if (m && !(m[1] in process.env)) process.env[m[1]] = m[2].trim().replace(/^["']|["']$/g, '');+ }+}++const { decodeSecretKey } = await import(path.join(ROOT, 'api/_lib/solana-signers.js'));++function arg(name) {+ const i = process.argv.indexOf(name);+ return i >= 0 ? process.argv[i + 1] : null;+}++const rpcUrl = process.env.SOLANA_RPC_URL_DEVNET || w3.clusterApiUrl('devnet');+const conn = new w3.Connection(rpcUrl, 'confirmed');+const requestSol = Number(process.env.SOL || '2');++let pubkey;+let mintedSecretB64 = null;++if (process.argv.includes('--new')) {+ const kp = w3.Keypair.generate();+ pubkey = kp.publicKey;+ mintedSecretB64 = Buffer.from(kp.secretKey).toString('base64');+} else if (arg('--pubkey')) {+ pubkey = new w3.PublicKey(arg('--pubkey'));+} else if (arg('--env')) {+ const secret = process.env[arg('--env')];+ if (!secret) {+ console.error(`env ${arg('--env')} is not set — pass --new to mint a throwaway, or set it first`);+ process.exit(1);+ }+ const bytes = await decodeSecretKey(secret);+ if (!bytes) {+ console.error(`could not decode secret in ${arg('--env')}`);+ process.exit(1);+ }+ pubkey = w3.Keypair.fromSecretKey(bytes).publicKey;+} else {+ console.error('pass one of: --new | --pubkey <addr> | --env <VAR>');+ process.exit(1);+}++console.log(`network: devnet rpc: ${rpcUrl}`);+console.log(`target: ${pubkey.toBase58()}`);++const before = await conn.getBalance(pubkey).catch(() => 0);+console.log(`balance before: ${(before / 1e9).toFixed(6)} SOL`);++try {+ const sig = await conn.requestAirdrop(pubkey, requestSol * 1e9);+ console.log(`airdrop tx: ${sig}`);+ const bh = await conn.getLatestBlockhash('confirmed');+ await conn.confirmTransaction({ signature: sig, ...bh }, 'confirmed');+ const after = await conn.getBalance(pubkey);+ console.log(`balance after: ${(after / 1e9).toFixed(6)} SOL`);+ console.log(`https://explorer.solana.com/tx/${sig}?cluster=devnet`);+} catch (e) {+ console.error(`\nairdrop failed: ${e.message}`);+ console.error('The public devnet faucet rate-limits cloud IPs. Use https://faucet.solana.com');+ console.error(`for ${pubkey.toBase58()} instead, then re-run with --pubkey to confirm.`);+ if (mintedSecretB64) printMinted();+ process.exit(1);+}++if (mintedSecretB64) printMinted();++function printMinted() {+ console.log('\n── fresh throwaway devnet keypair (DEVNET ONLY — never reuse on mainnet) ──');+ console.log(`pubkey: ${pubkey.toBase58()}`);+ console.log(`secret (base64, for a *_B64 env var): ${mintedSecretB64}`);+ console.log('Add it to .env.local yourself; this script never writes secrets to disk.');+}diff --git a/scripts/trigger-pump-crons.mjs b/scripts/trigger-pump-crons.mjsnew file mode 100644index 000000000..ac760ea33--- /dev/null+++ b/scripts/trigger-pump-crons.mjs@@ -0,0 +1,64 @@+#!/usr/bin/env node+// Trigger the pump.fun buyback / distribute crons against a deployment and print+// the JSON result — the operator's re-runnable verification for tasks 4 & 5 of+// tasks/onchain-deployment/09-fund-solana-relayers-verify-crons.md.+//+// Both crons are authed with the Vercel CRON_SECRET (Bearer). On success each+// returns per-mint results: when the relayer is funded you get tx_signature ++// status:'confirmed' and a fresh row in pump_buyback_runs / pump_distribute_runs;+// when it's unfunded you get status:'pending' + an unsigned tx_base64 for an+// external keeper (still a real audit row). A run that writes no row is a failure.+//+// Usage:+// BASE_URL=https://three.ws CRON_SECRET=… node scripts/trigger-pump-crons.mjs+// BASE_URL=http://localhost:3000 CRON_SECRET=… node scripts/trigger-pump-crons.mjs buyback+// … node scripts/trigger-pump-crons.mjs distribute+//+// Pass `buyback` or `distribute` to run just one; default runs both.++const BASE_URL = (process.env.BASE_URL || 'https://three.ws').replace(/\/$/, '');+const CRON_SECRET = process.env.CRON_SECRET;+if (!CRON_SECRET) {+ console.error('CRON_SECRET is required (the Vercel cron bearer secret)');+ process.exit(1);+}++const which = process.argv[2];+const targets = [];+if (!which || which === 'buyback') targets.push(['buyback', '/api/cron/run-buyback']);+if (!which || which === 'distribute') targets.push(['distribute', '/api/cron/run-distribute-payments']);+if (targets.length === 0) {+ console.error('arg must be "buyback", "distribute", or omitted for both');+ process.exit(1);+}++let failed = false;+for (const [label, path] of targets) {+ console.log(`\n── ${label} → ${BASE_URL}${path} ──`);+ try {+ const r = await fetch(`${BASE_URL}${path}`, {+ method: 'POST',+ headers: { authorization: `Bearer ${CRON_SECRET}` },+ });+ const body = await r.json().catch(() => ({}));+ console.log(`HTTP ${r.status}`);+ console.log(JSON.stringify(body, null, 2));+ const results = body?.results || [];+ const confirmed = results.filter((x) => x.status === 'confirmed');+ const pending = results.filter((x) => x.status === 'pending');+ const errored = results.filter((x) => x.status === 'failed');+ console.log(+ `summary: ${results.length} processed, ${confirmed.length} confirmed, ` ++ `${pending.length} pending, ${errored.length} failed`,+ );+ for (const c of confirmed) {+ console.log(` ✓ ${c.mint} sig=${c.tx_signature} run_id=${c.run_id}`);+ }+ if (!r.ok) failed = true;+ } catch (e) {+ console.error(`request failed: ${e.message}`);+ failed = true;+ }+}++process.exit(failed ? 1 : 0);diff --git a/scripts/verify-grad-sync.mjs b/scripts/verify-grad-sync.mjsnew file mode 100644index 000000000..fb1f1094f--- /dev/null+++ b/scripts/verify-grad-sync.mjs@@ -0,0 +1,54 @@+// Temporary verification for Task 08 — pumpfun-graduations-sync.+// Opens the live PumpPortal migration feed exactly like the cron does, confirms+// it persists fresh rows to pumpfun_graduations, then confirms+// pumpfunMcp.graduations() serves that live data with no bot configured.+//+// Run: node scripts/verify-grad-sync.mjs (DATABASE_URL must be exported)++import { neon } from '@neondatabase/serverless';++const sql = neon(process.env.DATABASE_URL);+const WINDOW_MS = Number(process.env.WINDOW_MS || 110_000);++const count = async () => (await sql`select count(*)::int as n from pumpfun_graduations`)[0].n;+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++const { connectPumpFunFeed } = await import('../api/_lib/pumpfun-ws-feed.js');++console.log(`[verify] opening live migration feed for ${WINDOW_MS / 1000}s …`);+const before = await count();+console.log('[verify] pumpfun_graduations rows before:', before);++const seen = new Map();+const controller = new AbortController();+const stop = connectPumpFunFeed({+ kind: 'graduation',+ signal: controller.signal,+ onEvent: ({ kind, data }) => {+ if (kind !== 'graduation') return;+ const sig = data?.tx_signature || data?.signature;+ if (sig && !seen.has(sig)) {+ seen.set(sig, true);+ console.log('[verify] graduation observed:', data.symbol || data.name || data.mint, sig.slice(0, 12));+ }+ },+});++await sleep(WINDOW_MS);+controller.abort();+try { stop?.(); } catch {}+await sleep(1000);++const after = await count();+console.log('[verify] observed this window:', seen.size);+console.log('[verify] pumpfun_graduations rows after:', after, `(delta +${after - before})`);++// Confirm the MCP client now serves live data with no bot configured.+delete process.env.PUMPFUN_BOT_URL;+const { pumpfunMcp, pumpfunBotEnabled } = await import('../api/_lib/pumpfun-mcp.js');+console.log('[verify] bot enabled?', pumpfunBotEnabled());+const grads = await pumpfunMcp.graduations({ limit: 3 });+console.log('[verify] pumpfunMcp.graduations() ok:', grads.ok, 'count:', grads.data?.length);+console.log('[verify] newest:', (grads.data || []).slice(0, 3).map((g) => g.symbol || g.name || g.mint));++process.exit(0);diff --git a/src/erc8004/validation-report.js b/src/erc8004/validation-report.jsnew file mode 100644index 000000000..b085a7d61--- /dev/null+++ b/src/erc8004/validation-report.js@@ -0,0 +1,137 @@+/**+ * ERC-8004 validation report — the canonical, dependency-light shape that both+ * the browser recorder (src/erc8004/validation-recorder.js) and the server+ * attestor (api/_lib/validation-attest.js) hash and pin.+ *+ * One source of truth for "is this GLB valid": the platform's glTF inspector+ * (src/gltf-inspect.js, surfaced as /api/x402/model-check). A GLB that the+ * inspector can parse is structurally valid (zero errors); a GLB that throws is+ * invalid (one error). Optimization suggestions ride along as warnings/infos —+ * they never fail a model.+ *+ * The report is byte-stable for a given build: keys are written in a fixed order+ * so `JSON.stringify` is deterministic, which means `hashReport()` over the+ * pinned bytes reproduces the on-chain `proofHash`. A verifier fetches+ * `proofURI`, re-stringifies, re-hashes, and compares.+ */++import { keccak256, toUtf8Bytes } from 'ethers';++export const KIND_GLB_SCHEMA = 'glb-schema';++// glTF-Validator severity convention, reused so the report reads the same to any+// tool that already understands Khronos reports: 0=Error 1=Warning 2=Info 3=Hint.+export const SEVERITY = { ERROR: 0, WARNING: 1, INFO: 2, HINT: 3 };++const SUGGESTION_SEVERITY = {+ critical: SEVERITY.ERROR,+ warn: SEVERITY.WARNING,+ info: SEVERITY.INFO,+ hint: SEVERITY.HINT,+};++/**+ * Derive a deterministic pass/fail flag from a validation report.+ * Pass = zero errors. Warnings, infos and hints are allowed.+ * @param {{ issues?: { numErrors?: number } }} report+ * @returns {boolean}+ */+export function reportPassed(report) {+ const errs = (report && report.issues && report.issues.numErrors) || 0;+ return errs === 0;+}++/**+ * keccak256 over the canonicalized JSON report, suitable for an on-chain proof.+ * @param {object} report+ * @returns {string} 0x-prefixed 32-byte hex.+ */+export function hashReport(report) {+ return keccak256(toUtf8Bytes(JSON.stringify(report)));+}++/**+ * Build the canonical glb-schema validation report from a glTF inspection.+ *+ * @param {object} p+ * @param {string} p.url Resolved GLB URL that was validated.+ * @param {string} [p.sha256] sha256 of the exact bytes fetched (independent byte-check).+ * @param {number} [p.byteLength] Size of the fetched model in bytes.+ * @param {object} [p.inspect] Output of inspectModel() — null on parse failure.+ * @param {Array<{id:string,severity:string,message:string,estimate?:string}>} [p.suggestions]+ * Output of suggestOptimizations().+ * @param {string|null} [p.error] Parse error message → records one hard error.+ * @param {string} p.validatedAt ISO timestamp the validation ran (caller-supplied; never Date.now() here).+ * @returns {object} Canonical report. `issues.numErrors === 0` ⇒ passing.+ */+export function buildGlbReport({+ url,+ sha256 = null,+ byteLength = null,+ inspect = null,+ suggestions = [],+ error = null,+ validatedAt,+}) {+ const messages = [];++ if (error) {+ messages.push({+ severity: SEVERITY.ERROR,+ code: 'GLB_PARSE_FAILED',+ message: String(error),+ pointer: '',+ });+ }++ for (const s of suggestions) {+ const severity = SUGGESTION_SEVERITY[s.severity] ?? SEVERITY.INFO;+ messages.push({+ severity,+ code: String(s.id || 'SUGGESTION').toUpperCase(),+ message: s.estimate ? `${s.message} (${s.estimate})` : s.message,+ pointer: '',+ });+ }++ const count = (sev) => messages.filter((m) => m.severity === sev).length;++ return {+ kind: KIND_GLB_SCHEMA,+ spec: 'erc-8004/validation/glb-schema@1',+ validatedAt,+ uri: url || '',+ validator: {+ name: 'three.ws glTF inspector',+ tool: '@gltf-transform/core',+ endpoint: '/api/x402/model-check',+ },+ // The byte-check is surfaced INDEPENDENTLY of the pass/fail flag, per spec:+ // a passing schema validation never overrides the sha256 byte identity.+ byteCheck: {+ sha256: sha256 || null,+ byteLength: byteLength ?? (inspect ? inspect.fileSize ?? null : null),+ },+ issues: {+ numErrors: count(SEVERITY.ERROR),+ numWarnings: count(SEVERITY.WARNING),+ numInfos: count(SEVERITY.INFO),+ numHints: count(SEVERITY.HINT),+ messages,+ },+ model: inspect,+ };+}++/**+ * Human-readable one-line reason a report failed (or '' when it passed).+ * @param {object} report+ * @returns {string}+ */+export function failureReason(report) {+ if (reportPassed(report)) return '';+ const errs = report?.issues?.messages?.filter((m) => m.severity === SEVERITY.ERROR) || [];+ if (errs.length === 0) return 'validation failed';+ if (errs.length === 1) return errs[0].message;+ return `${errs.length} errors: ${errs[0].message}`;+}diff --git a/tasks/onchain-deployment/SOLANA-SIGNERS.md b/tasks/onchain-deployment/SOLANA-SIGNERS.mdnew file mode 100644index 000000000..e3802600d--- /dev/null+++ b/tasks/onchain-deployment/SOLANA-SIGNERS.md@@ -0,0 +1,149 @@+# Solana Signers — Inventory, Funding & Verification++Every Solana keypair the platform loads to **pay fees / rent** for an on-chain+flow. Secrets are NEVER committed — this file documents env var **names**, what+each pays for, the network it spends real SOL on, the encoding, and the minimum+balance below which it should be refilled.++The machine-readable mirror is [`api/_lib/solana-signers.js`](../../api/_lib/solana-signers.js)+— the registry the low-balance watchdog and operator script both read. Keep the+two in sync.++Last verified: 2026-06-15. None of these secrets are present in the Codespace+sandbox (`vercel env pull` returns empty for sensitive vars), so the on-chain+funding/verification steps below are **operator-gated** — run them from a machine+that holds the secrets. Everything that does **not** require a live secret (the+inventory, the watchdog, the scripts, the cron registration) is done and shipped.++---++## Signer registry++| Signer | Env var (fallback) | Network | Encoding | Min SOL | Pays for |+|---|---|---|---|---|---|+| pump-cron-relayer | `PUMP_CRON_RELAYER_SECRET_KEY_B64` | mainnet + devnet | base64 (64 bytes) | 0.10 | fees + swap gas for **buyback** & **distribute-payments** crons |+| pump-x402-launcher | `PUMP_X402_LAUNCHER_SECRET_KEY_B64` | mainnet | base64 (64 bytes) | 0.10 | fronts ~0.022 SOL per x402 pay-per-call pump.fun launch |+| sns-parent-owner | `THREEWS_SOL_PARENT_SECRET_BASE58` | mainnet | base58 | 0.05 | owns `threews.sol`; rent/fees minting `*.threews.sol` subdomains |+| coin-treasury | `COIN_TREASURY_SECRET_KEY_B64` | mainnet | base64 (64 bytes) | 0.05 | lottery / reflection distribution txs for launched coins |+| club-treasury | `CLUB_SOLANA_TREASURY_SECRET_KEY_B64` | mainnet | base64 (64 bytes) | 0.05 | USDC tip-sweep transfers + recipient ATA rent (club-payouts) |+| platform-treasury | `PLATFORM_TREASURY_KEYPAIR` (`TREASURY_KEYPAIR`) | mainnet | base58 / JSON | 0.05 | SPL withdrawal gas (process-withdrawals cron) |+| a2a-payer | `A2A_PAYER_SOLANA_SECRET` (`A2A_PAYER_SOLANA_PRIVATE_KEY`) | mainnet | base58 | 0.02 | co-signs SPL TransferChecked for A2A mandate settlements |+| collection-authority | `SOLANA_AGENT_COLLECTION_AUTHORITY_KEY` | mainnet + devnet | base58 | 0.02 | creates/manages the three.ws agent NFT collection |++Adjacent Solana secrets that exist but are **not fee-payer relayers** (so not in+the watchdog): `SAS_AUTHORITY_SECRET` (attestation authority — funded ad-hoc per+[`scripts/sas-bootstrap.js`](../../scripts/sas-bootstrap.js)),+`ATTEST_AGENT_SECRET_KEY`, `AVATAR_WALLET_SECRET` (avatar economy fee-payer,+capped by `AVATAR_MAX_SEND_USD`), `X402_AGENT_SOLANA_SECRET_BASE58` (x402 test+wallet). `AGENT_RELAYER_KEY` is an **EVM** key, not Solana. Add any of these to+the registry if they start backing a production flow.++Encodings differ, so both the watchdog and the scripts use one auto-detecting+decoder (`decodeSecretKey` in `api/_lib/solana-signers.js`): JSON array → base64+(64-byte round-trip) → base58.++---++## What ships in this change (no secret required)++1. **`api/_lib/solana-signers.js`** — the registry + the universal secret decoder+ + `resolveSignerPubkey()`.+2. **`api/cron/relayer-balance-check.js`** — a watchdog cron (every 6h) that+ reads each *configured* signer's mainnet SOL balance and fires a+ `sendOpsAlert` (existing Telegram ops pipeline, deduped per-pubkey hourly)+ when one is below its `minSol`. Unconfigured signers are skipped; a signer it+ can't decode or read also alerts (an unreadable signer is itself an outage).+ Registered in `vercel.json` crons.+3. **`scripts/check-relayer-balances.mjs`** — operator companion: prints every+ signer's pubkey, SOL + USDC, and flags under-min ones. Exits non-zero if any+ configured signer is underfunded. `--network devnet` supported.+4. **`scripts/fund-devnet-signer.mjs`** — airdrops devnet SOL to an existing or+ freshly-minted throwaway signer and reports balances. Devnet only; never+ writes a secret to disk.+5. **`scripts/trigger-pump-crons.mjs`** — re-runnable trigger for the buyback /+ distribute crons against a deployment; prints per-mint results + run_ids.+6. **Cron registration** — `run-buyback`, `run-distribute-payments`, and+ `relayer-balance-check` added to `vercel.json`. The two money-movers existed+ as handlers in `api/cron/[name].js` but were **never scheduled**, so the+ platform never actually ran an autonomous buyback/distribution. They are now+ scheduled and **degrade safely**: with an unfunded/absent relayer they write a+ `status:'pending'` audit row + an unsigned tx for an external keeper — no+ failure — and only start submitting real txs once the relayer is funded.++---++## Operator runbook (requires the real secrets)++### 1. Fund the signers++- **Devnet** (free): `node scripts/fund-devnet-signer.mjs --env PUMP_CRON_RELAYER_SECRET_KEY_B64`+ (the public faucet rate-limits cloud IPs; from a Codespace use+ <https://faucet.solana.com> for the printed pubkey, then re-confirm with+ `--pubkey`).+- **Mainnet** (real SOL — operator must send): transfer the `Min SOL` above (a+ few × is healthier) to each signer's pubkey. Get the pubkeys with+ `node scripts/check-relayer-balances.mjs` on a machine that has the secrets.++### 2. Devnet smoke trade (`buy-prep` → `buy-confirm`)++pump.fun's program is mainnet-only, so a true on-curve buy requires a devnet+deployment + a devnet pump mint. Use the existing+[`scripts/buyback-devnet-smoke.mjs`](../../scripts/buyback-devnet-smoke.mjs)+(drives the same builder+signer path the cron uses) with `MINT` set to a+synthetic devnet pump mint and `PUMP_CRON_RELAYER_SECRET_KEY_B64` funded.+Capture the confirmed signature from its output.++### 3. Verify the distribution cron → `pump_distribute_runs`++```+BASE_URL=https://three.ws CRON_SECRET=… node scripts/trigger-pump-crons.mjs distribute+```++Confirm a fresh row in `pump_distribute_runs` (before/after balances + signature+when funded, or `pending` + unsigned tx when not). A run with **no** row is a+failure, not a pass.++### 4. Verify the buyback cron → `pump_buyback_runs`++```+BASE_URL=https://three.ws CRON_SECRET=… node scripts/trigger-pump-crons.mjs buyback+```++Confirm a fresh row in `pump_buyback_runs` (`confirmed` + signature, or+`pending`, or `failed` with the error — all are real audit rows).++### 5. Verify SNS minting end-to-end++`threews.sol` is a **mainnet** SNS domain, so this is mainnet-only and needs+`THREEWS_SOL_PARENT_SECRET_BASE58` funded with real SOL. `POST /api/threews/subdomain`+with `{ label: "<your-username>" }` (auth required; label must equal your+username). Confirm the `user_subdomains` row, the `url_record` →+`https://three.ws/u/<label>`, and the on-chain owner via+`GET /api/threews/subdomain?label=<label>`. Without the key the endpoint returns+`503 config_missing` by design. Clean up the test claim with `DELETE` (on-chain+ownership stays with the recipient wallet).++### 6. Low-balance alerting++Already live via `relayer-balance-check`. Needs `TELEGRAM_BOT_TOKEN` ++`TELEGRAM_ALERTS_CHAT_ID` (the existing private ops channel — `TELEGRAM_ALERTS_CHAT_ID`+is currently unset per ops notes; set it to arm alerts). Force a check now with:++```+CRON_SECRET=… curl -sH "authorization: Bearer $CRON_SECRET" \+ https://three.ws/api/cron/relayer-balance-check | jq+```++---++## Status++| Item | State |+|---|---|+| Signer inventory | ✅ done (this doc + registry) |+| Low-balance watchdog + alert | ✅ shipped (cron + registered) |+| Balance / funding / trigger scripts | ✅ shipped |+| Cron registration (buyback/distribute) | ✅ shipped (were unscheduled) |+| Devnet airdrop from sandbox | ⚠️ blocked — faucet rate-limits this cloud IP; use faucet.solana.com |+| Devnet buy smoke / cron audit rows | ⏳ operator-gated — needs funded relayer + secrets |+| SNS mint (mainnet) | ⏳ operator-gated — needs funded `THREEWS_SOL_PARENT_SECRET_BASE58` |diff --git a/vercel.json b/vercel.jsonindex aabe2182a..863269468 100644--- a/vercel.json+++ b/vercel.json@@ -47,6 +47,10 @@"includeFiles": "data/pages.json","maxDuration": 30},+ "api/cron/relayer-balance-check.js": {+ "includeFiles": "data/pages.json",+ "maxDuration": 60+ },"api/cron/flush-usage-events.js": {"includeFiles": "data/pages.json","maxDuration": 60@@ -3085,6 +3089,18 @@"path": "/api/cron/quota-check","schedule": "0 * * * *"},+ {+ "path": "/api/cron/relayer-balance-check",+ "schedule": "0 */6 * * *"+ },+ {+ "path": "/api/cron/run-buyback",+ "schedule": "0 * * * *"+ },+ {+ "path": "/api/cron/run-distribute-payments",+ "schedule": "30 * * * *"+ },{"path": "/api/cron/audit-log-cleanup","schedule": "0 4 * * *"@@ -3161,6 +3177,10 @@"path": "/api/cron/pumpfun-monitor","schedule": "*/3 * * * *"},+ {+ "path": "/api/cron/pumpfun-graduations-sync",+ "schedule": "*/2 * * * *"+ },{"path": "/api/cron/solana-attest-event-cleanup","schedule": "*/10 * * * *"