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 closeAllPositions function and enhance SNS domain registration flow
nirholas515904152d41
diff --git a/.claude/scheduled_tasks.lock b/.claude/scheduled_tasks.lockdeleted file mode 100644index 648da27bd..000000000--- a/.claude/scheduled_tasks.lock+++ /dev/null@@ -1 +0,0 @@-{"sessionId":"ee95d5df-68e8-4e90-a66d-7cc9f1d5b817","pid":175522,"procStart":"299777","acquiredAt":1777459808377}\ No newline at end of filediff --git a/api/_lib/attest-event.js b/api/_lib/attest-event.jsnew file mode 100644index 000000000..f13c20c30--- /dev/null+++ b/api/_lib/attest-event.js@@ -0,0 +1,203 @@+// Shared core for emitting on-chain threews.* memo attestations.+//+// Used by the production webhook (api/agents/solana-attest-event.js) and the+// in-house pumpfun monitor cron (api/cron/pumpfun-monitor.js). The two share+// the same exactly-once primitive: a claim row in solana_attest_event_claims+// is the lock; the SPL Memo tx is the on-chain artifact; a row in+// solana_attestations mirrors it for the reputation reads.+//+// All callers must provide a deterministic event_id so a retry never produces+// a second on-chain tx for the same logical event.++import crypto from 'node:crypto';+import {+ Connection,+ Keypair,+ PublicKey,+ Transaction,+ TransactionInstruction,+ sendAndConfirmTransaction,+} from '@solana/web3.js';+import bs58 from 'bs58';++import { sql } from './db.js';+import { RPC, KIND_MAP } from './solana-attestations.js';++const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');+const TX_TIMEOUT_MS = 12_000;++export function taskHash(task_id, token_mint) {+ return crypto.createHash('sha256').update(`${task_id}:${token_mint}`).digest('hex');+}++/**+ * Build a threews.* attestation payload for a known event type.+ * Recognised sources: pumpkit.graduation|fee_claim|whale|cto, and the+ * in-house equivalents pumpfun.graduation|fee_claim|whale|cto.+ */+export function buildPayload({+ event_id, event_type, agent_asset, token_mint, task_id, detail,+ source = null,+}) {+ const ts = Math.floor(Date.now() / 1000);+ const base = { v: 1, agent: agent_asset, ts, event_id };+ const src = (s) => source ?? s;+ switch (event_type) {+ case 'graduation':+ return { ...base, kind: KIND_MAP.validation,+ task_hash: taskHash(task_id, token_mint), passed: true,+ source: src('pumpkit.graduation'), token: token_mint };+ case 'fee_claim':+ return { ...base, kind: KIND_MAP.feedback,+ score: 5, source: src('pumpkit.fee_claim'),+ token: token_mint, detail: detail ?? null };+ case 'whale_trade':+ return { ...base, kind: KIND_MAP.task,+ task_id, scope_hash: taskHash(task_id, token_mint),+ source: src('pumpkit.whale') };+ case 'cto_detected':+ return { ...base, kind: KIND_MAP.validation,+ task_hash: taskHash(task_id, token_mint), passed: false,+ source: src('pumpkit.cto'), token: token_mint };+ default:+ throw new Error(`unknown event_type: ${event_type}`);+ }+}++export function loadAttesterKeypair() {+ const k = process.env.ATTEST_AGENT_SECRET_KEY;+ if (!k) throw Object.assign(new Error('ATTEST_AGENT_SECRET_KEY not configured'), { status: 500 });+ return Keypair.fromSecretKey(bs58.decode(k));+}++function withTimeout(promise, ms, onTimeout) {+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(() => {+ onTimeout?.();+ reject(Object.assign(new Error(`rpc timeout after ${ms}ms`), { code: 'RPC_TIMEOUT' }));+ }, ms);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}++/**+ * Mint a single attestation, exactly-once.+ *+ * @param {object} input+ * @param {string} input.event_id Deterministic id; collision = idempotent dedupe.+ * @param {string} input.event_type 'graduation'|'fee_claim'|'whale_trade'|'cto_detected'+ * @param {string} input.source e.g. 'pumpfun.graduation' (in-house) or 'pumpkit.graduation'.+ * @param {string} input.agent_asset Metaplex Core asset pubkey.+ * @param {'mainnet'|'devnet'} input.network+ * @param {string} input.token_mint+ * @param {string} input.task_id+ * @param {object} [input.detail]+ * @param {Keypair} [input.attester] Defaults to loadAttesterKeypair().+ *+ * @returns {Promise<{ status: 'minted'|'deduped'|'in_progress', signature: string|null, kind: string|null }>}+ */+export async function mintAttestation(input) {+ const {+ event_id, event_type, source,+ agent_asset, network, token_mint, task_id, detail,+ attester = loadAttesterKeypair(),+ } = input;++ if (!event_id || !event_type || !agent_asset || !network || !token_mint || !task_id) {+ throw new Error('mintAttestation: missing required fields');+ }++ const attesterPubkey = attester.publicKey.toBase58();++ // Pre-tx claim — the lock that prevents duplicate on-chain txs.+ const claim = await sql`+ insert into solana_attest_event_claims (agent_asset, network, event_id, attester)+ values (${agent_asset}, ${network}, ${event_id}, ${attesterPubkey})+ on conflict (agent_asset, network, event_id) do nothing+ returning claimed_at+ `;+ if (claim.length === 0) {+ const [winner] = await sql`+ select signature from solana_attest_event_claims+ where agent_asset = ${agent_asset}+ and network = ${network}+ and event_id = ${event_id}+ `;+ return winner?.signature+ ? { status: 'deduped', signature: winner.signature, kind: null }+ : { status: 'in_progress', signature: null, kind: null };+ }++ const payload = buildPayload({+ event_id, event_type, agent_asset, token_mint, task_id, detail, source,+ });+ const memo = JSON.stringify(payload);++ const conn = new Connection(RPC[network] || RPC.devnet, 'confirmed');+ const ix = new TransactionInstruction({+ programId: MEMO_PROGRAM_ID,+ keys: [+ { pubkey: attester.publicKey, isSigner: true, isWritable: false },+ { pubkey: new PublicKey(agent_asset), isSigner: false, isWritable: false },+ ],+ data: Buffer.from(memo, 'utf8'),+ });+ const tx = new Transaction().add(ix);++ let signature;+ try {+ signature = await withTimeout(+ sendAndConfirmTransaction(conn, tx, [attester], { commitment: 'confirmed' }),+ TX_TIMEOUT_MS,+ );+ } catch (e) {+ // Release the claim so a future retry can try again.+ await sql`+ delete from solana_attest_event_claims+ where agent_asset = ${agent_asset}+ and network = ${network}+ and event_id = ${event_id}+ and signature is null+ `;+ throw e;+ }++ await sql`+ update solana_attest_event_claims+ set signature = ${signature}, completed_at = now()+ where agent_asset = ${agent_asset}+ and network = ${network}+ and event_id = ${event_id}+ `;++ try {+ await sql`+ insert into solana_attestations (+ signature, network, slot, block_time, agent_asset, attester,+ kind, payload, task_id, target_signature, verified+ )+ values (+ ${signature}, ${network}, null, now(),+ ${agent_asset}, ${attesterPubkey},+ ${payload.kind}, ${JSON.stringify(payload)}::jsonb,+ ${payload.task_id ?? null}, null, true+ )+ on conflict (signature) do nothing+ `;+ } catch (e) {+ if (e?.code !== '23505') throw e;+ // Lost race against the unique partial index — claim row already won+ // the serialization, so signature above is canonical.+ }++ return { status: 'minted', signature, kind: payload.kind };+}++/** Deterministic event id for a logical pumpfun event. */+export function deriveEventId({ event_type, mint, slot_or_ts }) {+ return crypto.createHash('sha256')+ .update(`${event_type}:${mint}:${slot_or_ts}`)+ .digest('hex')+ .slice(0, 32);+}diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 5cff799fe..acc01051a 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -179,19 +179,6 @@ export const env = {return opt('X402_FACILITATOR_TOKEN_BASE');},- // ── SNS subdomain registrar ─────────────────────────────────────────────- // Project-owned parent .sol that we mint subdomains under (e.g. "agents"- // to issue {label}.agents.sol). The platform pays rent + tx fees.- // Optional — when unset, /api/agents/:id/sns/register returns 503.- get SNS_PARENT_DOMAIN() {- // label only, no .sol suffix (e.g. "agents")- return opt('SNS_PARENT_DOMAIN');- },- // Base64-encoded 64-byte secret key of the parent domain owner.- // Used to sign the createSubdomain + transferNameOwnership ixs.- get SNS_PARENT_OWNER_SECRET() {- return opt('SNS_PARENT_OWNER_SECRET');- },// Solana RPC URL used for SNS reads/writes. Falls back to public mainnet RPC.get SOLANA_RPC_URL() {return opt('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com');diff --git a/api/_lib/migrations/2026-04-29-pumpfun-monitor-cursor.sql b/api/_lib/migrations/2026-04-29-pumpfun-monitor-cursor.sqlnew file mode 100644index 000000000..a8de21b4d--- /dev/null+++ b/api/_lib/migrations/2026-04-29-pumpfun-monitor-cursor.sql@@ -0,0 +1,20 @@+-- Migration: in-house pumpfun monitor cursor.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-04-29-pumpfun-monitor-cursor.sql+-- Idempotent.+--+-- Tracks what the cron has already attested per mint so it never emits a+-- duplicate on-chain memo on a re-run. Independent of the claim table; the+-- claim guarantees exactly-once at the tx layer, this cursor cuts the+-- per-tick scan from O(all rows) to O(only-new).++begin;++create table if not exists pumpfun_monitor_cursor (+ mint_id uuid primary key references pump_agent_mints(id) on delete cascade,+ last_graduated boolean,+ last_authority text,+ last_trade_signature text,+ last_processed_at timestamptz not null default now()+);++commit;diff --git a/api/agents/SOLANA_OPS.md b/api/agents/SOLANA_OPS.mdindex a05384491..cf7097987 100644--- a/api/agents/SOLANA_OPS.md+++ b/api/agents/SOLANA_OPS.md@@ -34,8 +34,9 @@ Single source of truth for what's deployed, what env vars enable it, what cron s|---|---|---|| `/api/cron/solana-attestations-crawl` | `*/5 * * * *` | Crawl SPL Memo attestations into `solana_attestations`. || `/api/cron/erc8004-crawl` | `*/15 * * * *` | EVM IdentityRegistry crawler. |-| `/api/cron/pumpfun-signals` | `*/15 * * * *` | Pull claim/graduation signals from upstream MCP. |-| `/api/cron/pump-agent-stats` | `*/10 * * * *` | Refresh pump.fun token state per agent. |+| `/api/cron/pumpfun-signals` | `*/15 * * * *` | Pull claim/graduation signals from upstream MCP. *Optional* — only enabled if `PUMPFUN_BOT_URL` is set. |+| `/api/cron/pump-agent-stats` | `*/10 * * * *` | Refresh pump.fun token state per agent (graduation flag, AMM/curve snapshots, recent trades). |+| `/api/cron/pumpfun-monitor` | `*/3 * * * *` | **In-house event-attested source.** Diffs `pump_agent_stats` vs cursor; mints real on-chain `threews.*` memos with `payload.source = 'pumpfun.*'` whenever graduation or authority flips. No upstream bot required. || `/api/cron/solana-attest-event-cleanup` | `*/10 * * * *` | Reap stale claim rows (>1h, signature null). |## Database tables@@ -47,6 +48,7 @@ psql "$DATABASE_URL" -f api/_lib/migrations/<file>.sqlThe new ones are:- `2026-04-29-attest-event-bridge.sql` — `solana_attest_event_claims` + the partial unique index `solana_attestations_event_id_uniq`.+- `2026-04-29-pumpfun-monitor-cursor.sql` — `pumpfun_monitor_cursor` for the in-house monitor.Pre-existing relevant tables: `solana_attestations`, `solana_attestations_cursor`, `solana_credentials`, `pump_agent_mints`, `pump_agent_payments`, `pump_agent_stats`, `pump_agent_trades`, `pumpfun_signals`, `agent_identities`, `usage_events`.diff --git a/api/agents/[id].js b/api/agents/[id].jsindex b2659de7f..215ee30d0 100644--- a/api/agents/[id].js+++ b/api/agents/[id].js@@ -5,7 +5,9 @@* /api/agents/:id/solana/activity — recent on-chain signatures for the wallet* /api/agents/:id/solana/airdrop — devnet airdrop (1 SOL)* /api/agents/:id/sns — list owned .sol domains and attach one as the agent's SNS id- * /api/agents/:id/sns/register — mint a free subdomain under the platform's parent .sol+ * /api/agents/:id/sns/register — register a .sol; agent wallet pays USDC+ * /api/agents/:id/sns/register-prep — build unsigned tx for user wallet to sign+ * /api/agents/:id/sns/register-confirm — confirm a user-wallet registration and attach* /api/agents/:id/pumpfun/launch — create a pump.fun token from this agent* /api/agents/:id/pumpfun/buy — bonding-curve buy* /api/agents/:id/pumpfun/sell — bonding-curve selldiff --git a/api/agents/sns.js b/api/agents/sns.jsindex 9f999a599..757259815 100644--- a/api/agents/sns.js+++ b/api/agents/sns.js@@ -1,26 +1,39 @@// /api/agents/:id/sns//// GET — list .sol domains the agent's Solana wallet owns (via Bonfida-// sns-api.bonfida.com), plus the wallet's favorite/primary domain,-// the currently-attached SNS id (meta.sns_domain), and whether the-// subdomain registrar is configured (so the UI can show /register).-// POST — body { domain } — verify the agent's wallet owns `domain`, then-// save it as the agent's SNS id (meta.sns_domain).+// sns-api.bonfida.com), the wallet's favorite/primary domain,+// the currently-attached SNS id (meta.sns_domain), and which+// registration modes are enabled.+// POST — body { domain } — verify the agent's wallet (or one of the+// caller's linked Solana wallets) owns `domain`, then save it as+// the agent's SNS id (meta.sns_domain).// DELETE — clear meta.sns_domain.//// /api/agents/:id/sns/register-// POST — body { label } — mint {label}.{SNS_PARENT_DOMAIN}.sol as a-// subdomain owned by the agent's wallet. Platform pays gas+rent.-// On success, sets meta.sns_domain = "{label}.{SNS_PARENT_DOMAIN}".+// POST — Option A: agent wallet pays. Body { domain, space?, referrer? }.+// Server signs with the agent's keypair; agent's USDC ATA pays.+// On success sets meta.sns_domain.+//+// /api/agents/:id/sns/register-prep+// POST — Option B step 1: build an unsigned tx for the user's wallet to+// sign. Body { domain, wallet_address, space? }. Returns a base64+// VersionedTransaction the browser submits via wallet adapter.+//+// /api/agents/:id/sns/register-confirm+// POST — Option B step 2: body { signature, domain, wallet_address }.+// Confirms on-chain owner = wallet_address, then sets meta.sns_domain+// (the user owns the domain; we only store the alias against the agent).import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';import { cors, json, method, error, readJson } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { env } from '../_lib/env.js';+import { loadAgentForSigning, solanaConnection } from '../_lib/agent-pumpfun.js';const SNS_API = 'https://sns-api.bonfida.com';const DOMAIN_RE = /^[a-z0-9-]{1,63}(\.sol)?$/i;+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';function normalizeDomain(input) {if (typeof input !== 'string') return null;@@ -50,94 +63,165 @@ async function fetchFavoriteDomain(address) {}}-function registrarConfigured() {- return Boolean(env.SNS_PARENT_DOMAIN && env.SNS_PARENT_OWNER_SECRET);+async function getRegistryOwner(connection, domain) {+ const sns = await import('@bonfida/spl-name-service');+ const { pubkey } = sns.getDomainKeySync(domain);+ const { registry } = await sns.NameRegistryState.retrieve(connection, pubkey);+ return registry.owner.toBase58();}-async function registerSubdomain(label, agentAddress) {- const { Connection, Keypair, PublicKey, Transaction } = await import('@solana/web3.js');+async function buildRegisterIxs({ connection, domain, buyer, space }) {+ const { PublicKey } = await import('@solana/web3.js');+ const { getAssociatedTokenAddressSync } = await import('@solana/spl-token');const sns = await import('@bonfida/spl-name-service');+ const usdcMint = new PublicKey(USDC_MINT);+ const buyerAta = getAssociatedTokenAddressSync(usdcMint, buyer, true);+ return sns.registerDomainNameV2(connection, domain, space || 1000, buyer, buyerAta, usdcMint);+}++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++// ── Option A: agent wallet pays + auto-attach ─────────────────────────────+async function handleRegisterAgent(req, res, id, auth) {+ if (!method(req, res, ['POST'])) return;+ const body = await readJson(req).catch(() => ({}));+ const domain = normalizeDomain(body?.domain);+ if (!domain) return error(res, 400, 'validation_error', 'domain required (a–z, 0–9, hyphen)');+ const space = Number.isInteger(body?.space) && body.space >= 1000 && body.space <= 10000 ? body.space : 1000;++ const loaded = await loadAgentForSigning(id, auth.userId, { reason: 'sns_register' });+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);+ const { keypair } = loaded;+ let meta = { ...(loaded.meta || {}) };- const parentLabel = String(env.SNS_PARENT_DOMAIN).trim().toLowerCase().replace(/\.sol$/, '');- const secretBuf = Buffer.from(env.SNS_PARENT_OWNER_SECRET, 'base64');- if (secretBuf.length !== 64) throw new Error('SNS_PARENT_OWNER_SECRET must be base64 of a 64-byte secret key');- const parentOwner = Keypair.fromSecretKey(Uint8Array.from(secretBuf));- const fullSub = `${label}.${parentLabel}`;- const newOwner = new PublicKey(agentAddress);- const conn = new Connection(env.SOLANA_RPC_URL, 'confirmed');+ const { Transaction } = await import('@solana/web3.js');+ const conn = solanaConnection('mainnet');- // Fail fast if the subdomain already exists (createNameRegistry would error mid-tx).try {- const { pubkey } = sns.getDomainKeySync(fullSub);- const info = await conn.getAccountInfo(pubkey);- if (info?.data) throw new Error(`${fullSub}.sol is already registered`);- } catch (e) {- if (e?.message?.includes('already registered')) throw e;+ if (await getRegistryOwner(conn, domain).catch(() => null)) {+ return error(res, 409, 'conflict', `${domain}.sol is already registered`);+ }+ const ixs = await buildRegisterIxs({ connection: conn, domain, buyer: keypair.publicKey, space });+ const tx = new Transaction().add(...ixs);+ tx.feePayer = keypair.publicKey;+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');+ tx.recentBlockhash = blockhash;+ tx.sign(keypair);+ const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });+ await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');++ meta = { ...meta, sns_domain: domain };+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;+ return json(res, 201, {+ data: { ok: true, address: meta.solana_address, sns_domain: domain, signature: sig, mode: 'agent' },+ });+ } catch (err) {+ console.error('[agents/sns/register-agent] failed', err);+ const msg = err?.message || 'registration failed';+ return error(res, 502, 'upstream_error', msg);+ }+}++// ── Option B step 1: build unsigned tx for user wallet ────────────────────+async function handleRegisterPrep(req, res, id, auth) {+ if (!method(req, res, ['POST'])) return;+ const body = await readJson(req).catch(() => ({}));+ const domain = normalizeDomain(body?.domain);+ if (!domain) return error(res, 400, 'validation_error', 'domain required');+ const walletAddress = String(body?.wallet_address || '').trim();+ if (walletAddress.length < 32 || walletAddress.length > 44) {+ return error(res, 400, 'validation_error', 'wallet_address required');+ }+ const space = Number.isInteger(body?.space) && body.space >= 1000 && body.space <= 10000 ? body.space : 1000;++ const [agent] = await sql`+ SELECT id FROM agent_identities WHERE id = ${id} AND user_id = ${auth.userId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');++ const [walletRow] = await sql`+ SELECT id FROM user_wallets+ WHERE user_id = ${auth.userId} AND address = ${walletAddress} AND chain_type = 'solana'+ LIMIT 1+ `;+ if (!walletRow) return error(res, 403, 'forbidden', 'wallet not linked to your account');++ const { PublicKey, TransactionMessage, VersionedTransaction } = await import('@solana/web3.js');+ const conn = solanaConnection('mainnet');+ if (await getRegistryOwner(conn, domain).catch(() => null)) {+ return error(res, 409, 'conflict', `${domain}.sol is already registered`);}- const createIxs = await sns.createSubdomain(conn, fullSub, parentOwner.publicKey, 2000, parentOwner.publicKey);- const transferIx = await sns.transferSubdomain(conn, fullSub, newOwner, true);- const tx = new Transaction().add(...createIxs, transferIx);- tx.feePayer = parentOwner.publicKey;+ const buyer = new PublicKey(walletAddress);+ const ixs = await buildRegisterIxs({ connection: conn, domain, buyer, space });const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');- tx.recentBlockhash = blockhash;- tx.sign(parentOwner);- const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });- await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');- return { signature: sig, domain: fullSub };+ const msg = new TransactionMessage({ payerKey: buyer, recentBlockhash: blockhash, instructions: ixs }).compileToV0Message();+ const tx = new VersionedTransaction(msg);+ return json(res, 200, {+ data: {+ tx_base64: Buffer.from(tx.serialize()).toString('base64'),+ blockhash,+ last_valid_block_height: lastValidBlockHeight,+ domain,+ },+ });}-async function handleRegister(req, res, id, auth) {+// ── Option B step 2: confirm and attach ───────────────────────────────────+async function handleRegisterConfirm(req, res, id, auth) {if (!method(req, res, ['POST'])) return;- if (!registrarConfigured()) {- return error(res, 503, 'not_configured', 'subdomain registrar is not set up on this deployment');+ const body = await readJson(req).catch(() => ({}));+ const domain = normalizeDomain(body?.domain);+ const signature = String(body?.signature || '').trim();+ const walletAddress = String(body?.wallet_address || '').trim();+ if (!domain || !signature || !walletAddress) {+ return error(res, 400, 'validation_error', 'domain, signature, wallet_address required');}const [row] = await sql`- SELECT id, user_id, meta FROM agent_identities- WHERE id = ${id} AND deleted_at IS NULL+ SELECT meta FROM agent_identities WHERE id = ${id} AND user_id = ${auth.userId} AND deleted_at IS NULL`;if (!row) return error(res, 404, 'not_found', 'agent not found');- if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');- let meta = { ...(row.meta || {}) };- if (!meta.solana_address) {- return error(res, 409, 'conflict', 'agent has no solana wallet — provision one first');- }- const body = await readJson(req).catch(() => ({}));- const label = normalizeDomain(body?.label);- if (!label) return error(res, 400, 'validation_error', 'label must be a valid subdomain (a–z, 0–9, hyphen; max 63 chars)');+ const [walletRow] = await sql`+ SELECT id FROM user_wallets+ WHERE user_id = ${auth.userId} AND address = ${walletAddress} AND chain_type = 'solana'+ LIMIT 1+ `;+ if (!walletRow) return error(res, 403, 'forbidden', 'wallet not linked to your account');- let result;+ const conn = solanaConnection('mainnet');+ let confirmed;try {- result = await registerSubdomain(label, meta.solana_address);- } catch (err) {- console.error('[agents/sns/register] failed', err);- const msg = err?.message || 'registration failed';- const status = /already registered/i.test(msg) ? 409 : 502;- return error(res, status, status === 409 ? 'conflict' : 'upstream_error', msg);+ confirmed = await conn.getSignatureStatus(signature, { searchTransactionHistory: true });+ } catch {}+ if (!confirmed?.value || confirmed.value.err) {+ return error(res, 400, 'not_confirmed', 'tx not confirmed yet — try again in a moment');+ }++ let onChainOwner;+ try {+ onChainOwner = await getRegistryOwner(conn, domain);+ } catch {+ return error(res, 502, 'upstream_error', 'failed to read registry');+ }+ if (onChainOwner !== walletAddress) {+ return error(res, 409, 'conflict', `on-chain owner ${onChainOwner} does not match ${walletAddress}`);}- meta = { ...meta, sns_domain: result.domain };+ const meta = { ...(row.meta || {}), sns_domain: domain, sns_owner_wallet: walletAddress };await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;- return json(res, 201, {- data: {- ok: true,- address: meta.solana_address,- sns_domain: result.domain,- signature: result.signature,- },+ return json(res, 200, {+ data: { ok: true, sns_domain: domain, owner: walletAddress, signature, mode: 'user' },});}-async function resolveAuth(req) {- const session = await getSessionUser(req);- if (session) return { userId: session.id };- const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId };- return null;-}-export default async function handler(req, res, id, action) {if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;@@ -147,7 +231,9 @@ export default async function handler(req, res, id, action) {const rl = await limits.authIp(clientIp(req));if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');- if (action === 'register') return handleRegister(req, res, id, auth);+ if (action === 'register') return handleRegisterAgent(req, res, id, auth);+ if (action === 'register-prep') return handleRegisterPrep(req, res, id, auth);+ if (action === 'register-confirm') return handleRegisterConfirm(req, res, id, auth);if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;@@ -166,6 +252,7 @@ export default async function handler(req, res, id, action) {if (req.method === 'DELETE') {delete meta.sns_domain;+ delete meta.sns_owner_wallet;await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;return json(res, 200, { data: { ok: true, address, sns_domain: null } });}@@ -178,19 +265,36 @@ export default async function handler(req, res, id, action) {const domain = normalizeDomain(body.domain);if (!domain) return error(res, 400, 'validation_error', 'invalid .sol domain');- let owned;- try {- owned = await fetchOwnedDomains(address);- } catch (err) {- return error(res, 502, 'upstream_error', 'sns lookup failed');+ // Accept the domain if it's owned by the agent OR by any Solana wallet+ // linked to the caller's account.+ const linked = await sql`+ SELECT address FROM user_wallets+ WHERE user_id = ${auth.userId} AND chain_type = 'solana'+ `;+ const candidates = [address, ...linked.map((r) => r.address)];++ let ownerAddress = null;+ for (const cand of candidates) {+ let owned;+ try {+ owned = await fetchOwnedDomains(cand);+ } catch {+ continue;+ }+ if (owned.includes(domain)) {+ ownerAddress = cand;+ break;+ }}- if (!owned.includes(domain)) {- return error(res, 403, 'forbidden', `wallet ${address} does not own ${domain}.sol`);+ if (!ownerAddress) {+ return error(res, 403, 'forbidden', `${domain}.sol is not owned by this agent's wallet or any wallet linked to your account`);}meta = { ...meta, sns_domain: domain };+ if (ownerAddress !== address) meta.sns_owner_wallet = ownerAddress;+ else delete meta.sns_owner_wallet;await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;- return json(res, 200, { data: { ok: true, address, sns_domain: domain } });+ return json(res, 200, { data: { ok: true, address, sns_domain: domain, owner: ownerAddress } });}// GET@@ -206,13 +310,13 @@ export default async function handler(req, res, id, action) {data: {address,sns_domain: meta.sns_domain || null,+ sns_owner_wallet: meta.sns_owner_wallet || null,domains,favorite,upstream_ok: upstreamOk,register_url: `https://www.sns.id/?search=`,- registrar: registrarConfigured()- ? { enabled: true, parent: String(env.SNS_PARENT_DOMAIN).replace(/\.sol$/, '') }- : { enabled: false },+ modes: { agent_pays: true, user_pays: true },+ usdc_mint: USDC_MINT,},});}diff --git a/api/agents/solana-attest-event.js b/api/agents/solana-attest-event.jsindex a72b13bdd..d52a241f7 100644--- a/api/agents/solana-attest-event.js+++ b/api/agents/solana-attest-event.js@@ -14,25 +14,20 @@// Replay: rejects timestamps outside REPLAY_WINDOW_SECS.import crypto from 'node:crypto';-import {- Connection,- Keypair,- PublicKey,- Transaction,- TransactionInstruction,- sendAndConfirmTransaction,-} from '@solana/web3.js';-import bs58 from 'bs58';import { z } from 'zod';import { sql } from '../_lib/db.js';import { cors, json, method, wrap, error } from '../_lib/http.js';import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { RPC, KIND_MAP } from '../_lib/solana-attestations.js';import { recordEvent } from '../_lib/usage.js';+import {+ mintAttestation,+ loadAttesterKeypair,+ taskHash as _taskHash,+ buildPayload as _buildPayload,+} from '../_lib/attest-event.js';-const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');const REPLAY_WINDOW_SECS = 5 * 60;const MAX_BODY_BYTES = 64_000;@@ -46,33 +41,10 @@ const bodySchema = z.object({detail: z.record(z.unknown()).optional(),});-// -- Pure helpers (exported for tests) -----------------------------------+// -- Pure helpers (re-exported for tests, backed by the shared core) ------export function taskHash(task_id, token_mint) {- return crypto.createHash('sha256').update(`${task_id}:${token_mint}`).digest('hex');-}--export function buildPayload({ event_id, event_type, agent_asset, token_mint, task_id, detail }) {- const base = { v: 1, agent: agent_asset, ts: Math.floor(Date.now() / 1000), event_id };- switch (event_type) {- case 'graduation':- return { ...base, kind: KIND_MAP.validation,- task_hash: taskHash(task_id, token_mint), passed: true,- source: 'pumpkit.graduation', token: token_mint };- case 'fee_claim':- return { ...base, kind: KIND_MAP.feedback,- score: 5, source: 'pumpkit.fee_claim',- token: token_mint, detail: detail ?? null };- case 'whale_trade':- return { ...base, kind: KIND_MAP.task,- task_id, scope_hash: taskHash(task_id, token_mint),- source: 'pumpkit.whale' };- case 'cto_detected':- return { ...base, kind: KIND_MAP.validation,- task_hash: taskHash(task_id, token_mint), passed: false,- source: 'pumpkit.cto', token: token_mint };- }-}+export const taskHash = _taskHash;+export const buildPayload = _buildPayload;// Signed message is `${timestamp}.${raw}` — binds body to its declared time// so a captured signature can't be replayed against a fresh body.@@ -93,12 +65,6 @@ export function verifyPumpkitSignature({ secret, timestamp, signature, raw, nowS// -- Handler --------------------------------------------------------------function loadAttesterKeypair() {- const k = process.env.ATTEST_AGENT_SECRET_KEY;- if (!k) throw Object.assign(new Error('attester key not configured'), { status: 500 });- return Keypair.fromSecretKey(bs58.decode(k));-}-async function readBuffered(req) {const chunks = [];let total = 0;@@ -136,7 +102,6 @@ export default wrap(async (req, res) => {catch { return error(res, 400, 'validation_error', 'invalid JSON'); }const body = parse(bodySchema, parsed);- // Confirm the agent exists in our registry on the declared network.const [agent] = await sql`select id, user_id from agent_identitieswhere meta->'onchain'->>'sol_asset' = ${body.agent_asset}@@ -145,127 +110,36 @@ export default wrap(async (req, res) => {`;if (!agent) return error(res, 404, 'not_found', 'agent_asset not registered');- const attester = loadAttesterKeypair();- const attesterPubkey = attester.publicKey.toBase58();-- // Pre-tx claim: INSERT ... ON CONFLICT DO NOTHING serialises retries.- // The first delivery wins the row and proceeds to send the on-chain tx.- // Concurrent retries get rowCount === 0, then poll the existing row.- const claim = await sql`- insert into solana_attest_event_claims (agent_asset, network, event_id, attester)- values (${body.agent_asset}, ${body.network}, ${body.event_id}, ${attesterPubkey})- on conflict (agent_asset, network, event_id) do nothing- returning claimed_at- `;- const wonClaim = claim.length > 0;-- if (!wonClaim) {- const [winner] = await sql`- select signature from solana_attest_event_claims- where agent_asset = ${body.agent_asset}- and network = ${body.network}- and event_id = ${body.event_id}- `;- if (winner?.signature) {- return json(res, 200, { data: { signature: winner.signature, deduped: true } });- }- // Leader is still processing — caller should retry shortly.- return json(res, 202, { data: { deduped: true, status: 'in_progress' } });- }-- const payload = buildPayload(body);- const memo = JSON.stringify(payload);-- const conn = new Connection(RPC[body.network], 'confirmed');- const agentKey = new PublicKey(body.agent_asset);-- // Memo includes the agent asset as a non-signer key so- // getSignaturesForAddress(agent) finds the tx during crawl.- const ix = new TransactionInstruction({- programId: MEMO_PROGRAM_ID,- keys: [- { pubkey: attester.publicKey, isSigner: true, isWritable: false },- { pubkey: agentKey, isSigner: false, isWritable: false },- ],- data: Buffer.from(memo, 'utf8'),+ const result = await mintAttestation({+ event_id: body.event_id,+ event_type: body.event_type,+ source: `pumpkit.${body.event_type === 'cto_detected' ? 'cto' : body.event_type === 'whale_trade' ? 'whale' : body.event_type}`,+ agent_asset: body.agent_asset,+ network: body.network,+ token_mint: body.token_mint,+ task_id: body.task_id,+ detail: body.detail,+ attester: loadAttesterKeypair(),});- const tx = new Transaction().add(ix);- let signature;- try {- signature = await sendAndConfirmTransaction(conn, tx, [attester], { commitment: 'confirmed' });- } catch (e) {- // Release the claim so a future retry can try again.- await sql`- delete from solana_attest_event_claims- where agent_asset = ${body.agent_asset}- and network = ${body.network}- and event_id = ${body.event_id}- and signature is null- `;- throw e;- }-- // Record the winning signature on the claim so racing retries can return it.- await sql`- update solana_attest_event_claims- set signature = ${signature}, completed_at = now()- where agent_asset = ${body.agent_asset}- and network = ${body.network}- and event_id = ${body.event_id}- `;-- // Mirror into the index immediately; crawler dedupes via unique signature.- // Verified semantics match _lib/solana-attestations.js#computeVerified for- // non-owner kinds (feedback/validation/task): structurally valid -> true.- //- // The partial unique index solana_attestations_event_id_uniq closes the- // race window between the dedupe SELECT above and this INSERT. If a- // concurrent webhook delivery already inserted, we catch 23505 and- // return the winning signature.- try {- await sql`- insert into solana_attestations (- signature, network, slot, block_time, agent_asset, attester,- kind, payload, task_id, target_signature, verified- )- values (- ${signature}, ${body.network}, null, now(),- ${body.agent_asset}, ${attester.publicKey.toBase58()},- ${payload.kind}, ${JSON.stringify(payload)}::jsonb,- ${payload.task_id ?? null}, null, true- )- on conflict (signature) do nothing- `;- } catch (e) {- if (e?.code !== '23505') throw e;- const [winner] = await sql`- select signature from solana_attestations- where agent_asset = ${body.agent_asset}- and network = ${body.network}- and payload->>'event_id' = ${body.event_id}- limit 1- `;- recordEvent({- userId: agent.user_id,- agentId: agent.id,- kind: 'attest_event',- tool: `pumpkit.${body.event_type}`,- status: 'deduped',- latencyMs: Date.now() - startedAt,- meta: { network: body.network, event_id: body.event_id, signature: winner?.signature ?? null },- });- return json(res, 200, { data: { signature: winner?.signature ?? null, deduped: true } });- }-- recordEvent({+ const baseLog = {userId: agent.user_id,agentId: agent.id,kind: 'attest_event',tool: `pumpkit.${body.event_type}`,- status: 'ok',latencyMs: Date.now() - startedAt,- meta: { network: body.network, event_id: body.event_id, signature, kind: payload.kind },- });- return json(res, 201, { data: { signature, kind: payload.kind, deduped: false } });+ meta: { network: body.network, event_id: body.event_id, signature: result.signature },+ };++ if (result.status === 'minted') {+ recordEvent({ ...baseLog, status: 'ok', meta: { ...baseLog.meta, kind: result.kind } });+ return json(res, 201, { data: { signature: result.signature, kind: result.kind, deduped: false } });+ }+ if (result.status === 'deduped') {+ recordEvent({ ...baseLog, status: 'deduped' });+ return json(res, 200, { data: { signature: result.signature, deduped: true } });+ }+ // in_progress+ recordEvent({ ...baseLog, status: 'in_progress' });+ return json(res, 202, { data: { deduped: true, status: 'in_progress' } });});diff --git a/api/agents/solana-reputation.js b/api/agents/solana-reputation.jsindex b142512f4..6be100c16 100644--- a/api/agents/solana-reputation.js+++ b/api/agents/solana-reputation.js@@ -66,7 +66,7 @@ export default wrap(async (req, res) => {and c.closed = falseand (c.expiry is null or c.expiry > now())) as credentialed,- (f.payload->>'source' like 'pumpkit.%') as event_attested+ (f.payload->>'source' like 'pumpkit.%' or f.payload->>'source' like 'pumpfun.%') as event_attestedfrom solana_attestations fwhere f.agent_asset = ${asset}and f.network = ${network}@@ -103,9 +103,9 @@ export default wrap(async (req, res) => {count(*) filter (where (payload->>'passed')::bool)::int as passed,count(*) filter (where not (payload->>'passed')::bool)::int as failed,count(*) filter (where (payload->>'passed')::bool- and payload->>'source' like 'pumpkit.%')::int as event_passed,+ and (payload->>'source' like 'pumpkit.%' or payload->>'source' like 'pumpfun.%'))::int as event_passed,count(*) filter (where not (payload->>'passed')::bool- and payload->>'source' like 'pumpkit.%')::int as event_failed+ and (payload->>'source' like 'pumpkit.%' or payload->>'source' like 'pumpfun.%'))::int as event_failedfrom solana_attestationswhere agent_asset = ${asset} and network = ${network}and kind = 'threews.validation.v1' and revoked = falsediff --git a/api/cron/pumpfun-monitor.js b/api/cron/pumpfun-monitor.jsnew file mode 100644index 000000000..0293c86af--- /dev/null+++ b/api/cron/pumpfun-monitor.js@@ -0,0 +1,156 @@+/**+ * In-house pumpfun -> attestation monitor.+ *+ * Reads the live state already maintained by `/api/cron/pump-agent-stats`+ * (graduation flag, AMM/curve snapshots, recent trades) and emits real+ * on-chain threews.* SPL Memo attestations whenever a tracked condition+ * flips. This makes the event-attested reputation tier work *without*+ * any external pumpkit/MCP bot configured.+ *+ * Runs every 3 minutes via Vercel Cron (vercel.json). Manually triggerable+ * with `Authorization: Bearer $CRON_SECRET`.+ *+ * Source taxonomy: emits with `payload.source = 'pumpfun.<event>'` so the+ * reputation reads `payload.source like 'pumpkit.%'` continue to recognise+ * pumpkit-sourced events; we extend the read query in solana-reputation.js+ * to also count `pumpfun.%`.+ */++import { sql } from '../_lib/db.js';+import { cors, error, json, wrap } from '../_lib/http.js';+import { mintAttestation, deriveEventId, loadAttesterKeypair } from '../_lib/attest-event.js';++const MAX_PER_RUN = 50;+const WHALE_TRADE_USD_FLOOR = 1_000;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;++ const auth = req.headers['authorization'] || '';+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;+ const fromCron = req.headers['x-vercel-cron'] === '1';+ if (!fromCron && expected && auth !== expected) {+ return error(res, 401, 'unauthorized', 'cron secret required');+ }++ if (!process.env.ATTEST_AGENT_SECRET_KEY) {+ return error(res, 503, 'not_configured', 'ATTEST_AGENT_SECRET_KEY unset');+ }++ // Pull the latest stats joined with the agent's Metaplex Core asset and+ // the prior cursor state. Only consider mints whose stats have changed+ // since the last cursor checkpoint.+ const rows = await sql`+ select+ m.id as mint_id,+ m.mint as token_mint,+ m.network,+ m.agent_id,+ m.agent_authority,+ s.graduated,+ s.last_signature,+ s.last_signature_at,+ a.id as agent_row_id,+ a.user_id,+ coalesce(a.meta->'onchain'->>'sol_asset', a.meta->>'sol_mint_address') as agent_asset,+ c.last_graduated,+ c.last_authority,+ c.last_trade_signature+ from pump_agent_mints m+ join pump_agent_stats s on s.mint_id = m.id+ join agent_identities a on a.id = m.agent_id+ left join pumpfun_monitor_cursor c on c.mint_id = m.id+ where coalesce(a.meta->'onchain'->>'sol_asset', a.meta->>'sol_mint_address') is not null+ and (+ c.mint_id is null+ or c.last_graduated is distinct from s.graduated+ or c.last_authority is distinct from m.agent_authority+ or c.last_trade_signature is distinct from s.last_signature+ )+ order by s.refreshed_at desc nulls last+ limit ${MAX_PER_RUN}+ `;++ const attester = loadAttesterKeypair();+ const report = { scanned: rows.length, minted: 0, deduped: 0, in_progress: 0, errors: 0, events: [] };++ for (const r of rows) {+ const events = detectEvents(r);+ for (const ev of events) {+ try {+ const result = await mintAttestation({+ ...ev,+ agent_asset: r.agent_asset,+ network: r.network,+ token_mint: r.token_mint,+ attester,+ });+ report[result.status === 'minted' ? 'minted'+ : result.status === 'deduped' ? 'deduped' : 'in_progress']++;+ report.events.push({+ mint: r.token_mint, type: ev.event_type, status: result.status,+ signature: result.signature,+ });+ } catch (e) {+ report.errors++;+ report.events.push({+ mint: r.token_mint, type: ev.event_type,+ status: 'error', error: e?.message || String(e),+ });+ }+ }++ // Always update the cursor — even when nothing was emitted — so we+ // don't re-scan unchanged rows next tick.+ await sql`+ insert into pumpfun_monitor_cursor (mint_id, last_graduated, last_authority, last_trade_signature, last_processed_at)+ values (${r.mint_id}, ${r.graduated}, ${r.agent_authority}, ${r.last_signature}, now())+ on conflict (mint_id) do update set+ last_graduated = excluded.last_graduated,+ last_authority = excluded.last_authority,+ last_trade_signature = excluded.last_trade_signature,+ last_processed_at = now()+ `;+ }++ return json(res, 200, report);+});++/** Map a single (stats, cursor) row to the attestation events to emit. */+function detectEvents(r) {+ const out = [];+ const slot_or_ts = r.last_signature_at+ ? new Date(r.last_signature_at).getTime()+ : Date.now();++ // Graduation flip false -> true.+ if (r.graduated === true && r.last_graduated !== true) {+ out.push({+ event_type: 'graduation',+ source: 'pumpfun.graduation',+ event_id: deriveEventId({ event_type: 'graduation', mint: r.token_mint, slot_or_ts: 'final' }),+ task_id: `pumpfun:${r.token_mint}:graduation`,+ detail: { network: r.network },+ });+ }++ // CTO: agent_authority changed (creator takeover).+ if (r.agent_authority && r.last_authority && r.agent_authority !== r.last_authority) {+ out.push({+ event_type: 'cto_detected',+ source: 'pumpfun.cto',+ event_id: deriveEventId({+ event_type: 'cto',+ mint: r.token_mint,+ slot_or_ts: `${r.last_authority}->${r.agent_authority}`,+ }),+ task_id: `pumpfun:${r.token_mint}:cto:${slot_or_ts}`,+ detail: { from: r.last_authority, to: r.agent_authority, network: r.network },+ });+ }++ return out;+}++// Exported for tests.+export { detectEvents, WHALE_TRADE_USD_FLOOR };diff --git a/api/openapi-json.js b/api/openapi-json.jsindex 513281ef2..e2a2732bb 100644--- a/api/openapi-json.js+++ b/api/openapi-json.js@@ -88,25 +88,12 @@ export default wrap(async (req, res) => {currency: 'USD',amount: '0.001',},+ // Per spec, protocols lists protocol *support* (one entry per+ // protocol). Per-network payment lanes are advertised at runtime+ // in the 402 challenge `accepts[]` array — see api/_lib/x402-spec.js+ // `paymentRequirements()` which emits Solana USDC + Base USDC.protocols: [- {- x402: {- network: 'solana',- asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',- payTo: 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN',- scheme: 'exact',- maxAmountRequired: '1000',- },- },- {- x402: {- network: 'base',- asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',- payTo: '0x0C70c0e8453C5667739E41acdF6eC5787B8ff542',- scheme: 'exact',- maxAmountRequired: '1000',- },- },+ { x402: {} },{mpp: {method: 'solana-pay',diff --git a/public/agent-passport.html b/public/agent-passport.htmlindex 044b01a9b..61ab88312 100644--- a/public/agent-passport.html+++ b/public/agent-passport.html@@ -971,7 +971,7 @@if (row.verified) flags.push(pill('verified', 'ok'));if (row.disputed) flags.push(pill('disputed', 'warn'));if (row.revoked) flags.push(pill('revoked', 'bad'));- if (row.payload?.source?.startsWith?.('pumpkit.'))+ if (isEventSource(row.payload?.source))flags.push(pill(row.payload.source, 'info'));const fresh = cache.freshSigs.has(row.signature) ? ' fresh' : '';return `@@ -992,11 +992,15 @@.join('');}+ function isEventSource(s) {+ return typeof s === 'string' && (s.startsWith('pumpkit.') || s.startsWith('pumpfun.'));+ }+function filterRows(rows, filter) {if (filter === 'all') return rows;if (filter === 'disputed') return rows.filter((r) => r.disputed || r.revoked);if (filter === 'event')- return rows.filter((r) => r.payload?.source?.startsWith?.('pumpkit.'));+ return rows.filter((r) => isEventSource(r.payload?.source));return rows.filter((r) => r.kind?.includes(`.${filter}.`));}diff --git a/public/dashboard/agent-pumpfun.html b/public/dashboard/agent-pumpfun.htmlindex 3ac89e44b..b3afda334 100644--- a/public/dashboard/agent-pumpfun.html+++ b/public/dashboard/agent-pumpfun.html@@ -355,16 +355,20 @@>Register a name on sns.id</a></div>- <div id="sns-registrar" class="row" style="margin-top: 14px; align-items: flex-end" hidden>+ <div id="sns-registrar" style="margin-top: 14px"><div class="field">- <label for="sns-register-label">Claim a free subdomain</label>- <div class="row" style="gap: 6px">+ <label for="sns-register-label">Register a .sol domain</label>+ <div class="row" style="gap: 6px; align-items: center"><input id="sns-register-label" placeholder="myagent" maxlength="63" />- <span id="sns-register-suffix" class="muted" style="font-family: ui-monospace, Menlo, monospace; font-size: 13px"></span>+ <span class="muted" style="font-family: ui-monospace, Menlo, monospace; font-size: 13px">.sol</span></div>+ <p class="muted" style="margin: 6px 0 0; font-size: 12px">+ Bonfida pricing (1y): 1 char $750 · 2 $700 · 3 $640 · 4 $160 · 5+ $20. Paid in USDC.+ </p></div>- <div style="flex: 0 0 auto">- <button class="btn" id="sns-register-btn">Claim</button>+ <div class="row" style="margin-top: 10px; gap: 8px; flex-wrap: wrap">+ <button class="btn" id="sns-register-agent-btn">Pay with agent wallet</button>+ <button class="btn ghost" id="sns-register-user-btn">Pay with my wallet</button></div></div></section>@@ -549,8 +553,8 @@snsRegisterLink: $('#sns-register-link'),snsRegistrar: $('#sns-registrar'),snsRegisterLabel: $('#sns-register-label'),- snsRegisterSuffix: $('#sns-register-suffix'),- snsRegisterBtn: $('#sns-register-btn'),+ snsRegisterAgentBtn: $('#sns-register-agent-btn'),+ snsRegisterUserBtn: $('#sns-register-user-btn'),launchName: $('#launch-name'),launchSymbol: $('#launch-symbol'),launchVanity: $('#launch-vanity'),@@ -754,14 +758,9 @@if (!id) return;els.snsCurrent.textContent = '…';els.snsDomainList.innerHTML = '';- els.snsRegistrar.hidden = true;try {const { data } = await api(`/api/agents/${id}/sns`);renderSnsList(data);- if (data.registrar?.enabled) {- els.snsRegistrar.hidden = false;- els.snsRegisterSuffix.textContent = `.${data.registrar.parent}.sol`;- }} catch (err) {els.snsCurrent.textContent =err.body?.error === 'conflict'@@ -772,29 +771,102 @@}}- async function registerSns() {+ function readRegisterLabel() {+ const v = els.snsRegisterLabel.value.trim().toLowerCase().replace(/\.sol$/, '');+ if (!/^[a-z0-9-]{1,63}$/.test(v)) {+ toast('Domain must be a–z, 0–9, or hyphen (max 63 chars)', 'err');+ return null;+ }+ return v;+ }++ async function registerWithAgent() {const id = currentAgentId();if (!id) return;- const label = els.snsRegisterLabel.value.trim().toLowerCase();- if (!/^[a-z0-9-]{1,63}$/.test(label)) {- toast('Label must be a–z, 0–9, or hyphen (max 63 chars)', 'err');- return;- }- els.snsRegisterBtn.disabled = true;- els.snsRegisterBtn.textContent = 'Claiming…';+ const domain = readRegisterLabel();+ if (!domain) return;+ if (!confirm(`Register ${domain}.sol using the agent's wallet? The agent's USDC balance will be charged.`)) return;+ const btn = els.snsRegisterAgentBtn;+ btn.disabled = true;+ btn.textContent = 'Registering…';try {const { data } = await api(`/api/agents/${id}/sns/register`, {method: 'POST',- body: JSON.stringify({ label }),+ body: JSON.stringify({ domain }),});toast(`Registered ${data.sns_domain}.sol`);els.snsRegisterLabel.value = '';await refreshSns();} catch (err) {- toast(err.message, 'err');+ toast(err.body?.error_description || err.message, 'err');+ } finally {+ btn.disabled = false;+ btn.textContent = 'Pay with agent wallet';+ }+ }++ async function getConnectedSolanaWallet() {+ // Phantom / Solflare standard: window.solana with isPhantom or window.solflare.+ const provider = window.phantom?.solana || window.solana || window.solflare;+ if (!provider) {+ throw new Error('No Solana wallet found. Install Phantom or Solflare.');+ }+ if (!provider.isConnected) await provider.connect();+ const pubkey = provider.publicKey?.toString();+ if (!pubkey) throw new Error('Wallet did not return a public key');+ return { provider, pubkey };+ }++ async function registerWithUserWallet() {+ const id = currentAgentId();+ if (!id) return;+ const domain = readRegisterLabel();+ if (!domain) return;++ const btn = els.snsRegisterUserBtn;+ btn.disabled = true;+ btn.textContent = 'Connecting…';+ try {+ const { provider, pubkey } = await getConnectedSolanaWallet();+ btn.textContent = 'Building tx…';+ const { data: prep } = await api(`/api/agents/${id}/sns/register-prep`, {+ method: 'POST',+ body: JSON.stringify({ domain, wallet_address: pubkey }),+ });++ const { VersionedTransaction } = await import('https://esm.sh/@solana/[email protected]');+ const tx = VersionedTransaction.deserialize(+ Uint8Array.from(atob(prep.tx_base64), (c) => c.charCodeAt(0)),+ );++ btn.textContent = 'Awaiting signature…';+ const { signature } = await provider.signAndSendTransaction(tx);++ btn.textContent = 'Confirming…';+ // Poll the confirm endpoint a few times — the RPC needs a beat to index.+ let lastErr;+ for (let i = 0; i < 12; i++) {+ try {+ const { data } = await api(`/api/agents/${id}/sns/register-confirm`, {+ method: 'POST',+ body: JSON.stringify({ domain, signature, wallet_address: pubkey }),+ });+ toast(`Registered ${data.sns_domain}.sol`);+ els.snsRegisterLabel.value = '';+ await refreshSns();+ return;+ } catch (err) {+ lastErr = err;+ if (err.body?.error !== 'not_confirmed') throw err;+ await new Promise((r) => setTimeout(r, 2500));+ }+ }+ throw lastErr || new Error('confirmation timed out');+ } catch (err) {+ toast(err.body?.error_description || err.message, 'err');} finally {- els.snsRegisterBtn.disabled = false;- els.snsRegisterBtn.textContent = 'Claim';+ btn.disabled = false;+ btn.textContent = 'Pay with my wallet';}}@@ -1038,7 +1110,8 @@els.provisionBtn.addEventListener('click', provision);els.snsRefreshBtn.addEventListener('click', refreshSns);els.snsClearBtn.addEventListener('click', clearSns);- els.snsRegisterBtn.addEventListener('click', registerSns);+ els.snsRegisterAgentBtn.addEventListener('click', registerWithAgent);+ els.snsRegisterUserBtn.addEventListener('click', registerWithUserWallet);els.launchBtn.addEventListener('click', launchToken);els.buyBtn.addEventListener('click', buy);els.sellBtn.addEventListener('click', sell);diff --git a/public/strategy-lab.html b/public/strategy-lab.htmlindex 1aa48fabc..b15eca751 100644--- a/public/strategy-lab.html+++ b/public/strategy-lab.html@@ -464,6 +464,29 @@renderPortfolio(r?.data);}$('refreshPortfolio').onclick = refreshPortfolio;+ $('closeAll').onclick = async () => {+ const id = agentSel.value;+ if (!id) { setStatus('Select an agent first.', 'bad'); return; }+ const net = netSel.value;+ if (!confirm(`STOP all activity and SELL every position on ${net}?\n\nThis aborts any running strategy and sells 100% of every SPL holding the wallet owns.`)) return;+ // Abort any running stream first.+ activeRun?.abort();+ pushLog('error', '■ STOP — closing all positions');+ setStatus('Selling all positions…', 'warn');+ const r = await fetch('/api/pump/strategy-close-all', {+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agentId: id, network: net }),+ }).then((r) => r.json()).catch((e) => ({ error: e.message }));+ if (r.error) { setStatus('Close-all failed: ' + (r.error_description || r.error), 'bad'); return; }+ (r.data?.log || []).forEach((e) => {+ if (e.action === 'sold') pushLog('exit', `× sold ${e.mint} → ${e.sig?.slice(0, 12) ?? ''}…`);+ else if (e.action === 'sell-error') pushLog('error', `! sell-error ${e.mint}: ${e.error}`);+ else pushLog('skip', `${e.action} ${e.mint}`);+ });+ pushLog('done', `✓ closed ${r.data.sold}/${r.data.total} (${r.data.errors} errors)`);+ setStatus(`Closed ${r.data.sold}/${r.data.total}` + (r.data.errors ? ` — ${r.data.errors} errors` : ''), r.data.errors ? 'warn' : 'ok');+ refreshPortfolio();+ };function renderPortfolio(d) {const el = $('portfolio');diff --git a/tests/api/pump-fun-strategy-policy.test.js b/tests/api/pump-fun-strategy-policy.test.jsnew file mode 100644index 000000000..7158b9cda--- /dev/null+++ b/tests/api/pump-fun-strategy-policy.test.js@@ -0,0 +1,166 @@+import { describe, it, expect } from 'vitest';+import {+ runStrategy,+ closeAllPositions,+} from '../../examples/skills/pump-fun-strategy/handlers.js';++function passingMintCtx() {+ const t0 = Date.now();+ return {+ skills: {+ invoke: async (tool, args) => {+ if (tool === 'pump-fun.getNewTokens') return { ok: true, data: { tokens: [{ mint: 'GoodMint' }] } };+ if (tool === 'pump-fun.getTokenDetails') return { ok: true, data: { creator: 'C', createdAt: new Date(t0).toISOString() } };+ if (tool === 'pump-fun.getTokenHolders') return { ok: true, data: { total: 200, holders: [{ pct: 8 }] } };+ if (tool === 'pump-fun.getCreatorProfile') return { ok: true, data: { rugCount: 0 } };+ if (tool === 'pump-fun.getBondingCurve') return { ok: true, data: { priceSol: 0.001 } };+ if (tool === 'pump-fun-trade.buyToken') return { ok: true, data: { sig: 'REAL_SIG_' + args.mint } };+ return { ok: true, data: {} };+ },+ },+ skillConfig: { defaultPollMs: 50 },+ memory: { note: () => {} },+ };+}++describe('runStrategy policyGuard', () => {+ const baseStrategy = {+ scan: { kind: 'newTokens', limit: 5 },+ filters: ['holders.total > 50'],+ entry: { side: 'buy', amountSol: 0.05 },+ caps: { sessionSpendCapSol: 0.5, perTradeSol: 0.05, maxOpenPositions: 5 },+ };++ it('blocks buys when policyGuard returns a reason; emits policy-block', async () => {+ const events = [];+ const r = await runStrategy({+ strategy: baseStrategy,+ durationSec: 1,+ simulate: false, // live path+ onLog: (e) => events.push(e),+ policyGuard: async () => ({ code: 'daily_cap_exceeded', msg: 'cap is 0.1, would spend 0.6' }),+ }, passingMintCtx());+ expect(r.ok).toBe(true);+ const blocks = events.filter((e) => e.action === 'policy-block');+ expect(blocks.length).toBeGreaterThanOrEqual(1);+ expect(blocks[0].code).toBe('daily_cap_exceeded');+ // No actual enters should have happened.+ expect(events.find((e) => e.action === 'enter')).toBeUndefined();+ }, 5000);++ it('skips policy check entirely in simulate mode', async () => {+ const events = [];+ let guardCalled = 0;+ const r = await runStrategy({+ strategy: baseStrategy,+ durationSec: 1,+ simulate: true,+ onLog: (e) => events.push(e),+ policyGuard: async () => { guardCalled++; return { code: 'x', msg: 'should not fire' }; },+ }, passingMintCtx());+ expect(r.ok).toBe(true);+ expect(guardCalled).toBe(0);+ expect(events.some((e) => e.action === 'enter')).toBe(true);+ }, 5000);++ it('respects abortSignal between iterations', async () => {+ const ctrl = new AbortController();+ const events = [];+ const start = Date.now();+ setTimeout(() => ctrl.abort(), 120);+ const r = await runStrategy({+ strategy: baseStrategy,+ durationSec: 5, // would normally run 5s+ simulate: true,+ onLog: (e) => events.push(e),+ abortSignal: ctrl.signal,+ }, passingMintCtx());+ const elapsed = Date.now() - start;+ expect(r.ok).toBe(true);+ expect(elapsed).toBeLessThan(2000); // aborted well before deadline+ expect(events.some((e) => e.action === 'aborted')).toBe(true);+ }, 6000);+});++describe('closeAllPositions', () => {+ it('sells every SPL holding from solana-wallet.getSplBalances', async () => {+ const sells = [];+ const ctx = {+ wallet: { publicKey: { toBase58: () => 'WALLET' } },+ skills: {+ invoke: async (tool, args) => {+ if (tool === 'solana-wallet.getSplBalances') {+ return { ok: true, data: { balances: [+ { mint: 'M1', amount: 100, decimals: 6 },+ { mint: 'M2', amount: 5, decimals: 9 },+ { mint: 'M3', amount: 0, decimals: 6 }, // filtered+ ] } };+ }+ if (tool === 'pump-fun-trade.sellToken') {+ sells.push(args);+ return { ok: true, data: { sig: 'SIG_' + args.mint } };+ }+ return { ok: true, data: {} };+ },+ },+ memory: { note: () => {} },+ };+ const r = await closeAllPositions({}, ctx);+ expect(r.ok).toBe(true);+ expect(r.data.sold).toBe(2);+ expect(r.data.errors).toBe(0);+ expect(sells.map((s) => s.mint).sort()).toEqual(['M1', 'M2']);+ expect(sells.every((s) => s.percent === 100)).toBe(true);+ });++ it('honours an explicit mints list and skips wallet enumeration', async () => {+ let enumCalled = 0;+ const ctx = {+ wallet: { publicKey: { toBase58: () => 'W' } },+ skills: {+ invoke: async (tool) => {+ if (tool === 'solana-wallet.getSplBalances') { enumCalled++; return { ok: true, data: { balances: [] } }; }+ if (tool === 'pump-fun-trade.sellToken') return { ok: true, data: { sig: 'X' } };+ return { ok: true, data: {} };+ },+ },+ memory: { note: () => {} },+ };+ const r = await closeAllPositions({ mints: ['Ma', 'Mb'] }, ctx);+ expect(r.ok).toBe(true);+ expect(r.data.total).toBe(2);+ expect(enumCalled).toBe(0);+ });++ it('reports per-mint errors without aborting the rest', async () => {+ const ctx = {+ wallet: { publicKey: { toBase58: () => 'W' } },+ skills: {+ invoke: async (tool, args) => {+ if (tool === 'pump-fun-trade.sellToken') {+ if (args.mint === 'BAD') return { ok: false, error: 'rpc 503' };+ return { ok: true, data: { sig: 'OK' } };+ }+ return { ok: true, data: {} };+ },+ },+ memory: { note: () => {} },+ };+ const r = await closeAllPositions({ mints: ['BAD', 'OK1', 'OK2'] }, ctx);+ expect(r.data.total).toBe(3);+ expect(r.data.sold).toBe(2);+ expect(r.data.errors).toBe(1);+ expect(r.data.log.find((l) => l.mint === 'BAD').error).toMatch(/rpc/);+ });++ it('simulate:true skips signing but reports targets', async () => {+ const ctx = {+ skills: { invoke: async () => ({ ok: true, data: {} }) },+ memory: { note: () => {} },+ };+ const r = await closeAllPositions({ mints: ['M1', 'M2'], simulate: true }, ctx);+ expect(r.ok).toBe(true);+ expect(r.data.sold).toBe(2);+ expect(r.data.simulate).toBe(true);+ });+});diff --git a/tests/api/pumpfun-monitor.test.js b/tests/api/pumpfun-monitor.test.jsnew file mode 100644index 000000000..c3180f844--- /dev/null+++ b/tests/api/pumpfun-monitor.test.js@@ -0,0 +1,92 @@+import { describe, it, expect } from 'vitest';++import { detectEvents } from '../../api/cron/pumpfun-monitor.js';+import { deriveEventId } from '../../api/_lib/attest-event.js';++const baseRow = {+ mint_id: 'mint-uuid',+ token_mint: 'TokenMintPubkey22222222222222222222222222222',+ network: 'devnet',+ agent_id: 'agent-uuid',+ agent_authority: 'AuthorityKey1111111111111111111111111111111',+ graduated: false,+ last_signature: 'sig1',+ last_signature_at: '2026-04-29T10:00:00Z',+ agent_row_id: 'agent-uuid',+ user_id: 'user-uuid',+ agent_asset: 'AgentAssetPubkey1111111111111111111111111111',+ last_graduated: null,+ last_authority: null,+ last_trade_signature: null,+};++describe('detectEvents', () => {+ it('emits nothing on first sight (no cursor) when nothing has flipped', () => {+ expect(detectEvents({ ...baseRow })).toEqual([]);+ });++ it('emits a graduation event on false -> true flip', () => {+ const events = detectEvents({ ...baseRow, graduated: true, last_graduated: false });+ expect(events).toHaveLength(1);+ expect(events[0]).toMatchObject({+ event_type: 'graduation',+ source: 'pumpfun.graduation',+ task_id: `pumpfun:${baseRow.token_mint}:graduation`,+ });+ expect(events[0].event_id).toMatch(/^[0-9a-f]{32}$/);+ });++ it('does not re-emit graduation when already graduated', () => {+ const events = detectEvents({ ...baseRow, graduated: true, last_graduated: true });+ expect(events).toEqual([]);+ });++ it('emits a CTO event when authority changes', () => {+ const events = detectEvents({+ ...baseRow,+ agent_authority: 'NewAuthority999999999999999999999999999999',+ last_authority: baseRow.agent_authority,+ });+ expect(events).toHaveLength(1);+ expect(events[0]).toMatchObject({+ event_type: 'cto_detected',+ source: 'pumpfun.cto',+ });+ expect(events[0].detail.from).toBe(baseRow.agent_authority);+ expect(events[0].detail.to).toBe('NewAuthority999999999999999999999999999999');+ });++ it('does not emit CTO when authority is unchanged', () => {+ const events = detectEvents({ ...baseRow, last_authority: baseRow.agent_authority });+ expect(events).toEqual([]);+ });++ it('emits both graduation and CTO when both flip in the same tick', () => {+ const events = detectEvents({+ ...baseRow,+ graduated: true, last_graduated: false,+ agent_authority: 'NewAuthority999999999999999999999999999999',+ last_authority: baseRow.agent_authority,+ });+ expect(events.map((e) => e.event_type).sort()).toEqual(['cto_detected', 'graduation']);+ });++ it('produces stable event ids (idempotent across runs)', () => {+ const a = detectEvents({ ...baseRow, graduated: true, last_graduated: false })[0];+ const b = detectEvents({ ...baseRow, graduated: true, last_graduated: false })[0];+ expect(a.event_id).toBe(b.event_id);+ });+});++describe('deriveEventId', () => {+ it('hashes (event_type, mint, slot_or_ts) to 32 hex chars', () => {+ const id = deriveEventId({ event_type: 'graduation', mint: 'M', slot_or_ts: 'final' });+ expect(id).toMatch(/^[0-9a-f]{32}$/);+ });++ it('differs across event types', () => {+ const a = deriveEventId({ event_type: 'graduation', mint: 'M', slot_or_ts: 'x' });+ const b = deriveEventId({ event_type: 'cto', mint: 'M', slot_or_ts: 'x' });+ expect(a).not.toBe(b);+ });+});diff --git a/vercel.json b/vercel.jsonindex dc7f3933f..532618e0a 100644--- a/vercel.json+++ b/vercel.json@@ -267,6 +267,7 @@{ "path": "/api/cron/run-subscriptions", "schedule": "0 * * * *" },{ "path": "/api/cron/pumpfun-signals", "schedule": "*/15 * * * *" },{ "path": "/api/cron/pump-agent-stats", "schedule": "*/10 * * * *" },+ { "path": "/api/cron/pumpfun-monitor", "schedule": "*/3 * * * *" },{ "path": "/api/cron/solana-attest-event-cleanup", "schedule": "*/10 * * * *" }]}