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: implement AMM pool state retrieval and enhance solana-wallet functionality
nirholasf07b42a0c725
diff --git a/.claude/scheduled_tasks.lock b/.claude/scheduled_tasks.locknew file mode 100644index 000000000..648da27bd--- /dev/null+++ b/.claude/scheduled_tasks.lock@@ -0,0 +1 @@+{"sessionId":"ee95d5df-68e8-4e90-a66d-7cc9f1d5b817","pid":175522,"procStart":"299777","acquiredAt":1777459808377}\ No newline at end of filediff --git a/api/_lib/pump-vanity.js b/api/_lib/pump-vanity.jsnew file mode 100644index 000000000..22a441ab6--- /dev/null+++ b/api/_lib/pump-vanity.js@@ -0,0 +1,41 @@+// Mint Keypair vanity grinder for pump.fun launches.+//+// Generates Solana Keypairs until the base58 address starts with `prefix`.+// Capped by `maxIterations` so a serverless invocation can't time out.+//+// Base58 alphabet excludes 0, O, I, l — reject prefixes containing those+// up-front so callers get a clear 400 instead of an infinite loop.++import { Keypair } from '@solana/web3.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;++// Rough expected attempts ≈ 58^len. Hard cap default keeps us under+// ~5s wall time for 4-char prefixes on Vercel's serverless CPU.+const DEFAULT_MAX_ITERATIONS = 2_000_000;++export function isValidVanityPrefix(prefix) {+ if (!prefix || typeof prefix !== 'string') return false;+ if (prefix.length > 6) return false;+ return BASE58_RE.test(prefix);+}++export function grindMintKeypair({ prefix, maxIterations = DEFAULT_MAX_ITERATIONS } = {}) {+ if (!prefix) return { keypair: Keypair.generate(), iterations: 1 };+ if (!isValidVanityPrefix(prefix)) {+ throw Object.assign(new Error('invalid vanity prefix'), {+ status: 400,+ code: 'invalid_vanity',+ });+ }+ for (let i = 1; i <= maxIterations; i++) {+ const kp = Keypair.generate();+ if (kp.publicKey.toBase58().startsWith(prefix)) {+ return { keypair: kp, iterations: i };+ }+ }+ throw Object.assign(+ new Error(`vanity prefix '${prefix}' not found in ${maxIterations} attempts`),+ { status: 504, code: 'vanity_timeout' },+ );+}diff --git a/api/_lib/pump.js b/api/_lib/pump.jsindex 8ff874c02..37d6aa224 100644--- a/api/_lib/pump.js+++ b/api/_lib/pump.js@@ -133,6 +133,88 @@ export async function verifySignature({ network, signature }) {return tx;}+// Resolve the canonical pump.fun AMM pool for `mint` (post-graduation) and+// return everything `buyQuoteInput` / `sellBaseInput` need to price a swap.+// Quote currency is WSOL on the canonical pool.+//+// Throws { status: 404, code: 'pool_not_found' } if no pool exists yet.+export async function getAmmPoolState({ network = 'mainnet', mint } = {}) {+ if (!mint) throw Object.assign(new Error('mint required'), { status: 400 });+ const [+ {+ canonicalPumpPoolPda,+ OnlinePumpAmmSdk,+ PumpAmmSdk,+ },+ web3,+ BN,+ spl,+ ] = await Promise.all([+ import('@pump-fun/pump-swap-sdk'),+ import('@solana/web3.js'),+ import('bn.js').then((m) => m.default || m),+ import('@solana/spl-token'),+ ]);+ const connection = getConnection({ network });+ const mintPk = mint instanceof PublicKey ? mint : new PublicKey(mint);+ const poolKey = canonicalPumpPoolPda(mintPk);++ const online = new OnlinePumpAmmSdk(connection);+ let pool;+ try {+ pool = await online.fetchPool(poolKey);+ } catch {+ const e = new Error('pump.fun AMM pool not found for mint');+ e.status = 404;+ e.code = 'pool_not_found';+ throw e;+ }++ const [baseAccInfo, quoteAccInfo, baseMintInfo] = await Promise.all([+ connection.getAccountInfo(pool.poolBaseTokenAccount),+ connection.getAccountInfo(pool.poolQuoteTokenAccount),+ connection.getAccountInfo(pool.baseMint),+ ]);+ if (!baseAccInfo || !quoteAccInfo || !baseMintInfo) {+ const e = new Error('pool token accounts unavailable');+ e.status = 502;+ e.code = 'pool_accounts_missing';+ throw e;+ }+ const baseAcc = spl.AccountLayout.decode(baseAccInfo.data);+ const quoteAcc = spl.AccountLayout.decode(quoteAccInfo.data);+ const baseMintAccount = spl.MintLayout.decode(baseMintInfo.data);+ const baseReserve = new BN(baseAcc.amount.toString());+ const quoteReserve = new BN(quoteAcc.amount.toString());++ const offline = new PumpAmmSdk();+ const [globalConfigInfo, feeConfigInfo] = await Promise.all([+ connection.getAccountInfo(+ (await import('@pump-fun/pump-swap-sdk')).GLOBAL_CONFIG_PDA,+ ),+ connection.getAccountInfo(+ (await import('@pump-fun/pump-swap-sdk')).PUMP_AMM_FEE_CONFIG_PDA,+ ),+ ]);+ const globalConfig = globalConfigInfo+ ? offline.decodeGlobalConfig(globalConfigInfo)+ : null;+ const feeConfig = feeConfigInfo ? offline.decodeFeeConfig(feeConfigInfo) : null;++ return {+ connection,+ poolKey,+ pool,+ baseReserve,+ quoteReserve,+ baseMintAccount,+ globalConfig,+ feeConfig,+ BN,+ web3,+ };+}+// Build a versioned tx from a list of instructions, return base64 (unsigned).// Mirrors the pattern used in api/agents/solana-register-prep.js so frontends// can decode via VersionedTransaction.deserialize and submit via injected wallet.diff --git a/api/agents/solana-card.js b/api/agents/solana-card.jsindex 65621d373..2484542a9 100644--- a/api/agents/solana-card.js+++ b/api/agents/solana-card.js@@ -33,6 +33,36 @@ export default wrap(async (req, res) => {const network = a.meta?.network || 'mainnet';const origin = env.APP_ORIGIN;+ // Pump.fun off-chain signals — most-recent + per-kind counts. Best-effort:+ // the table is optional and may not exist in every deployment.+ let pumpfun = null;+ try {+ const rows = await sql`+ select kind, count(*)::int as n, max(seen_at) as last_seen+ from pumpfun_signals+ where agent_asset = ${asset}+ group by kind+ `;+ if (rows.length > 0) {+ const byKind = {};+ let total = 0;+ let last = null;+ for (const r of rows) {+ byKind[r.kind] = { count: r.n, last_seen: r.last_seen };+ total += r.n;+ if (!last || (r.last_seen && r.last_seen > last)) last = r.last_seen;+ }+ pumpfun = {+ signal_count: total,+ by_kind: byKind,+ last_seen: last,+ feed_url: `${origin}/api/agents/pumpfun-feed`,+ };+ }+ } catch {+ // pumpfun_signals table not present — omit the block entirely.+ }+return json(res, 200, {schema_version: '1.0',// A2A core@@ -58,5 +88,6 @@ export default wrap(async (req, res) => {memo_program: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',usage: 'Sign an SPL Memo tx with one of the published schemas as JSON, including this asset_pubkey as a non-signer key.',},+ ...(pumpfun ? { pumpfun } : {}),}, { 'cache-control': 'public, max-age=120', 'access-control-allow-origin': '*' });});diff --git a/api/pump/quote.js b/api/pump/quote.jsindex 40cf96631..4c986a5cc 100644--- a/api/pump/quote.js+++ b/api/pump/quote.js@@ -6,7 +6,7 @@import { cors, json, method, wrap, error } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { getPumpSdk, getPumpSwapSdk, solanaPubkey } from '../_lib/pump.js';+import { getPumpSdk, getAmmPoolState, solanaPubkey } from '../_lib/pump.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;@@ -21,6 +21,11 @@ export default wrap(async (req, res) => {const direction = url.searchParams.get('direction') === 'sell' ? 'sell' : 'buy';const solRaw = url.searchParams.get('sol');const tokenRaw = url.searchParams.get('token');+ const slippageRaw = url.searchParams.get('slippage_bps');+ const slippageBps = Number.isFinite(Number(slippageRaw))+ ? Math.max(0, Math.min(5000, Number(slippageRaw)))+ : 100;+ const slippage = slippageBps / 10_000;const mint = solanaPubkey(mintStr);if (!mint) return error(res, 400, 'validation_error', 'invalid mint');@@ -79,34 +84,95 @@ export default wrap(async (req, res) => {});}- // Post-graduation: AMM- const { sdk: ammSdk, BN: BN2 } = await getPumpSwapSdk({ network });- // Find pool for this mint vs WSOL (or USDC). Pool discovery is left to- // caller for now — if not implemented, return graduated:true with no quote.- let pool = null;+ // Post-graduation: AMM via canonical pump.fun pool (quote = WSOL).+ let amm;try {- if (ammSdk.findPoolByMint) {- pool = await ammSdk.findPoolByMint(mint);+ amm = await getAmmPoolState({ network, mint });+ } catch (e) {+ if (e.code === 'pool_not_found') {+ return json(res, 200, {+ mint: mintStr,+ network,+ graduated: true,+ pool: null,+ quote: null,+ note: 'No bonding curve and no canonical AMM pool — token may not be a pump.fun mint or has not graduated yet',+ });}- } catch {- pool = null;+ throw e;+ }++ const { pool, poolKey, baseReserve, quoteReserve, baseMintAccount, globalConfig, feeConfig } = amm;+ const LAMPORTS_PER_SOL_AMM = 1_000_000_000;+ const ammSdk = await import('@pump-fun/pump-swap-sdk');+ let quote = null;++ if (direction === 'buy' && solRaw) {+ const sol = Number(solRaw);+ if (!(sol > 0)) return error(res, 400, 'validation_error', 'sol must be > 0');+ const lamports = new BN(Math.floor(sol * LAMPORTS_PER_SOL_AMM));+ const r = ammSdk.buyQuoteInput({+ quote: lamports,+ slippage,+ baseReserve,+ quoteReserve,+ globalConfig,+ baseMintAccount,+ baseMint: pool.baseMint,+ coinCreator: pool.coinCreator,+ creator: pool.creator,+ feeConfig,+ });+ quote = {+ sol_in: sol,+ tokens_out: r.base?.toString?.() ?? null,+ min_tokens_out: r.uiBase?.toString?.() ?? r.minBase?.toString?.() ?? null,+ slippage_bps: slippageBps,+ source: 'amm',+ };+ } else if (direction === 'sell' && tokenRaw) {+ const tokens = new BN(tokenRaw);+ const r = ammSdk.sellBaseInput({+ base: tokens,+ slippage,+ baseReserve,+ quoteReserve,+ globalConfig,+ baseMintAccount,+ baseMint: pool.baseMint,+ coinCreator: pool.coinCreator,+ creator: pool.creator,+ feeConfig,+ });+ const lamportsOut = r.quote ?? r.uiQuote ?? r.minQuote;+ quote = {+ tokens_in: tokenRaw,+ sol_out:+ lamportsOut != null ? Number(lamportsOut.toString()) / LAMPORTS_PER_SOL_AMM : null,+ min_sol_out:+ (r.minQuote ?? r.uiQuote)?.toString+ ? Number((r.minQuote ?? r.uiQuote).toString()) / LAMPORTS_PER_SOL_AMM+ : null,+ slippage_bps: slippageBps,+ source: 'amm',+ };}return json(res, 200, {mint: mintStr,network,graduated: true,- pool: pool- ? {- address: pool.address?.toString?.() ?? String(pool.address),- base: pool.baseMint?.toString?.() ?? null,- quote: pool.quoteMint?.toString?.() ?? null,- }- : null,- quote: null,- note: pool ? null : 'Post-graduation pool lookup requires explicit pool key',+ pool: {+ address: poolKey.toString(),+ base: pool.baseMint.toString(),+ quote: pool.quoteMint.toString(),+ base_reserve: baseReserve.toString(),+ quote_reserve: quoteReserve.toString(),+ lp_supply: pool.lpSupply?.toString?.() ?? null,+ },+ quote,});} catch (err) {- return error(res, 502, 'pump_sdk_error', err.message || 'pump.fun SDK error');+ return error(res, err.status || 502, err.code || 'pump_sdk_error', err.message || 'pump.fun SDK error');}});diff --git a/api/pump/withdraw-confirm.js b/api/pump/withdraw-confirm.jsnew file mode 100644index 000000000..bacaaa8d5--- /dev/null+++ b/api/pump/withdraw-confirm.js@@ -0,0 +1,64 @@+// POST /api/pump/withdraw-confirm+// Verify the withdraw tx landed and acknowledge it. Symmetric with+// accept-payment-confirm / launch-confirm. The on-chain tx is the canonical+// receipt — we do not persist a row, only verify ownership + tx success.++import { z } from 'zod';+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { parse } from '../_lib/validate.js';+import { verifySignature } from '../_lib/pump.js';++const bodySchema = z.object({+ mint: z.string().min(32).max(44),+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),+ tx_signature: z.string().min(80).max(100),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(bodySchema, await readJson(req));++ const [row] = await sql`+ select id, mint, user_id, agent_authority, network from pump_agent_mints+ where mint=${body.mint} and network=${body.network} limit 1+ `;+ if (!row) return error(res, 404, 'not_found', 'agent mint not registered');+ if (row.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');++ let tx;+ try {+ tx = await verifySignature({ network: body.network, signature: body.tx_signature });+ } catch (e) {+ return error(res, e.status || 422, e.code || 'tx_failed', e.message);+ }++ const accountKeys = tx.transaction.message.accountKeys.map((k) =>+ (k.pubkey || k).toString(),+ );+ if (!accountKeys.includes(body.mint)) {+ return error(res, 422, 'mint_not_in_tx', 'mint not present in tx accounts');+ }+ if (row.agent_authority && !accountKeys.includes(row.agent_authority)) {+ return error(res, 422, 'authority_not_in_tx', 'agent authority not present in tx');+ }++ return json(res, 200, {+ ok: true,+ mint: body.mint,+ network: body.network,+ tx_signature: body.tx_signature,+ slot: tx.slot ?? null,+ block_time: tx.blockTime ?? null,+ });+});diff --git a/examples/skills/pump-fun-compose/SKILL.md b/examples/skills/pump-fun-compose/SKILL.mdindex 30a3689ed..dec28de24 100644--- a/examples/skills/pump-fun-compose/SKILL.md+++ b/examples/skills/pump-fun-compose/SKILL.md@@ -17,6 +17,11 @@ Agent-level loops that compose `pump-fun` (read) and `pump-fun-trade` (sign).- `exitOnConcentrationPct` / `exitOnDevSellPct` — exit triggers- `sessionSpendCapSol` / `perTradeSol` — hard spend caps+## Safety++- Pass `simulate: true` on any tool to dry-run: filters/quotes still execute, but `buyToken` / `sellToken` are skipped and a `SIMULATED:*` sig is returned. Spend caps still tick as if real so the simulated session terminates the same way a live one would.+- Pass `sessionId: "<stable-string>"` to persist `seen` / `mirrored` / `spent` / `exited` between calls. A restart with the same `sessionId` resumes — preventing a crash mid-loop from re-spending up to the cap. State is written via `ctx.memory.note` and falls back to an in-process Map if memory is unavailable.+## WiringThe host runtime injects:diff --git a/examples/skills/pump-fun-compose/tools.json b/examples/skills/pump-fun-compose/tools.jsonindex 5f7dc5573..e9598a3ff 100644--- a/examples/skills/pump-fun-compose/tools.json+++ b/examples/skills/pump-fun-compose/tools.json@@ -2,49 +2,56 @@"tools": [{"name": "researchAndBuy",- "description": "Research a token (curve, holders, creator rug flags), then buy if it passes filters. Returns decision + sig.",+ "description": "Research a token (curve, holders, creator rug flags), then buy if it passes filters. Returns decision + sig. Pass simulate:true for a dry-run that skips signing.","input_schema": {"type": "object","properties": {"query": { "type": "string", "description": "name, symbol, or mint" },- "amountSol": { "type": "number" }+ "amountSol": { "type": "number" },+ "simulate": { "type": "boolean", "description": "Dry-run: vet + quote but skip the actual buy." }},"required": ["query"]}},{"name": "autoSnipe",- "description": "Poll getNewTokens, filter by rug/holder rules, buy each pass with perTradeSol until sessionSpendCapSol is hit.",+ "description": "Poll getNewTokens, filter by rug/holder rules, buy each pass with perTradeSol until sessionSpendCapSol is hit. State (seen, spent) is persisted under sessionId so a restart resumes where it left off.","input_schema": {"type": "object","properties": {"durationSec": { "type": "integer", "minimum": 10, "maximum": 3600 },- "perTradeSol": { "type": "number" }+ "perTradeSol": { "type": "number" },+ "sessionId": { "type": "string", "description": "Stable id to persist & resume seen/spent state. Reusing an id continues a prior session within the cap." },+ "simulate": { "type": "boolean", "description": "Dry-run: vet + log intended buys but skip signing. Spend cap still enforced as if real." }},"required": ["durationSec"]}},{"name": "copyTrade",- "description": "Watch a creator/wallet's recent trades and mirror their buys with size scaling.",+ "description": "Watch a creator/wallet's recent trades and mirror their buys with size scaling. State (mirrored sigs, spent) persisted under sessionId.","input_schema": {"type": "object","properties": {"wallet": { "type": "string" },"sizeMultiplier": { "type": "number", "minimum": 0.001, "maximum": 10 },- "durationSec": { "type": "integer", "minimum": 10, "maximum": 7200 }+ "durationSec": { "type": "integer", "minimum": 10, "maximum": 7200 },+ "sessionId": { "type": "string" },+ "simulate": { "type": "boolean" }},"required": ["wallet", "durationSec"]}},{"name": "rugExitWatch",- "description": "Monitor held positions; auto-sell when top-holder concentration or dev-wallet sells cross thresholds.",+ "description": "Monitor held positions; auto-sell when top-holder concentration or dev-wallet sells cross thresholds. State (exited mints) persisted under sessionId.","input_schema": {"type": "object","properties": {"mints": { "type": "array", "items": { "type": "string" } },- "durationSec": { "type": "integer", "minimum": 10, "maximum": 86400 }+ "durationSec": { "type": "integer", "minimum": 10, "maximum": 86400 },+ "sessionId": { "type": "string" },+ "simulate": { "type": "boolean" }},"required": ["mints", "durationSec"]}diff --git a/examples/skills/pump-fun-trade/manifest.json b/examples/skills/pump-fun-trade/manifest.jsonindex 9eee89193..4a1a7df80 100644--- a/examples/skills/pump-fun-trade/manifest.json+++ b/examples/skills/pump-fun-trade/manifest.json@@ -7,7 +7,7 @@"tags": ["solana", "pump.fun", "trading", "signing"],"requires": {"runtime": ">=0.1.0",- "tools": [],+ "skills": ["solana-wallet@^0.1"],"capabilities": ["wallet.sign", "solana.rpc"]},"provides": {diff --git a/examples/skills/solana-wallet/SKILL.md b/examples/skills/solana-wallet/SKILL.mdnew file mode 100644index 000000000..4c44975e2--- /dev/null+++ b/examples/skills/solana-wallet/SKILL.md@@ -0,0 +1,36 @@+# solana-wallet++Generic Solana primitives. Provides the `ctx.wallet` contract that every signing+skill (pump-fun-trade, jupiter-swap, ...) consumes.++| Tool | Use it for |+|---|---|+| `getAddress` | Wallet pubkey |+| `getBalance` | SOL balance (self or any address) |+| `getSplBalances` | All SPL holdings |+| `transferSol` | Send SOL (capped by `maxTransferSol`) |+| `transferSpl` | Send any SPL token; auto-creates recipient ATA |+| `wrapSol` / `unwrapSol` | wSOL conversions |+| `getRecentSignatures` | Recent activity |++## Wallet contract++The host runtime injects `ctx.wallet` built via [api/_lib/solana-wallet.js](../../../api/_lib/solana-wallet.js):++```ts+{+ publicKey: PublicKey,+ signTransaction(tx): tx, // Transaction | VersionedTransaction+ sendAndConfirm(tx, conn): string, // returns signature+}+```++The wallet itself is recovered from an encrypted keypair stored on the agent+record (see `agent_identities.meta.encrypted_secret`). Never accepts keys via+tool args.++## Safety++- `transferSol` is capped by `manifest.config.maxTransferSol`.+- All write ops set a priority fee from `priorityFeeMicroLamports`.+- All write ops record to `ctx.memory` for the orchestrator to audit.diff --git a/src/app.js b/src/app.jsindex f2b8eb572..5ee449118 100644--- a/src/app.js+++ b/src/app.js@@ -14,6 +14,7 @@ import { mountAnimationGallery } from './widgets/animation-gallery.js';import { mountTalkingAgent } from './widgets/talking-agent.js';import { mountTurntable } from './widgets/turntable.js';import { mountHotspotTour } from './widgets/hotspot-tour.js';+import { mountPumpfunFeed } from './widgets/pumpfun-feed.js';import queryString from 'query-string';// Agent system — the new primitive layer@@ -988,6 +989,9 @@ class App {} else if (type === 'hotspot-tour') {const ctl = await mountHotspotTour(this.viewer, cfg, document.body);this._widgetController = ctl;+ } else if (type === 'pumpfun-feed') {+ const ctl = await mountPumpfunFeed(this.viewer, cfg, document.body, { protocol });+ this._widgetController = ctl;}} catch (e) {console.warn('[widget] mount failed', type, e?.message);diff --git a/src/onchain/README.md b/src/onchain/README.mdindex 609e9699c..e388ce920 100644--- a/src/onchain/README.md+++ b/src/onchain/README.md@@ -142,3 +142,57 @@ No UI changes required.`tests/src/onchain.test.js` — pure-logic coverage of `chain-ref` + adapterfactory dispatch. Wallet I/O is integration-tested via Playwright (not yetwritten for this module — TODO).++## Token launches (Pump.fun, …)++Layered on top of the deploy stack. Same pattern: a `TokenAdapter` interface+under `src/onchain/tokens/` with one impl today (`PumpfunTokenAdapter`) and+two endpoints (`/api/agents/tokens/launch-prep` + `launch-confirm`) writing a+canonical `meta.token` block on the agent record:++```json+{+ "token": {+ "provider": "pumpfun",+ "mint": "<base58>",+ "symbol": "AGT",+ "name": "Agent",+ "metadata_uri": "ipfs://...",+ "cluster": "mainnet" | "devnet",+ "creator": "<base58>",+ "tx_signature": "<base58>",+ "launched_at": "2026-...",+ "pumpfun_url": "https://pump.fun/<mint>"+ }+}+```++Mounting:++```js+import { LaunchTokenButton } from 'src/onchain/launch-token-button.js';+new LaunchTokenButton({ agent, container }).mount();+```++The button auto-hides itself unless the agent is deployed on Solana. After a+launch, it rehydrates as a chip linking to the Pump.fun page (mainnet) or+Solana Explorer (devnet).++Schema migration: `api/_lib/migrations/2026-04-29-token-launches.sql`.++Pump.fun specifics:+- The mint Keypair is generated server-side and partial-signs the launch tx.+ Its secret key never touches the client and is dropped after partial-signing.+- Optional `initial_buy_sol` (0–50) buys the first slot on the bonding curve+ in the same transaction as the create.+- Compute budget is bumped to 350k units — coin creation routinely overflows+ the 200k default and reverts otherwise.+- Mainnet only after deploy. Devnet works for QA via Pump.fun's devnet-tagged+ SDK builds (`@pump-fun/pump-sdk@*-devnet.*`).++Adding another launchpad:+1. Implement `TokenAdapter` in `src/onchain/tokens/<provider>.js`.+2. Add to `getTokenAdapter()` in `src/onchain/tokens/index.js`.+3. Branch on `provider` in `api/agents/tokens/launch-prep.js`.+4. UI auto-extends if you make the dropdown provider-aware (single provider+ today, no dropdown).diff --git a/src/widgets/pumpfun-feed.js b/src/widgets/pumpfun-feed.jsnew file mode 100644index 000000000..4746904cd--- /dev/null+++ b/src/widgets/pumpfun-feed.js@@ -0,0 +1,184 @@+/**+ * Pump.fun Live Feed Widget+ *+ * DOM overlay on top of the 3D viewer. Subscribes to /api/agents/pumpfun-feed+ * (SSE) and renders a stack of cards. When `autoNarrate` is on, the agent+ * narrates each event through the existing protocol bus — speak + emote+ * routed through the Empathy Layer (see src/CLAUDE.md "Empathy Layer").+ *+ * Config (validated in widget-types.js):+ * - kind 'all' | 'claims' | 'graduations'+ * - minTier '' | 'notable' | 'influencer' | 'mega'+ * - autoNarrate boolean+ * - maxCards 1..50+ */++const FEED_PATH = '/api/agents/pumpfun-feed';+const TIER_BADGE = { mega: '🔥🔥', influencer: '🔥', notable: '⭐' };++/**+ * @param {import('../viewer.js').Viewer} viewer+ * @param {object} config+ * @param {HTMLElement} container parent element to attach the overlay to+ * @param {{ protocol?: any }} [ctx]+ */+export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {+ const root = document.createElement('div');+ root.className = 'pumpfun-feed';+ root.style.cssText = [+ 'position:absolute',+ 'right:16px',+ 'top:16px',+ 'width:320px',+ 'max-height:80%',+ 'overflow-y:auto',+ 'pointer-events:auto',+ 'z-index:5',+ 'font-family:ui-sans-serif,system-ui,-apple-system,sans-serif',+ 'color:#fff',+ ].join(';');+ (container || document.body).appendChild(root);++ const status = document.createElement('div');+ status.style.cssText = 'opacity:0.6;font-size:12px;padding:4px 8px';+ status.textContent = 'Connecting to pump.fun feed…';+ root.appendChild(status);++ const stack = document.createElement('div');+ root.appendChild(stack);++ const params = new URLSearchParams();+ params.set('kind', config.kind || 'all');+ if (config.minTier) params.set('minTier', config.minTier);++ const es = new EventSource(`${FEED_PATH}?${params.toString()}`, {+ withCredentials: true,+ });++ const maxCards = Math.max(1, Math.min(50, config.maxCards || 8));+ const protocol = ctx.protocol || (typeof window !== 'undefined' ? window.VIEWER?.agent_protocol : null);++ es.addEventListener('open', () => {+ status.textContent = 'Live · pump.fun';+ });++ es.addEventListener('claim', (msg) => {+ const ev = safeJson(msg.data);+ if (!ev) return;+ addCard(stack, renderClaim(ev), maxCards);+ if (config.autoNarrate) narrateClaim(protocol, ev);+ });++ es.addEventListener('graduation', (msg) => {+ const ev = safeJson(msg.data);+ if (!ev) return;+ addCard(stack, renderGraduation(ev), maxCards);+ if (config.autoNarrate) narrateGraduation(protocol, ev);+ });++ es.addEventListener('error', () => {+ if (es.readyState === EventSource.CLOSED) {+ status.textContent = 'Disconnected.';+ }+ });++ es.addEventListener('close', () => {+ status.textContent = 'Reconnecting…';+ });++ return {+ destroy() {+ try {+ es.close();+ } catch {}+ root.remove();+ },+ };+}++function addCard(stack, el, max) {+ stack.prepend(el);+ while (stack.children.length > max) stack.lastChild?.remove();+}++function renderClaim(ev) {+ const el = document.createElement('div');+ el.style.cssText = cardStyle(ev.fake_claim ? '#3a1418' : ev.first_time_claim ? '#0d2d1a' : '#161616');+ const tier = ev.tier ? `${TIER_BADGE[ev.tier] || ''} ${ev.tier}` : '';+ const sol = ev.amount_sol != null ? `${Number(ev.amount_sol).toFixed(3)} SOL` : '';+ el.innerHTML = `+ <div style="display:flex;justify-content:space-between;font-size:11px;opacity:0.7">+ <span>${ev.first_time_claim ? '🚨 FIRST CLAIM' : 'Claim'}</span>+ <span>${tier}</span>+ </div>+ <div style="font-weight:600;margin-top:4px">${escapeHtml(ev.github_user ? '@' + ev.github_user : ev.claimer || '—')}</div>+ <div style="font-size:12px;opacity:0.85">${sol}${ev.token_symbol ? ' · $' + escapeHtml(ev.token_symbol) : ''}</div>+ ${ev.ai_take ? `<div style="font-size:11px;opacity:0.75;margin-top:4px;font-style:italic">${escapeHtml(ev.ai_take)}</div>` : ''}+ `;+ return el;+}++function renderGraduation(ev) {+ const el = document.createElement('div');+ el.style.cssText = cardStyle('#1a1632');+ el.innerHTML = `+ <div style="font-size:11px;opacity:0.7">🎓 Graduation</div>+ <div style="font-weight:600;margin-top:4px">${escapeHtml(ev.name || ev.symbol || ev.mint)}</div>+ ${ev.symbol ? `<div style="font-size:12px;opacity:0.85">$${escapeHtml(ev.symbol)}</div>` : ''}+ `;+ return el;+}++function cardStyle(bg) {+ return [+ `background:${bg}`,+ 'border:1px solid rgba(255,255,255,0.08)',+ 'border-radius:8px',+ 'padding:10px 12px',+ 'margin-bottom:6px',+ 'box-shadow:0 2px 6px rgba(0,0,0,0.3)',+ ].join(';');+}++function narrateClaim(protocol, ev) {+ if (!protocol) return;+ if (ev.first_time_claim) {+ protocol.emit({ type: 'emote', payload: { trigger: 'celebration', weight: 0.9 } });+ protocol.emit({+ type: 'speak',+ payload: {+ text: `First-time claim: ${ev.github_user ? '@' + ev.github_user : 'unknown'}${ev.ai_take ? ' — ' + ev.ai_take : ''}`,+ sentiment: 0.7,+ },+ });+ } else if (ev.fake_claim) {+ protocol.emit({ type: 'emote', payload: { trigger: 'concern', weight: 0.7 } });+ protocol.emit({+ type: 'speak',+ payload: { text: `Fake claim from ${ev.github_user || ev.claimer}.`, sentiment: -0.5 },+ });+ } else if (ev.tier === 'mega' || ev.tier === 'influencer') {+ protocol.emit({ type: 'emote', payload: { trigger: 'curiosity', weight: 0.5 } });+ }+}++function narrateGraduation(protocol, ev) {+ if (!protocol) return;+ protocol.emit({ type: 'gesture', payload: { name: 'wave', duration: 1500 } });+ protocol.emit({+ type: 'speak',+ payload: { text: `Graduation: ${ev.symbol || ev.name || 'a token'} hit PumpAMM.`, sentiment: 0.6 },+ });+}++function escapeHtml(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++function safeJson(s) {+ try {+ return JSON.parse(s);+ } catch {+ return null;+ }+}diff --git a/tests/api/solana-wallet.smoke.test.js b/tests/api/solana-wallet.smoke.test.jsnew file mode 100644index 000000000..50952d393--- /dev/null+++ b/tests/api/solana-wallet.smoke.test.js@@ -0,0 +1,77 @@+// Devnet smoke test for the solana-wallet skill + ctx.wallet contract.+//+// Verifies the full path: generate encrypted keypair → loadWallet → fund via+// devnet airdrop → transferSol round-trip → balance check.+//+// Skipped by default. Enable with:+// SOLANA_DEVNET_SMOKE=1 SOLANA_DEVNET_RPC=https://api.devnet.solana.com npx vitest run tests/api/solana-wallet.smoke.test.js+//+// Devnet airdrops are flaky/rate-limited; allow ~60s.++import { describe, it, expect } from 'vitest';+import { Connection, Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js';++import { generateSolanaAgentWallet } from '../../api/_lib/agent-wallet.js';+import { loadWallet } from '../../api/_lib/solana-wallet.js';+import {+ getAddress,+ getBalance,+ transferSol,+} from '../../examples/skills/solana-wallet/handlers.js';++const ENABLED = process.env.SOLANA_DEVNET_SMOKE === '1';+const RPC = process.env.SOLANA_DEVNET_RPC ?? 'https://api.devnet.solana.com';++const maybe = ENABLED ? describe : describe.skip;++maybe('solana-wallet (devnet smoke)', () => {+ it('round-trips: generate → airdrop → transferSol → balance', async () => {+ // Need JWT_SECRET for the encrypt/decrypt path.+ process.env.JWT_SECRET ??= 'devnet-smoke-secret';++ const { encrypted_secret, address } = await generateSolanaAgentWallet();+ const wallet = await loadWallet(encrypted_secret);+ expect(wallet.publicKey.toBase58()).toBe(address);++ const ctx = { wallet, skillConfig: { rpc: RPC, maxTransferSol: 1 } };++ const addr = await getAddress({}, ctx);+ expect(addr.ok).toBe(true);+ expect(addr.data.address).toBe(address);++ // Airdrop 0.5 SOL to fund the test.+ const conn = new Connection(RPC, 'confirmed');+ const sig = await conn.requestAirdrop(wallet.publicKey, 0.5 * LAMPORTS_PER_SOL);+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash();+ await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');++ const balBefore = await getBalance({}, ctx);+ expect(balBefore.data.sol).toBeGreaterThan(0.4);++ // Transfer 0.01 to a throwaway recipient.+ const recipient = Keypair.generate();+ const xfer = await transferSol(+ { to: recipient.publicKey.toBase58(), amountSol: 0.01 },+ ctx,+ );+ expect(xfer.ok).toBe(true);+ expect(typeof xfer.data.sig).toBe('string');++ const recipBal = await getBalance({ address: recipient.publicKey.toBase58() }, ctx);+ expect(recipBal.data.sol).toBeCloseTo(0.01, 4);+ }, 90_000);++ it('rejects transferSol over the cap', async () => {+ process.env.JWT_SECRET ??= 'devnet-smoke-secret';+ const { encrypted_secret } = await generateSolanaAgentWallet();+ const wallet = await loadWallet(encrypted_secret);+ const ctx = { wallet, skillConfig: { rpc: RPC, maxTransferSol: 0.001 } };+ const recipient = Keypair.generate();+ const res = await transferSol(+ { to: recipient.publicKey.toBase58(), amountSol: 1 },+ ctx,+ );+ expect(res.ok).toBe(false);+ expect(res.error).toMatch(/exceeds cap/);+ });+});diff --git a/tests/src/pump-fun-skill.test.js b/tests/src/pump-fun-skill.test.jsnew file mode 100644index 000000000..0e08f5696--- /dev/null+++ b/tests/src/pump-fun-skill.test.js@@ -0,0 +1,89 @@+// Validates the pump-fun skill bundle is internally consistent: manifest tools+// list, tools.json schemas, and handlers.js exports all match.++import { describe, it, expect } from 'vitest';+import { readFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++const __dirname = dirname(fileURLToPath(import.meta.url));+const BUNDLE = resolve(__dirname, '../../public/skills/pump-fun');++async function readJSON(rel) {+ return JSON.parse(await readFile(resolve(BUNDLE, rel), 'utf8'));+}++describe('pump-fun skill bundle', () => {+ it('manifest declares 10 tools and matches tools.json', async () => {+ const manifest = await readJSON('manifest.json');+ const toolsJSON = await readJSON('tools.json');++ expect(manifest.name).toBe('pump-fun');+ expect(manifest.spec).toBe('skill/0.1');+ expect(manifest.provides.tools).toHaveLength(10);++ const declared = new Set(manifest.provides.tools);+ const defined = new Set(toolsJSON.tools.map((t) => t.name));+ expect(defined).toEqual(declared);+ });++ it('every tool has an input schema', async () => {+ const { tools } = await readJSON('tools.json');+ for (const t of tools) {+ expect(t.description).toBeTruthy();+ expect(t.input_schema?.type).toBe('object');+ }+ });++ it('handlers.js exports every declared tool', async () => {+ const handlers = await import(resolve(BUNDLE, 'handlers.js'));+ const manifest = await readJSON('manifest.json');+ for (const tool of manifest.provides.tools) {+ expect(typeof handlers[tool]).toBe('function');+ }+ });++ it('skill is listed in the public skills index', async () => {+ const indexPath = resolve(__dirname, '../../public/skills-index.json');+ const index = JSON.parse(await readFile(indexPath, 'utf8'));+ const entry = index.find((s) => s.id === 'pump-fun');+ expect(entry).toBeDefined();+ expect(entry.uri).toBe('skills/pump-fun/');+ });++ it('handlers proxy through ctx.fetch with JSON-RPC tools/call shape', async () => {+ const handlers = await import(resolve(BUNDLE, 'handlers.js'));+ let captured;+ const ctx = {+ fetch: async (url, opts) => {+ captured = { url, body: JSON.parse(opts.body) };+ return {+ ok: true,+ json: async () => ({+ jsonrpc: '2.0',+ id: captured.body.id,+ result: { content: [{ type: 'text', text: '{"hits":[]}' }] },+ }),+ };+ },+ memory: { note: () => {} },+ };+ const result = await handlers.searchTokens({ query: 'pepe', limit: 3 }, ctx);+ expect(result.ok).toBe(true);+ expect(result.data).toEqual({ hits: [] });+ expect(captured.body.method).toBe('tools/call');+ expect(captured.body.params.name).toBe('searchTokens');+ expect(captured.body.params.arguments).toEqual({ query: 'pepe', limit: 3 });+ });++ it('handlers return { ok:false } on non-2xx responses', async () => {+ const handlers = await import(resolve(BUNDLE, 'handlers.js'));+ const ctx = {+ fetch: async () => ({ ok: false, status: 502, json: async () => ({}) }),+ memory: { note: () => {} },+ };+ const result = await handlers.getTrendingTokens({}, ctx);+ expect(result.ok).toBe(false);+ expect(result.error).toMatch(/502/);+ });+});diff --git a/vercel.json b/vercel.jsonindex baf0363a0..c7a95ffcc 100644--- a/vercel.json+++ b/vercel.json@@ -247,6 +247,7 @@{ "path": "/api/cron/solana-attestations-crawl", "schedule": "*/5 * * * *" },{ "path": "/api/cron/index-delegations", "schedule": "*/5 * * * *" },{ "path": "/api/cron/run-dca", "schedule": "0 * * * *" },- { "path": "/api/cron/run-subscriptions", "schedule": "0 * * * *" }+ { "path": "/api/cron/run-subscriptions", "schedule": "0 * * * *" },+ { "path": "/api/cron/pumpfun-signals", "schedule": "*/15 * * * *" }]}