Skip to content

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.

pump alert system (eval/runner/delivery/rules API), agent passport + on-chain card, ERC-8004 registration, strategy lab DSL, agent-invocation Anchor contract

nirholas7f5619e2e623
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c88434db5..61fdc6529 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,9 +6,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-15
+- **After you launch a coin, jump straight to viewing or managing it** — The success screen you see right after launching a coin no longer dead-ends. Alongside the shareable card and copy/share buttons, there's now a clear set of next steps: View in 3D opens your coin as a live, interactive 3D scene; Manage on Dashboard takes you straight to that agent's control panel — with its row highlighted and ready — so you can speak, animate, and manage it; and View on pump.fun opens the coin on pump.fun. Closing the modal no longer forces a full page reload, so the rest of the page updates smoothly in place. (`/pump-dashboard`) `[improvement]`
- **Autonomous coin buybacks and creator-fee distributions now run on schedule** — Coins launched through three.ws with autopilot enabled now have their buybacks and creator-fee distributions executed automatically on an hourly schedule, instead of waiting for a manual trigger. A new balance watchdog checks every Solana signer the platform uses to pay on-chain fees and alerts the team the moment one runs low, so autopilot never silently stalls for lack of gas. No action needed from coin owners — it just works in the background. `[improvement, infra]`
- **Launchpad Studio: pick your avatar from your own agents and the gallery** — Building a launchpad in Launchpad Studio (three.ws/launchpad) no longer means hunting down a model URL by hand. The avatar picker now shows three sections: your own three.ws agents (when you're signed in), the platform avatar gallery with a Show more button to browse deeper, and a collapsed Or enter a URL field for power users who want to paste a custom .glb. Thumbnails load lazily, the selected avatar updates the live 3D preview instantly, and your choice is saved with the published page. (`/launchpad`) `[feature, improvement]`
- **Pump Visualizer’s Trending view fixed — spheres now sized by real market cap** — The Trending mode of the 3D Pump Visualizer (three.ws/pump-visualizer) now renders correctly: every coin appears as a sphere sized by its real USD market cap, textured with its actual logo, with a full detail panel showing market cap, all-time-high, replies, age, and socials. Previously Trending failed to load because the market data it relied on wasn’t reaching the scene. Click a sphere to inspect it, or double-click to open the full 3D coin page. The live Firehose and Migrations modes are unchanged. (`/pump-visualizer`) `[fix, improvement]`
+- **Rate and vouch for Solana agents from their passport** — Every Solana agent passport already showed its on-chain reputation — now you can add to it. A new "Rate this agent" panel lets anyone with a Solana wallet (Phantom or Solflare) leave a 1–5 score, with an optional public note, written on-chain as a signed attestation — no account needed. You can also back your rating with a SOL stake (from 0.001 SOL) sent to the agent's owner for an economically-weighted vouch. Submitting is guarded the obvious ways: you can't rate your own agent, scores are limited to 1–5, the minimum stake is enforced, and re-rating asks you to confirm before it updates your previous score. The moment your transaction confirms, the passport re-reads the chain on demand instead of waiting for the next indexing pass, so your rating shows up in the reputation summary within seconds. (`/agent-passport.html`) `[feature]`
+- **Register an existing agent on-chain in one click** — Any agent you already built can now be given an ERC-8004 on-chain identity straight from its profile — no re-entering its name, 3D model, voice, or skills. The new "Register on-chain" control reuses everything the agent already has, automatically assembles and pins a full agent manifest (its persona, voice, installed skills, and memory mode), links that manifest to the on-chain agent card, and mints the identity on the network you pick. Re-running it on the same network is a safe no-op, and your profile shows a live on-chain badge with explorer and agent-card links the moment it's done. (`/agents`) `[feature]`
+- **The pump.fun graduations feed stays fresh around the clock** — The recent-graduations feed and the graduation data behind pump.fun signals and MCP tools now refresh continuously in the background, instead of only updating while someone had the live feed open. A new scheduled job listens to the real pump.fun migration stream and records graduations as they happen, so the feed shows up-to-date tokens even after quiet periods. Graduation data is also served straight from our own live records, so it never silently falls back to an empty list. `[infra, improvement]`
- **three.ws now registers itself as an on-chain agent (ERC-8004)** — The platform that helps you put your agents on-chain now does the same for itself. three.ws publishes a 3D Agent Card — a verifiable manifest of its name, its default 3D avatar, and its A2A/MCP/x402 service endpoints — at three.ws/.well-known/3d-agent-card.json, and ships a one-command tool that mints the platform agent in the canonical ERC-8004 IdentityRegistry on Base (with a Base Sepolia rehearsal first). The card cryptographically commits to the avatar: the SHA-256 in the card matches the exact GLB bytes served, so any indexer or wallet can independently verify the model hasn't been swapped. Other agents and directories can now discover and trust three.ws the same way three.ws lets them be discovered. `[feature, infra]`
## 2026-06-14
diff --git a/agent-protocol-sdk/src/idl.ts b/agent-protocol-sdk/src/idl.ts
index f4feda591..ba1feddb5 100644
--- a/agent-protocol-sdk/src/idl.ts
+++ b/agent-protocol-sdk/src/idl.ts
@@ -8,7 +8,7 @@
import type { Idl } from '@coral-xyz/anchor';
-export const AGENT_INVOCATION_PROGRAM_ID = 'CcdC7xDhQ9r2PoafbsfWVewcbuAYozECHJEXWe4ELnqR';
+export const AGENT_INVOCATION_PROGRAM_ID = 'AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo';
export const IDL = {
address: AGENT_INVOCATION_PROGRAM_ID,
diff --git a/api/_lib/alert-delivery.js b/api/_lib/alert-delivery.js
new file mode 100644
index 000000000..1c37d8d2a
--- /dev/null
+++ b/api/_lib/alert-delivery.js
@@ -0,0 +1,162 @@
+// @ts-check
+// Multi-channel delivery for pump dashboard alerts (Task 04).
+//
+// Three independent channels — in-app notification, signed webhook, Telegram —
+// each wrapped so one channel's failure never blocks the others. Every call
+// returns a per-channel result the runner persists to pump_alert_deliveries so
+// the dashboard can surface "webhook failed" instead of silently dropping it.
+//
+// Webhooks are signed with the rule's per-rule secret using the Standard
+// Webhooks format (matching api/_lib/webhook-dispatch.js) and pinned to a
+// validated public address (SSRF guard). Telegram uses the platform bot and
+// no-ops cleanly when TELEGRAM_BOT_TOKEN is absent.
+
+import { sql } from './db.js';
+import { hmacSha256, randomToken } from './crypto.js';
+import { validatePublicUrl, resolvePublicHost, pinnedAgent, SsrfError } from './ssrf.js';
+import { formatAlertSummary } from './pump-alert-eval.js';
+
+const WEBHOOK_TIMEOUT_MS = 8_000;
+const TELEGRAM_TIMEOUT_MS = 5_000;
+
+/** @typedef {{ attempted: boolean, ok: boolean, detail: string|null }} ChannelResult */
+
+const skipped = () => /** @type {ChannelResult} */ ({ attempted: false, ok: false, detail: null });
+
+/**
+ * Deliver one alert across every channel the rule has configured. Channels run
+ * concurrently and are fully isolated.
+ *
+ * @param {import('./pump-alert-eval.js').AlertRule} rule
+ * @param {Record<string, any>} payload alert payload (also stored in-app)
+ * @returns {Promise<{ in_app: ChannelResult, webhook: ChannelResult, telegram: ChannelResult }>}
+ */
+export async function deliverAlert(rule, payload) {
+ const [inApp, webhook, telegram] = await Promise.all([
+ rule.deliver_in_app ? deliverInApp(rule, payload) : skipped(),
+ rule.webhook_url ? deliverWebhook(rule, payload) : skipped(),
+ rule.telegram_chat ? deliverTelegram(rule, payload) : skipped(),
+ ]);
+ return { in_app: inApp, webhook, telegram };
+}
+
+/** Insert the in-app notification row (type 'pump_alert'). */
+async function deliverInApp(rule, payload) {
+ try {
+ await sql`
+ insert into user_notifications (user_id, type, payload)
+ values (${rule.user_id}, 'pump_alert', ${JSON.stringify(payload)}::jsonb)
+ `;
+ return { attempted: true, ok: true, detail: null };
+ } catch (e) {
+ return { attempted: true, ok: false, detail: errMsg(e) };
+ }
+}
+
+/**
+ * POST a signed event to the rule's webhook. Redirects are not followed and the
+ * connection is pinned to the resolved public address so a webhook can't be
+ * used as an SSRF oracle. Returns ok only on a 2xx.
+ */
+async function deliverWebhook(rule, payload) {
+ const eventId = `evt_${randomToken(16)}`;
+ const timestamp = Math.floor(Date.now() / 1000);
+ const body = JSON.stringify({
+ id: eventId,
+ type: 'pump.alert',
+ created_at: new Date(timestamp * 1000).toISOString(),
+ data: payload,
+ });
+
+ let target;
+ let agent;
+ try {
+ target = validatePublicUrl(rule.webhook_url);
+ const addrs = await resolvePublicHost(target.hostname);
+ agent = pinnedAgent(target.hostname, addrs);
+ } catch (e) {
+ const reason = e instanceof SsrfError ? `blocked_url:${e.code}` : 'invalid_url';
+ return { attempted: true, ok: false, detail: reason };
+ }
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), WEBHOOK_TIMEOUT_MS);
+ try {
+ const headers = {
+ 'content-type': 'application/json',
+ 'webhook-id': eventId,
+ 'webhook-timestamp': String(timestamp),
+ 'user-agent': 'three.ws-pump-alerts/1.0',
+ };
+ if (rule.webhook_secret) {
+ const sig = await hmacSha256(rule.webhook_secret, `${eventId}.${timestamp}.${body}`);
+ headers['webhook-signature'] = `v1,${sig}`;
+ }
+ const res = await fetch(target, {
+ method: 'POST',
+ redirect: 'manual',
+ // @ts-ignore — undici dispatcher option, pins the resolved address.
+ dispatcher: agent,
+ headers,
+ body,
+ signal: controller.signal,
+ });
+ if (res.status >= 300 && res.status < 400) {
+ return { attempted: true, ok: false, detail: `redirect_not_followed:${res.status}` };
+ }
+ return { attempted: true, ok: res.ok, detail: res.ok ? null : `http_${res.status}` };
+ } catch (e) {
+ return { attempted: true, ok: false, detail: errMsg(e) };
+ } finally {
+ clearTimeout(timer);
+ await agent.close().catch(() => {});
+ }
+}
+
+/**
+ * Send the alert to the user's Telegram chat via the platform bot. No-ops
+ * cleanly (attempted=false) when the bot token is unset so dev/test never fail.
+ */
+async function deliverTelegram(rule, payload) {
+ const token = process.env.TELEGRAM_BOT_TOKEN;
+ if (!token) return { attempted: false, ok: false, detail: 'no_bot_token' };
+
+ const text = telegramText(payload);
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), TELEGRAM_TIMEOUT_MS);
+ try {
+ const res = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ chat_id: rule.telegram_chat,
+ text,
+ disable_web_page_preview: true,
+ }),
+ signal: controller.signal,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok || data?.ok === false) {
+ return { attempted: true, ok: false, detail: data?.description || `http_${res.status}` };
+ }
+ return { attempted: true, ok: true, detail: null };
+ } catch (e) {
+ return { attempted: true, ok: false, detail: errMsg(e) };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/** Plain-text Telegram body — no parse_mode, so user/token text can't inject markup. */
+function telegramText(payload) {
+ const lines = [formatAlertSummary(payload)];
+ if (payload.mint) {
+ lines.push(`Mint: ${payload.mint}`);
+ lines.push(`https://pump.fun/coin/${payload.mint}`);
+ }
+ return lines.join('\n').slice(0, 4000);
+}
+
+function errMsg(e) {
+ return (e && (e.message || String(e))) ? String(e.message || e).slice(0, 200) : 'error';
+}
diff --git a/api/_lib/migrations/2026-06-14-pump-trades-quote.sql b/api/_lib/migrations/2026-06-14-pump-trades-quote.sql
deleted file mode 100644
index 7f2ed87d1..000000000
--- a/api/_lib/migrations/2026-06-14-pump-trades-quote.sql
+++ /dev/null
@@ -1,34 +0,0 @@
--- Migration: record the quote (pairing) asset on every pump.fun trade.
--- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-06-14-pump-trades-quote.sql
--- Idempotent.
---
--- pump_agent_trades originally modelled SOL only: a `sol_amount` lamports column
--- and nothing recording which quote currency a trade settled in. pump.fun v2
--- coins can be USDC-paired (buy_v2/sell_v2 against a USDC curve), and our launch,
--- wallet-signed, and custodial trade paths all support that now. These columns
--- make the trade row self-describing for both quote assets:
--- quote_mint → the quote SPL mint (WSOL mint for SOL-paired, USDC mint for USDC).
--- quote_symbol → 'SOL' | 'USDC' | 'OTHER' — a stable display label.
--- quote_amount → atomic units of the quote asset spent (buy) / received (sell).
--- For SOL trades this equals sol_amount (lamports); for USDC it
--- is 6-decimal USDC atomics. New code reads quote_amount.
--- sol_amount is kept (not dropped) for backward compatibility.
-
-begin;
-
-alter table pump_agent_trades
- add column if not exists quote_mint text;
-alter table pump_agent_trades
- add column if not exists quote_symbol text;
-alter table pump_agent_trades
- add column if not exists quote_amount numeric(40, 0);
-
--- Backfill legacy rows: every pre-existing trade is SOL-paired, so the quote is
--- wrapped SOL and the quote amount is the lamports already stored in sol_amount.
-update pump_agent_trades
- set quote_mint = 'So11111111111111111111111111111111111111112',
- quote_symbol = 'SOL',
- quote_amount = sol_amount
- where quote_mint is null;
-
-commit;
diff --git a/api/_lib/migrations/20260615000000_erc8004_validation.sql b/api/_lib/migrations/20260615000000_erc8004_validation.sql
new file mode 100644
index 000000000..5f355d22b
--- /dev/null
+++ b/api/_lib/migrations/20260615000000_erc8004_validation.sql
@@ -0,0 +1,24 @@
+-- ERC-8004 ValidationRegistry attestation cache.
+--
+-- The authoritative record lives on-chain (ValidationRegistry.getLatestByKind);
+-- these columns mirror the latest glb-schema attestation so list views, the
+-- crawler, and ops dashboards can show a "Validated" badge and re-validation
+-- state without an RPC round-trip per row. The on-chain read path stays the
+-- source of truth for the profile badge.
+
+ALTER TABLE erc8004_agents_index
+ ADD COLUMN IF NOT EXISTS validation_passed boolean,
+ ADD COLUMN IF NOT EXISTS validation_kind text,
+ ADD COLUMN IF NOT EXISTS validation_proof_hash text,
+ ADD COLUMN IF NOT EXISTS validation_proof_uri text,
+ ADD COLUMN IF NOT EXISTS validation_tx text,
+ ADD COLUMN IF NOT EXISTS validator_address text,
+ ADD COLUMN IF NOT EXISTS validation_at timestamptz,
+ -- Last ops error code (e.g. validator_not_allowlisted) when an attestation
+ -- could not be recorded — visible to ops, never blocks registration.
+ ADD COLUMN IF NOT EXISTS validation_error text;
+
+-- Fast lookup of validated agents for directory filtering / badges.
+CREATE INDEX IF NOT EXISTS idx_erc8004_validation_passed
+ ON erc8004_agents_index (chain_id, agent_id)
+ WHERE validation_passed = true;
diff --git a/api/_lib/onchain.js b/api/_lib/onchain.js
index c57fe86cb..ad3ff961a 100644
--- a/api/_lib/onchain.js
+++ b/api/_lib/onchain.js
@@ -12,7 +12,13 @@
import { Contract, getAddress } from 'ethers';
import { evmFallbackProvider } from './evm/rpc.js';
-import { cacheGet, cacheSet } from './cache.js';
+import { cacheGet, cacheSet, cacheDel } from './cache.js';
+import {
+ CHAIN_BY_ID,
+ VALIDATION_REGISTRY_ABI,
+ validationRegistryFor,
+} from './erc8004-chains.js';
+import { KIND_GLB_SCHEMA } from '../../src/erc8004/validation-report.js';
const IDENTITY_ABI = [
'function tokenURI(uint256 tokenId) external view returns (string)',
@@ -412,6 +418,92 @@ function _withTimeout(promise, ms) {
});
}
+// ---------------------------------------------------------------------------
+// Validation attestations (ERC-8004 ValidationRegistry)
+// ---------------------------------------------------------------------------
+
+const VALIDATION_CACHE_TTL_S = 60;
+
+/**
+ * Read the latest on-chain validation attestation for an agent — no wallet
+ * required, so any surface can render the "Validated" badge straight from the
+ * server. Authoritative source is the on-chain ValidationRegistry; this layers a
+ * 60s cache on top (validation is re-runnable, so the badge stays fresh).
+ *
+ * Always resolves (never throws) so a badge fetch can't break a page:
+ * - { available: false } registry not deployed on this chain
+ * - { available: true, exists:false } deployed, but no attestation yet
+ * - { available: true, exists:true, passed, proofHash, proofURI, … }
+ *
+ * @param {{ chainId: number, agentId: string|number, kind?: string }} p
+ */
+export async function resolveLatestValidation({ chainId, agentId, kind = KIND_GLB_SCHEMA }) {
+ const meta = CHAIN_BY_ID[chainId];
+ const registryAddr = validationRegistryFor(chainId);
+ const explorer = meta?.explorer || '';
+
+ const base = {
+ chainId,
+ agentId: String(agentId),
+ kind,
+ registry: registryAddr || null,
+ available: !!registryAddr,
+ exists: false,
+ };
+
+ if (!registryAddr) {
+ base.reason = 'validation_registry_not_deployed';
+ return base;
+ }
+
+ const cacheKey = `onchain-validation:${chainId}:${agentId}:${kind}`;
+ const cached = await cacheGet(cacheKey);
+ if (cached) return cached;
+
+ let provider;
+ try {
+ provider = await evmFallbackProvider(chainId, { primaryUrl: meta?.rpcUrls?.[0] });
+ } catch (err) {
+ return { ...base, error: `rpc_init: ${err.message}` };
+ }
+
+ const registry = new Contract(registryAddr, VALIDATION_REGISTRY_ABI, provider);
+ let v;
+ try {
+ v = await _withTimeout(registry.getLatestByKind(BigInt(agentId), kind), 4000);
+ } catch (err) {
+ // getLatestByKind reverts with "no validation" when none exists — that's a
+ // normal empty result, not an error.
+ const msg = String(err?.shortMessage || err?.reason || err?.message || '');
+ if (/no validation/i.test(msg) || err?.code === 'CALL_EXCEPTION') {
+ await cacheSet(cacheKey, base, VALIDATION_CACHE_TTL_S);
+ return base;
+ }
+ return { ...base, error: `chain_read: ${msg}` };
+ }
+
+ const timestamp = Number(v.timestamp);
+ const result = {
+ ...base,
+ exists: true,
+ passed: Boolean(v.passed),
+ proofHash: v.proofHash,
+ proofURI: v.proofURI || null,
+ proofUrlResolved: v.proofURI ? resolveURI(v.proofURI) : null,
+ validator: _safeAddress(v.validator),
+ validatorExplorer: explorer && v.validator ? `${explorer}/address/${v.validator}` : null,
+ timestamp,
+ validatedAt: timestamp ? new Date(timestamp * 1000).toISOString() : null,
+ };
+ await cacheSet(cacheKey, result, VALIDATION_CACHE_TTL_S);
+ return result;
+}
+
+/** Invalidate the cached validation badge for an agent (call after a fresh attestation). */
+export async function invalidateValidationCache({ chainId, agentId, kind = KIND_GLB_SCHEMA }) {
+ await cacheDel(`onchain-validation:${chainId}:${agentId}:${kind}`);
+}
+
/** Short address form 0xabc…def */
export function shortenAddr(addr) {
if (!addr || typeof addr !== 'string') return '';
diff --git a/api/_lib/pump-alert-eval.js b/api/_lib/pump-alert-eval.js
new file mode 100644
index 000000000..43241626f
--- /dev/null
+++ b/api/_lib/pump-alert-eval.js
@@ -0,0 +1,241 @@
+// @ts-check
+// Pure rule-evaluation logic for pump dashboard alerts (Task 04).
+//
+// No DB, no network, no env — every function here is deterministic given its
+// inputs so the matching/cooldown/crossing logic can be unit-tested in
+// isolation (see tests/pump-alert-eval.test.js). The runner
+// (pump-alert-runner.js) supplies real data and the delivery side-effects.
+
+/**
+ * @typedef {Object} AlertRule
+ * @property {string} id
+ * @property {string} user_id
+ * @property {'graduation'|'price_above'|'price_below'|'whale_buy'|'new_mint'} kind
+ * @property {string|null} [target_mint]
+ * @property {string|null} [target_agent]
+ * @property {number|null} [threshold]
+ * @property {boolean} [deliver_in_app]
+ * @property {string|null} [webhook_url]
+ * @property {string|null} [webhook_secret]
+ * @property {string|null} [telegram_chat]
+ * @property {number} cooldown_seconds
+ * @property {boolean} enabled
+ * @property {string|null} [label]
+ */
+
+/** Kinds that require a specific mint target. */
+export const MINT_TARGETED_KINDS = Object.freeze(['price_above', 'price_below', 'whale_buy']);
+/** Kinds that require an agent target. */
+export const AGENT_TARGETED_KINDS = Object.freeze(['new_mint']);
+/** Kinds whose threshold is meaningful and must be > 0. */
+export const THRESHOLD_KINDS = Object.freeze(['price_above', 'price_below', 'whale_buy']);
+
+/**
+ * True when enough wall-clock has passed since the rule last fired.
+ * @param {string|number|Date|null|undefined} lastFiredAt
+ * @param {number} cooldownSeconds
+ * @param {number} [now] epoch ms
+ */
+export function cooldownElapsed(lastFiredAt, cooldownSeconds, now = Date.now()) {
+ if (!lastFiredAt) return true;
+ const last = lastFiredAt instanceof Date ? lastFiredAt.getTime() : new Date(lastFiredAt).getTime();
+ if (!Number.isFinite(last)) return true;
+ return now - last >= Math.max(0, (cooldownSeconds || 0) * 1000);
+}
+
+/**
+ * Does a graduation event satisfy this rule's targeting?
+ * @param {AlertRule} rule
+ * @param {{ mint?: string }} grad
+ * @param {{ agentMints?: Set<string> }} [ctx] mints owned by the rule's target agent
+ */
+export function gradMatchesRule(rule, grad, ctx = {}) {
+ if (rule.kind !== 'graduation') return false;
+ if (!grad?.mint) return false;
+ if (rule.target_mint) return grad.mint === rule.target_mint;
+ if (rule.target_agent) return ctx.agentMints instanceof Set && ctx.agentMints.has(grad.mint);
+ return true; // global graduation rule
+}
+
+/**
+ * Does a new-mint row (from pump_agent_mints) satisfy this rule?
+ * @param {AlertRule} rule
+ * @param {{ agent_id?: string, mint?: string }} mintRow
+ */
+export function newMintMatchesRule(rule, mintRow) {
+ if (rule.kind !== 'new_mint') return false;
+ if (!rule.target_agent) return false;
+ return mintRow?.agent_id === rule.target_agent;
+}
+
+/**
+ * Is this trade a whale buy for the rule (right mint, a buy, >= threshold SOL)?
+ * @param {AlertRule} rule
+ * @param {{ mint?: string, is_buy?: boolean, sol_amount?: number }} trade
+ */
+export function isWhaleBuy(rule, trade) {
+ if (rule.kind !== 'whale_buy') return false;
+ if (!rule.target_mint || trade?.mint !== rule.target_mint) return false;
+ if (!trade?.is_buy) return false;
+ const sol = Number(trade.sol_amount);
+ const threshold = Number(rule.threshold);
+ return Number.isFinite(sol) && Number.isFinite(threshold) && threshold > 0 && sol >= threshold;
+}
+
+/**
+ * Edge-triggered evaluation of a price (USD market cap) rule. Fires once when
+ * the metric crosses the threshold, then stays quiet until it crosses back and
+ * crosses again — so a token parked above the line doesn't alert every tick.
+ *
+ * @param {AlertRule} rule
+ * @param {number|null|undefined} currentMcapUsd
+ * @param {{ side?: 'over'|'under'|null }} [lastState]
+ * @returns {{ fire: boolean, nextState: { side: 'over'|'under' }, reason: string }}
+ */
+export function evaluatePriceRule(rule, currentMcapUsd, lastState = {}) {
+ const mcap = Number(currentMcapUsd);
+ const threshold = Number(rule.threshold);
+ // Without a live price we can't decide — preserve prior state, don't fire.
+ if (!Number.isFinite(mcap) || !Number.isFinite(threshold) || threshold <= 0) {
+ return { fire: false, nextState: { side: lastState.side === 'over' ? 'over' : 'under' }, reason: 'no_price' };
+ }
+
+ if (rule.kind === 'price_above') {
+ const over = mcap >= threshold;
+ const fire = over && lastState.side !== 'over';
+ return { fire, nextState: { side: over ? 'over' : 'under' }, reason: over ? 'above_threshold' : 'below_threshold' };
+ }
+ if (rule.kind === 'price_below') {
+ const under = mcap <= threshold;
+ const fire = under && lastState.side !== 'under';
+ return { fire, nextState: { side: under ? 'under' : 'over' }, reason: under ? 'below_threshold' : 'above_threshold' };
+ }
+ return { fire: false, nextState: { side: 'under' }, reason: 'not_price_rule' };
+}
+
+// ── Payload builders ─────────────────────────────────────────────────────────
+// Every alert is stored as a `user_notifications` row of type 'pump_alert' with
+// a payload shaped consistently across kinds so the dashboard renders them
+// uniformly. `event_id` is the dedupe key the runner persists in last_event_id.
+
+const iso = (v) => {
+ if (!v) return null;
+ const d = v instanceof Date ? v : new Date(v);
+ return Number.isFinite(d.getTime()) ? d.toISOString() : null;
+};
+
+/** @param {{ mint?: string, name?: string, symbol?: string, amount_sol?: number, market_cap_usd?: number, tx_signature?: string, seen_at?: any }} g */
+export function buildGraduationPayload(rule, g) {
+ return {
+ kind: 'graduation',
+ rule_id: rule.id,
+ event_id: g.tx_signature || g.mint || null,
+ mint: g.mint || null,
+ name: g.name || null,
+ symbol: g.symbol || null,
+ amount_sol: g.amount_sol != null ? Number(g.amount_sol) : null,
+ market_cap_usd: g.market_cap_usd != null ? Number(g.market_cap_usd) : null,
+ tx: g.tx_signature || null,
+ at: iso(g.seen_at) || iso(Date.now()),
+ };
+}
+
+/** @param {{ id?: string, mint?: string, name?: string, symbol?: string, agent_id?: string, created_at?: any }} m */
+export function buildNewMintPayload(rule, m) {
+ return {
+ kind: 'new_mint',
+ rule_id: rule.id,
+ event_id: m.mint || m.id || null,
+ mint: m.mint || null,
+ name: m.name || null,
+ symbol: m.symbol || null,
+ agent_id: m.agent_id || rule.target_agent || null,
+ at: iso(m.created_at) || iso(Date.now()),
+ };
+}
+
+/** @param {{ mint?: string, name?: string, symbol?: string }} token @param {{ sol_amount?: number, sol_value_usd?: number, signature?: string, buyer?: string, ts?: any }} trade */
+export function buildWhalePayload(rule, token, trade) {
+ return {
+ kind: 'whale_buy',
+ rule_id: rule.id,
+ event_id: trade.signature || null,
+ mint: token.mint || rule.target_mint || null,
+ name: token.name || null,
+ symbol: token.symbol || null,
+ amount_sol: trade.sol_amount != null ? Number(trade.sol_amount) : null,
+ amount_usd: trade.sol_value_usd != null ? Number(trade.sol_value_usd) : null,
+ buyer: trade.buyer || null,
+ tx: trade.signature || null,
+ at: iso(trade.ts) || iso(Date.now()),
+ };
+}
+
+/** @param {{ mint?: string, name?: string, symbol?: string, market_cap_usd?: number }} token */
+export function buildPricePayload(rule, token) {
+ return {
+ kind: rule.kind, // price_above | price_below
+ rule_id: rule.id,
+ // Bucket the dedupe key by hour so a sustained crossing logs at most one
+ // event per cooldown window even if the cron restarts mid-window.
+ event_id: `${rule.kind}:${token.mint}:${Math.floor(Date.now() / 3_600_000)}`,
+ mint: token.mint || rule.target_mint || null,
+ name: token.name || null,
+ symbol: token.symbol || null,
+ threshold_usd: Number(rule.threshold),
+ market_cap_usd: token.market_cap_usd != null ? Number(token.market_cap_usd) : null,
+ at: iso(Date.now()),
+ };
+}
+
+/**
+ * Human-readable one-line summary used for the Telegram message and as the
+ * in-app feed title.
+ * @param {Record<string, any>} p alert payload
+ */
+export function formatAlertSummary(p) {
+ const tok = p.symbol ? `$${p.symbol}` : p.name || (p.mint ? `${p.mint.slice(0, 4)}…${p.mint.slice(-4)}` : 'token');
+ const usd = (n) => (n != null && Number.isFinite(Number(n)) ? `$${Math.round(Number(n)).toLocaleString('en-US')}` : null);
+ switch (p.kind) {
+ case 'graduation': {
+ const mc = usd(p.market_cap_usd);
+ return `🎓 ${tok} graduated to AMM${mc ? ` at ${mc} mcap` : ''}`;
+ }
+ case 'new_mint':
+ return `🆕 ${tok} just launched`;
+ case 'whale_buy': {
+ const sol = p.amount_sol != null ? `${Number(p.amount_sol).toFixed(2)} SOL` : 'a large buy';
+ const u = usd(p.amount_usd);
+ return `🐳 Whale bought ${sol}${u ? ` (${u})` : ''} of ${tok}`;
+ }
+ case 'price_above':
+ return `📈 ${tok} mcap rose above ${usd(p.threshold_usd)} (now ${usd(p.market_cap_usd)})`;
+ case 'price_below':
+ return `📉 ${tok} mcap fell below ${usd(p.threshold_usd)} (now ${usd(p.market_cap_usd)})`;
+ default:
+ return `🔔 ${tok} alert`;
+ }
+}
+
+/** Default label shown when the user doesn't name a rule. */
+export function deriveRuleLabel(rule) {
+ const target = rule.target_mint
+ ? `${rule.target_mint.slice(0, 4)}…${rule.target_mint.slice(-4)}`
+ : rule.target_agent
+ ? 'tracked agent'
+ : 'all tokens';
+ switch (rule.kind) {
+ case 'graduation':
+ return `Graduations · ${target}`;
+ case 'new_mint':
+ return `New launches · ${target}`;
+ case 'whale_buy':
+ return `Whale buys ≥ ${rule.threshold} SOL · ${target}`;
+ case 'price_above':
+ return `Mcap above $${rule.threshold} · ${target}`;
+ case 'price_below':
+ return `Mcap below $${rule.threshold} · ${target}`;
+ default:
+ return 'Alert';
+ }
+}
diff --git a/api/_lib/pump-alert-runner.js b/api/_lib/pump-alert-runner.js
new file mode 100644
index 000000000..9e5099853
--- /dev/null
+++ b/api/_lib/pump-alert-runner.js
@@ -0,0 +1,385 @@
+// @ts-check
+// Server-side evaluator for pump dashboard alert rules (Task 04).
+//
+// Invoked every ~3 min by the pumpfun-monitor cron (api/cron/[name].js). For
+// every enabled rule it matches the configured event class against a REAL
+// persisted/live data source, respects the rule's cooldown, dedupes so the same
+// on-chain event is never delivered twice, and fans the match out across the
+// rule's delivery channels (in-app / webhook / Telegram).
+//
+// Data sources (all real, no mocks):
+// graduation → pumpfun_graduations (persisted global feed) + pump_agent_mints
+// new_mint → pump_agent_mints (a tracked agent's new coins)
+// price_* → pump.fun coins API (authoritative USD market cap)
+// whale_buy → pump.fun trades API (recent buys on the target mint)
+
+import { sql } from './db.js';
+import {
+ cooldownElapsed,
+ gradMatchesRule,
+ newMintMatchesRule,
+ isWhaleBuy,
+ evaluatePriceRule,
+ buildGraduationPayload,
+ buildNewMintPayload,
+ buildWhalePayload,
+ buildPricePayload,
+} from './pump-alert-eval.js';
+import { deliverAlert } from './alert-delivery.js';
+
+const GRAD_WINDOW = '15 minutes';
+const NEW_MINT_WINDOW = '60 minutes';
+const GRADS_PER_RUN = 100;
+const DELIVER_CAP = 5; // max events delivered per rule per run (storm guard)
+const MAX_PRICE_MINTS = 60; // distinct mints priced per run
+const MAX_WHALE_MINTS = 60; // distinct mints polled for trades per run
+const TRADES_LIMIT = 50;
+const FETCH_TIMEOUT_MS = 2_500;
+const SOL_PRICE_TTL_MS = 60_000;
+
+const PUMPFUN_COIN_API = 'https://frontend-api-v3.pump.fun/coins';
+const PUMPFUN_TRADES_API = 'https://frontend-api-v3.pump.fun/trades/all';
+
+/**
+ * Evaluate all enabled pump alert rules and deliver matches.
+ * @returns {Promise<Record<string, any>>} a structured report for the cron response.
+ */
+export async function runPumpAlertRules(now = Date.now()) {
+ const report = {
+ rules: 0,
+ evaluated: 0,
+ fired: 0,
+ deliveries: { in_app: 0, webhook: 0, telegram: 0 },
+ failures: { in_app: 0, webhook: 0, telegram: 0 },
+ capped: { price_mints: false, whale_mints: false },
+ errors: 0,
+ };
+
+ /** @type {any[]} */
+ let rules;
+ try {
+ rules = await sql`
+ SELECT id, user_id, kind, target_mint, target_agent, threshold,
+ deliver_in_app, webhook_url, webhook_secret, telegram_chat,
+ cooldown_seconds, enabled, label
+ FROM pump_alert_rules
+ WHERE enabled = true
+ `;
+ } catch (e) {
+ // Table not migrated yet (dev/test) — skip cleanly.
+ return { skipped: 'pump_alert_rules_unavailable', detail: e?.message || String(e) };
+ }
+ report.rules = rules.length;
+ if (!rules.length) {
+ await pruneDeliveries();
+ return report;
+ }
+
+ // Fire state (cooldown / dedupe / crossing) for every rule, in one query.
+ const fireRows = await sql`
+ SELECT rule_id, last_fired_at, last_event_id, last_state
+ FROM pump_alert_rule_fires
+ WHERE rule_id = ANY(${rules.map((r) => r.id)})
+ `;
+ const fireState = new Map(fireRows.map((f) => [f.rule_id, f]));
+
+ // Partition rules by kind.
+ const byKind = { graduation: [], new_mint: [], price: [], whale_buy: [] };
+ for (const r of rules) {
+ if (r.kind === 'graduation') byKind.graduation.push(r);
+ else if (r.kind === 'new_mint') byKind.new_mint.push(r);
+ else if (r.kind === 'price_above' || r.kind === 'price_below') byKind.price.push(r);
+ else if (r.kind === 'whale_buy') byKind.whale_buy.push(r);
+ }
+
+ const ctx = { now, solPrice: 0 };
+
+ await Promise.all([
+ runGraduationRules(byKind.graduation, fireState, report, ctx).catch((e) => bumpErr(report, e)),
+ runNewMintRules(byKind.new_mint, fireState, report, ctx).catch((e) => bumpErr(report, e)),
+ runPriceRules(byKind.price, fireState, report, ctx).catch((e) => bumpErr(report, e)),
+ runWhaleRules(byKind.whale_buy, fireState, report, ctx).catch((e) => bumpErr(report, e)),
+ ]);
+
+ await pruneDeliveries();
+ return report;
+}
+
+function bumpErr(report, e) {
+ report.errors++;
+ console.error('[pump-alerts] evaluation error:', e?.message || e);
+}
+
+// ── graduation ───────────────────────────────────────────────────────────────
+
+async function runGraduationRules(rules, fireState, report, ctx) {
+ if (!rules.length) return;
+
+ const grads = await sql`
+ SELECT tx_signature, mint, name, symbol, amount_sol, market_cap_usd, seen_at
+ FROM pumpfun_graduations
+ WHERE seen_at > now() - ${GRAD_WINDOW}::interval
+ ORDER BY seen_at ASC
+ LIMIT ${GRADS_PER_RUN}
+ `;
+ if (!grads.length) return;
+
+ // Build agent → owned-mints map for any agent-scoped graduation rules.
+ const agentIds = [...new Set(rules.map((r) => r.target_agent).filter(Boolean))];
+ const agentMints = await loadAgentMintSets(agentIds);
+
+ for (const rule of rules) {
+ report.evaluated++;
+ const owned = rule.target_agent ? agentMints.get(rule.target_agent) || new Set() : undefined;
+ const matched = grads.filter((g) => gradMatchesRule(rule, g, { agentMints: owned }));
+ if (!matched.length) continue;
+ const events = matched.map((g) => buildGraduationPayload(rule, g));
+ await deliverEventRule(rule, fireState.get(rule.id), events, report, ctx.now);
+ }
+}
+
+// ── new_mint (by tracked agent) ───────────────────────────────────────────────
+
+async function runNewMintRules(rules, fireState, report, ctx) {
+ if (!rules.length) return;
+ const agentIds = [...new Set(rules.map((r) => r.target_agent).filter(Boolean))];
+ if (!agentIds.length) return;
+
+ const mints = await sql`
+ SELECT id, agent_id, mint, name, symbol, created_at
+ FROM pump_agent_mints
+ WHERE agent_id = ANY(${agentIds})
+ AND created_at > now() - ${NEW_MINT_WINDOW}::interval
+ ORDER BY created_at ASC
+ `;
+ if (!mints.length) return;
+
+ for (const rule of rules) {
+ report.evaluated++;
+ const matched = mints.filter((m) => newMintMatchesRule(rule, m));
+ if (!matched.length) continue;
+ const events = matched.map((m) => buildNewMintPayload(rule, m));
+ await deliverEventRule(rule, fireState.get(rule.id), events, report, ctx.now);
+ }
+}
+
+// ── price (USD market cap crossing) ────────────────────────────────────────────
+
+async function runPriceRules(rules, fireState, report, ctx) {
+ if (!rules.length) return;
+
+ let mints = [...new Set(rules.map((r) => r.target_mint).filter(Boolean))];
+ if (mints.length > MAX_PRICE_MINTS) {
+ report.capped.price_mints = mints.length;
+ console.warn(`[pump-alerts] price rules: ${mints.length} mints exceeds cap ${MAX_PRICE_MINTS}; pricing first ${MAX_PRICE_MINTS}`);
+ mints = mints.slice(0, MAX_PRICE_MINTS);
+ }
+ const priced = new Map();
+ await Promise.all(
+ mints.map(async (mint) => {
+ priced.set(mint, await fetchCoin(mint));
+ }),
+ );
+
+ for (const rule of rules) {
+ report.evaluated++;
+ const coin = priced.get(rule.target_mint);
+ if (!coin || coin.market_cap_usd == null) continue;
+ const fs = fireState.get(rule.id);
+ const lastState = fs?.last_state || {};
+ const { fire, nextState } = evaluatePriceRule(rule, coin.market_cap_usd, lastState);
+
+ if (!fire) {
+ // Persist crossing state every tick so the edge-trigger stays accurate.
+ await upsertFire(rule.id, { last_state: nextState });
+ continue;
+ }
+ if (!cooldownElapsed(fs?.last_fired_at, rule.cooldown_seconds, ctx.now)) {
+ await upsertFire(rule.id, { last_state: nextState });
+ continue;
+ }
+ const payload = buildPricePayload(rule, coin);
+ await deliverOne(rule, payload, report);
+ await upsertFire(rule.id, { last_fired_at: new Date(ctx.now), last_event_id: payload.event_id, last_state: nextState });
+ report.fired++;
+ }
+}
+
+// ── whale buys ─────────────────────────────────────────────────────────────────
+
+async function runWhaleRules(rules, fireState, report, ctx) {
+ if (!rules.length) return;
+
+ let mints = [...new Set(rules.map((r) => r.target_mint).filter(Boolean))];
+ if (mints.length > MAX_WHALE_MINTS) {
+ report.capped.whale_mints = mints.length;
+ console.warn(`[pump-alerts] whale rules: ${mints.length} mints exceeds cap ${MAX_WHALE_MINTS}; polling first ${MAX_WHALE_MINTS}`);
+ mints = mints.slice(0, MAX_WHALE_MINTS);
+ }
+ ctx.solPrice = await getSolPrice();
+ const tradesByMint = new Map();
+ await Promise.all(
+ mints.map(async (mint) => {
+ tradesByMint.set(mint, await fetchRecentTrades(mint, ctx.solPrice));
+ }),
+ );
+
+ for (const rule of rules) {
+ report.evaluated++;
+ const coin = { mint: rule.target_mint };
+ const trades = tradesByMint.get(rule.target_mint) || [];
+ // trades are returned newest-first; flip to ascending for ordered dedupe.
+ const asc = trades.slice().reverse();
+ const matched = asc.filter((t) => isWhaleBuy(rule, { ...t, mint: rule.target_mint }));
+ if (!matched.length) continue;
+ const events = matched.map((t) => buildWhalePayload(rule, coin, t));
+ await deliverEventRule(rule, fireState.get(rule.id), events, report, ctx.now);
+ }
+}
+
+// ── generic event delivery (graduation / new_mint / whale) ─────────────────────
+
+/**
+ * Deliver an ordered (ascending) list of event payloads for one rule, honoring
+ * cooldown and deduping against last_event_id.
+ */
+async function deliverEventRule(rule, fs, events, report, now) {
+ if (!cooldownElapsed(fs?.last_fired_at, rule.cooldown_seconds, now)) return;
+
+ let fresh = events;
+ if (fs?.last_event_id) {
+ const idx = events.findIndex((e) => e.event_id && e.event_id === fs.last_event_id);
+ if (idx >= 0) fresh = events.slice(idx + 1);
+ }
+ fresh = fresh.filter((e) => e.event_id);
+ if (!fresh.length) return;
+
+ const toDeliver = fresh.slice(-DELIVER_CAP);
+ for (const payload of toDeliver) {
+ await deliverOne(rule, payload, report);
+ report.fired++;
+ }
+ const latest = toDeliver[toDeliver.length - 1];
+ await upsertFire(rule.id, { last_fired_at: new Date(now), last_event_id: latest.event_id });
+}
+
+/** Run one payload across the rule's channels and log per-channel outcomes. */
+async function deliverOne(rule, payload, report) {
+ const result = await deliverAlert(rule, payload);
+ for (const channel of /** @type {const} */ (['in_app', 'webhook', 'telegram'])) {
+ const r = result[channel];
+ if (!r.attempted) continue;
+ if (r.ok) report.deliveries[channel]++;
+ else report.failures[channel]++;
+ await logDelivery(rule, channel, r, payload.event_id).catch(() => {});
+ }
+}
+
+async function logDelivery(rule, channel, r, eventId) {
+ await sql`
+ insert into pump_alert_deliveries (rule_id, user_id, channel, ok, detail, event_id)
+ values (${rule.id}, ${rule.user_id}, ${channel}, ${r.ok}, ${r.detail || null}, ${eventId || null})
+ `;
+}
+
+/** Upsert a rule's fire/cooldown/crossing state. Only provided columns change. */
+async function upsertFire(ruleId, { last_fired_at, last_event_id, last_state } = {}) {
+ await sql`
+ insert into pump_alert_rule_fires (rule_id, last_fired_at, last_event_id, last_state, updated_at)
+ values (
+ ${ruleId},
+ ${last_fired_at ?? null},
+ ${last_event_id ?? null},
+ ${last_state ? JSON.stringify(last_state) : '{}'}::jsonb,
+ now()
+ )
+ on conflict (rule_id) do update set
+ last_fired_at = coalesce(${last_fired_at ?? null}, pump_alert_rule_fires.last_fired_at),
+ last_event_id = coalesce(${last_event_id ?? null}, pump_alert_rule_fires.last_event_id),
+ last_state = coalesce(${last_state ? JSON.stringify(last_state) : null}::jsonb, pump_alert_rule_fires.last_state),
+ updated_at = now()
+ `;
+}
+
+async function pruneDeliveries() {
+ try {
+ await sql`DELETE FROM pump_alert_deliveries WHERE created_at < now() - interval '7 days'`;
+ } catch {
+ /* best-effort */
+ }
+}
+
+// ── agent → owned mints ────────────────────────────────────────────────────────
+
+async function loadAgentMintSets(agentIds) {
+ const map = new Map();
+ if (!agentIds.length) return map;
+ const rows = await sql`
+ SELECT agent_id, mint FROM pump_agent_mints WHERE agent_id = ANY(${agentIds})
+ `;
+ for (const r of rows) {
+ if (!map.has(r.agent_id)) map.set(r.agent_id, new Set());
+ map.get(r.agent_id).add(r.mint);
+ }
+ return map;
+}
+
+// ── live pump.fun fetchers ─────────────────────────────────────────────────────
+
+async function fetchJsonWithTimeout(url, ms = FETCH_TIMEOUT_MS) {
+ const ctrl = new AbortController();
+ const tid = setTimeout(() => ctrl.abort(), ms);
+ try {
+ const r = await fetch(url, {
+ signal: ctrl.signal,
+ headers: { accept: 'application/json', 'user-agent': 'three.ws-pump-alerts/1' },
+ });
+ if (!r.ok) return null;
+ return await r.json();
+ } catch {
+ return null;
+ } finally {
+ clearTimeout(tid);
+ }
+}
+
+/** Current coin snapshot → { mint, name, symbol, market_cap_usd } or null. */
+async function fetchCoin(mint) {
+ const d = await fetchJsonWithTimeout(`${PUMPFUN_COIN_API}/${encodeURIComponent(mint)}`);
+ if (!d) return null;
+ const mc = typeof d.usd_market_cap === 'number' ? d.usd_market_cap : null;
+ return { mint, name: d.name || null, symbol: d.symbol || null, market_cap_usd: mc };
+}
+
+/**
+ * Recent trades for a mint, newest-first, normalized to
+ * { signature, is_buy, sol_amount (SOL), sol_value_usd, buyer, ts }.
+ */
+async function fetchRecentTrades(mint, solPrice = 0) {
+ const d = await fetchJsonWithTimeout(`${PUMPFUN_TRADES_API}/${encodeURIComponent(mint)}?limit=${TRADES_LIMIT}&offset=0`);
+ if (!Array.isArray(d)) return [];
+ return d.map((t) => {
+ const sol = typeof t.sol_amount === 'number' ? t.sol_amount / 1e9 : null;
+ return {
+ signature: t.signature || t.tx_signature || null,
+ is_buy: t.is_buy === true,
+ sol_amount: sol,
+ sol_value_usd: sol != null && solPrice > 0 ? sol * solPrice : null,
+ buyer: t.user || t.trader || null,
+ ts: typeof t.timestamp === 'number' ? new Date(t.timestamp * 1000) : null,
+ };
+ });
+}
+
+let _solPrice = 0;
+let _solPriceAt = 0;
+async function getSolPrice() {
+ if (Date.now() - _solPriceAt < SOL_PRICE_TTL_MS && _solPrice > 0) return _solPrice;
+ const d = await fetchJsonWithTimeout('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd');
+ const p = d?.solana?.usd;
+ if (p > 0) {
+ _solPrice = p;
+ _solPriceAt = Date.now();
+ }
+ return _solPrice || 0;
+}
diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.js
index f1dc52889..8e5b6b43e 100644
--- a/api/agents/solana/_handlers.js
+++ b/api/agents/solana/_handlers.js
@@ -65,6 +65,11 @@ export const handleAttestations = wrap(async (req, res) => {
const network = url.searchParams.get('network') === 'mainnet' ? 'mainnet' : 'devnet';
const limit = Math.min(Number(url.searchParams.get('limit') || 100), 500);
const includeRevoked = url.searchParams.get('include_revoked') === '1';
+ // One-shot on-demand reindex. The crawl cron only runs every 5 min, so a
+ // visitor who just submitted feedback would otherwise wait minutes to see it.
+ // `refresh=1` (already rate-limited by authIp above) pulls the latest
+ // signatures for this agent before answering, closing the submit→see-it loop.
+ const force = url.searchParams.get('refresh') === '1';
if (!asset) return error(res, 400, 'validation_error', 'asset query param required');
try { new PublicKey(asset); } catch { return error(res, 400, 'validation_error', 'invalid asset pubkey'); }
@@ -74,10 +79,11 @@ export const handleAttestations = wrap(async (req, res) => {
return error(res, 400, 'validation_error', 'kind must be one of: feedback, validation, task, accept, revoke, dispute, all');
}
- const [cursor] = await sql`select last_indexed_at from solana_attestations_cursor where agent_asset = ${asset} limit 1`;
- if (!cursor) {
+ let [cursor] = await sql`select last_indexed_at from solana_attestations_cursor where agent_asset = ${asset} limit 1`;
+ if (!cursor || force) {
const [agent] = await sql`select wallet_address as owner from agent_identities where meta->>'sol_mint_address' = ${asset} and deleted_at is null limit 1`;
try { await crawlAgentAttestations({ agentAsset: asset, network, ownerWallet: agent?.owner || null }); } catch {}
+ [cursor] = await sql`select last_indexed_at from solana_attestations_cursor where agent_asset = ${asset} limit 1`;
}
const rows = wantKind
diff --git a/api/alerts/_rules.js b/api/alerts/_rules.js
new file mode 100644
index 000000000..e44c06537
--- /dev/null
+++ b/api/alerts/_rules.js
@@ -0,0 +1,155 @@
+// Shared validation + serialization for the pump alert rules CRUD endpoints.
+// Underscore-prefixed → not routed by Vercel; imported by rules.js and
+// rules/[id].js so the create and update paths can't drift apart.
+
+import { z } from 'zod';
+import { isValidSolanaAddress, isUuid } from '../_lib/validate.js';
+import { MINT_TARGETED_KINDS, AGENT_TARGETED_KINDS, THRESHOLD_KINDS, deriveRuleLabel } from '../_lib/pump-alert-eval.js';
+
+export const RULE_KINDS = ['graduation', 'price_above', 'price_below', 'whale_buy', 'new_mint'];
+
+const telegramChat = z
+ .string()
+ .trim()
+ .max(64)
+ .refine(
+ (v) => /^-?\d{1,32}$/.test(v) || /^@[a-zA-Z0-9_]{4,64}$/.test(v),
+ 'telegram_chat must be a numeric chat id or @username',
+ );
+
+const webhookUrl = z
+ .string()
+ .trim()
+ .max(2048)
+ .url()
+ .refine((u) => /^https:\/\//i.test(u), 'webhook_url must be https');
+
+const nullableUrl = webhookUrl.nullable().or(z.literal('').transform(() => null));
+const nullableTelegram = telegramChat.nullable().or(z.literal('').transform(() => null));
+
+// Base shape — refinements that depend on `kind` run in superRefine below.
+const baseShape = {
+ kind: z.enum(RULE_KINDS),
+ target_mint: z
+ .string()
+ .trim()
+ .max(64)
+ .refine((v) => isValidSolanaAddress(v), 'target_mint is not a valid Solana address')
+ .nullable()
+ .optional(),
+ target_agent: z
+ .string()
+ .trim()
+ .refine((v) => isUuid(v), 'target_agent must be a UUID')
+ .nullable()
+ .optional(),
+ threshold: z.coerce.number().positive().max(1e15).nullable().optional(),
+ deliver_in_app: z.boolean().optional(),
+ webhook_url: nullableUrl.optional(),
+ telegram_chat: nullableTelegram.optional(),
+ cooldown_seconds: z.coerce.number().int().min(5).max(86_400).optional(),
+ enabled: z.boolean().optional(),
+ label: z.string().trim().max(80).nullable().optional(),
+};
+
+/** Cross-field rules shared by create (strict) and update (after merge). */
+function refineRule(v, ctx) {
+ const mintTargeted = MINT_TARGETED_KINDS.includes(v.kind);
+ const agentTargeted = AGENT_TARGETED_KINDS.includes(v.kind);
+
+ if (mintTargeted) {
+ if (!v.target_mint) {
+ ctx.addIssue({ code: 'custom', path: ['target_mint'], message: `${v.kind} requires a target_mint` });
+ }
+ if (v.target_agent) {
+ ctx.addIssue({ code: 'custom', path: ['target_agent'], message: `${v.kind} cannot have a target_agent` });
+ }
+ }
+ if (agentTargeted) {
+ if (!v.target_agent) {
+ ctx.addIssue({ code: 'custom', path: ['target_agent'], message: `${v.kind} requires a target_agent` });
+ }
+ if (v.target_mint) {
+ ctx.addIssue({ code: 'custom', path: ['target_mint'], message: `${v.kind} cannot have a target_mint` });
+ }
+ }
+ if (v.kind === 'graduation' && v.target_mint && v.target_agent) {
+ ctx.addIssue({ code: 'custom', path: ['target_agent'], message: 'set either target_mint or target_agent, not both' });
+ }
+ if (THRESHOLD_KINDS.includes(v.kind) && !(Number(v.threshold) > 0)) {
+ ctx.addIssue({ code: 'custom', path: ['threshold'], message: `${v.kind} requires a positive threshold` });
+ }
+
+ // At least one delivery channel must be active. deliver_in_app defaults true.
+ const inApp = v.deliver_in_app !== false;
+ if (!inApp && !v.webhook_url && !v.telegram_chat) {
+ ctx.addIssue({ code: 'custom', path: ['deliver_in_app'], message: 'enable at least one delivery channel' });
+ }
+}
+
+export const createRuleSchema = z.object(baseShape).superRefine(refineRule);
+
+// Update: every field optional; cross-field validation happens after merging
+// with the existing row (see validateUpdate).
+export const updateRuleSchema = z
+ .object({ ...baseShape, kind: baseShape.kind.optional() })
+ .refine((v) => Object.keys(v).length > 0, 'no fields to update');
+
+/**
+ * Merge a partial update over the current row, normalize targeting/threshold to
+ * the effective kind, then run the shared cross-field validation.
+ * @returns {{ ok: true, value: object } | { ok: false, issues: any[] }}
+ */
+export function validateUpdate(current, patch) {
+ const merged = {
+ kind: patch.kind ?? current.kind,
+ target_mint: 'target_mint' in patch ? patch.target_mint : current.target_mint,
+ target_agent: 'target_agent' in patch ? patch.target_agent : current.target_agent,
+ threshold: 'threshold' in patch ? patch.threshold : current.threshold,
+ deliver_in_app: 'deliver_in_app' in patch ? patch.deliver_in_app : current.deliver_in_app,
+ webhook_url: 'webhook_url' in patch ? patch.webhook_url : current.webhook_url,
+ telegram_chat: 'telegram_chat' in patch ? patch.telegram_chat : current.telegram_chat,
+ cooldown_seconds: 'cooldown_seconds' in patch ? patch.cooldown_seconds : current.cooldown_seconds,
+ enabled: 'enabled' in patch ? patch.enabled : current.enabled,
+ label: 'label' in patch ? patch.label : current.label,
+ };
+ const issues = [];
+ refineRule(merged, { addIssue: (i) => issues.push(i) });
+ if (issues.length) return { ok: false, issues };
+ return { ok: true, value: normalizeForKind(merged) };
+}
+
+/** Null out fields that don't apply to the rule's kind so stale values can't leak. */
+export function normalizeForKind(v) {
+ const out = { ...v };
+ if (!THRESHOLD_KINDS.includes(out.kind)) out.threshold = null;
+ if (!MINT_TARGETED_KINDS.includes(out.kind) && out.kind !== 'graduation') out.target_mint = null;
+ if (!AGENT_TARGETED_KINDS.includes(out.kind) && out.kind !== 'graduation') out.target_agent = null;
+ if (out.deliver_in_app === undefined) out.deliver_in_app = true;
+ if (out.cooldown_seconds === undefined) out.cooldown_seconds = 300;
+ if (out.enabled === undefined) out.enabled = true;
+ return out;
+}
+
+/** Shape a DB row for the API response (includes the user's own webhook secret). */
+export function serializeRule(row) {
+ return {
+ id: row.id,
+ kind: row.kind,
+ target_mint: row.target_mint || null,
+ target_agent: row.target_agent || null,
+ threshold: row.threshold != null ? Number(row.threshold) : null,
+ deliver_in_app: row.deliver_in_app,
+ webhook_url: row.webhook_url || null,
+ webhook_secret: row.webhook_secret || null,
+ telegram_chat: row.telegram_chat || null,
+ cooldown_seconds: row.cooldown_seconds,
+ enabled: row.enabled,
+ label: row.label || deriveRuleLabel(row),
+ last_fired_at: row.last_fired_at || null,
+ recent_failures: row.recent_failures != null ? Number(row.recent_failures) : 0,
+ recent_deliveries: row.recent_deliveries || [],
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ };
+}
diff --git a/api/alerts/rules.js b/api/alerts/rules.js
new file mode 100644
index 000000000..344456996
--- /dev/null
+++ b/api/alerts/rules.js
@@ -0,0 +1,100 @@
+// GET /api/alerts/rules — list the signed-in user's pump alert rules.
+// POST /api/alerts/rules — create a new rule.
+//
+// Server-persisted, multi-rule alert model (Task 04). Rules are evaluated by the
+// pumpfun-monitor cron against the live pump.fun event stream, so they fire
+// across devices even with no dashboard tab open. The frontend treats
+// localStorage as a render cache only; these endpoints are the source of truth.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { limits } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import { randomToken } from '../_lib/crypto.js';
+import { createRuleSchema, normalizeForKind, serializeRule } from './_rules.js';
+
+const MAX_RULES_PER_USER = 50;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ if (req.method === 'GET') {
+ const rl = await limits.notificationsRead(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+ const rows = await listRules(user.id);
+ return json(res, 200, { rules: rows.map(serializeRule) });
+ }
+
+ // POST — create
+ const rl = await limits.prefsWrite(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const body = normalizeForKind(parse(createRuleSchema, await readJson(req)));
+
+ if (body.target_agent) {
+ const [agent] = await sql`SELECT 1 AS ok FROM agent_identities WHERE id = ${body.target_agent}`;
+ if (!agent) return error(res, 400, 'validation_error', 'target_agent does not exist');
+ }
+
+ const [{ count }] = await sql`SELECT count(*)::int AS count FROM pump_alert_rules WHERE user_id = ${user.id}`;
+ if (count >= MAX_RULES_PER_USER) {
+ return error(res, 409, 'limit_reached', `you can have at most ${MAX_RULES_PER_USER} alert rules`);
+ }
+
+ // Generate a per-rule signing secret when a webhook is configured so the
+ // receiver can verify the webhook-signature header.
+ const webhookSecret = body.webhook_url ? `whsec_${randomToken(24)}` : null;
+
+ const [row] = await sql`
+ INSERT INTO pump_alert_rules
+ (user_id, kind, target_mint, target_agent, threshold, deliver_in_app,
+ webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled, label)
+ VALUES
+ (${user.id}, ${body.kind}, ${body.target_mint || null}, ${body.target_agent || null},
+ ${body.threshold ?? null}, ${body.deliver_in_app}, ${body.webhook_url || null},
+ ${webhookSecret}, ${body.telegram_chat || null}, ${body.cooldown_seconds},
+ ${body.enabled}, ${body.label || null})
+ RETURNING id, kind, target_mint, target_agent, threshold, deliver_in_app,
+ webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled,
+ label, created_at, updated_at
+ `;
+
+ return json(res, 201, { rule: serializeRule({ ...row, last_fired_at: null, recent_failures: 0, recent_deliveries: [] }) });
+});
+
+async function listRules(userId) {
+ return sql`
+ SELECT r.id, r.kind, r.target_mint, r.target_agent, r.threshold,
+ r.deliver_in_app, r.webhook_url, r.webhook_secret, r.telegram_chat,
+ r.cooldown_seconds, r.enabled, r.label, r.created_at, r.updated_at,
+ f.last_fired_at,
+ coalesce(fail.cnt, 0) AS recent_failures,
+ coalesce(rd.deliveries, '[]'::json) AS recent_deliveries
+ FROM pump_alert_rules r
+ LEFT JOIN pump_alert_rule_fires f ON f.rule_id = r.id
+ LEFT JOIN LATERAL (
+ SELECT count(*)::int AS cnt
+ FROM pump_alert_deliveries d
+ WHERE d.rule_id = r.id AND d.ok = false AND d.created_at > now() - interval '24 hours'
+ ) fail ON true
+ LEFT JOIN LATERAL (
+ SELECT json_agg(json_build_object('channel', s.channel, 'ok', s.ok, 'detail', s.detail, 'at', s.created_at) ORDER BY s.created_at DESC) AS deliveries
+ FROM (
+ SELECT channel, ok, detail, created_at
+ FROM pump_alert_deliveries d2
+ WHERE d2.rule_id = r.id
+ ORDER BY created_at DESC
+ LIMIT 5
+ ) s
+ ) rd ON true
+ WHERE r.user_id = ${userId}
+ ORDER BY r.created_at DESC
+ `;
+}
diff --git a/api/alerts/rules/[id].js b/api/alerts/rules/[id].js
new file mode 100644
index 000000000..70cd2065e
--- /dev/null
+++ b/api/alerts/rules/[id].js
@@ -0,0 +1,108 @@
+// PATCH /api/alerts/rules/:id — update a rule.
+// DELETE /api/alerts/rules/:id — delete a rule (cascades fires + delivery log).
+//
+// Part of the server-side multi-rule alert model (Task 04). Ownership is
+// enforced on every operation: a user can only touch their own rules.
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { parse, isUuid } from '../../_lib/validate.js';
+import { randomToken } from '../../_lib/crypto.js';
+import { updateRuleSchema, validateUpdate, serializeRule } from '../_rules.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'PATCH,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['PATCH', 'DELETE'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const id = req.query?.id;
+ if (!id || !isUuid(id)) return error(res, 400, 'validation_error', 'valid rule id required');
+
+ const rl = await limits.prefsWrite(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ if (req.method === 'DELETE') {
+ const [row] = await sql`
+ DELETE FROM pump_alert_rules WHERE id = ${id} AND user_id = ${user.id} RETURNING id
+ `;
+ if (!row) return error(res, 404, 'not_found', 'rule not found');
+ return json(res, 200, { ok: true, id: row.id });
+ }
+
+ // PATCH
+ const [current] = await sql`
+ SELECT id, kind, target_mint, target_agent, threshold, deliver_in_app,
+ webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled, label
+ FROM pump_alert_rules
+ WHERE id = ${id} AND user_id = ${user.id}
+ `;
+ if (!current) return error(res, 404, 'not_found', 'rule not found');
+
+ const patch = parse(updateRuleSchema, await readJson(req));
+ const result = validateUpdate(current, patch);
+ if (!result.ok) {
+ return error(res, 400, 'validation_error', result.issues[0]?.message || 'invalid update', {
+ issues: result.issues,
+ });
+ }
+ const next = result.value;
+
+ if (next.target_agent && next.target_agent !== current.target_agent) {
+ const [agent] = await sql`SELECT 1 AS ok FROM agent_identities WHERE id = ${next.target_agent}`;
+ if (!agent) return error(res, 400, 'validation_error', 'target_agent does not exist');
+ }
+
+ // Webhook secret lifecycle: mint one when a webhook is newly configured,
+ // drop it when the webhook is removed, otherwise keep the existing secret.
+ let webhookSecret = current.webhook_secret;
+ if (!next.webhook_url) webhookSecret = null;
+ else if (!current.webhook_url || !current.webhook_secret) webhookSecret = `whsec_${randomToken(24)}`;
+
+ await sql`
+ UPDATE pump_alert_rules SET
+ kind = ${next.kind},
+ target_mint = ${next.target_mint || null},
+ target_agent = ${next.target_agent || null},
+ threshold = ${next.threshold ?? null},
+ deliver_in_app = ${next.deliver_in_app},
+ webhook_url = ${next.webhook_url || null},
+ webhook_secret = ${webhookSecret},
+ telegram_chat = ${next.telegram_chat || null},
+ cooldown_seconds = ${next.cooldown_seconds},
+ enabled = ${next.enabled},
+ label = ${next.label || null},
+ updated_at = now()
+ WHERE id = ${id} AND user_id = ${user.id}
+ `;
+
+ const [row] = await sql`
+ SELECT r.id, r.kind, r.target_mint, r.target_agent, r.threshold,
+ r.deliver_in_app, r.webhook_url, r.webhook_secret, r.telegram_chat,
+ r.cooldown_seconds, r.enabled, r.label, r.created_at, r.updated_at,
+ f.last_fired_at,
+ coalesce(fail.cnt, 0) AS recent_failures,
+ coalesce(rd.deliveries, '[]'::json) AS recent_deliveries
+ FROM pump_alert_rules r
+ LEFT JOIN pump_alert_rule_fires f ON f.rule_id = r.id
+ LEFT JOIN LATERAL (
+ SELECT count(*)::int AS cnt FROM pump_alert_deliveries d
+ WHERE d.rule_id = r.id AND d.ok = false AND d.created_at > now() - interval '24 hours'
+ ) fail ON true
+ LEFT JOIN LATERAL (
+ SELECT json_agg(json_build_object('channel', s.channel, 'ok', s.ok, 'detail', s.detail, 'at', s.created_at) ORDER BY s.created_at DESC) AS deliveries
+ FROM (
+ SELECT channel, ok, detail, created_at FROM pump_alert_deliveries d2
+ WHERE d2.rule_id = r.id ORDER BY created_at DESC LIMIT 5
+ ) s
+ ) rd ON true
+ WHERE r.id = ${id} AND r.user_id = ${user.id}
+ `;
+
+ return json(res, 200, { rule: serializeRule(row) });
+});
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 02a68a62c..8c677e4b6 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -51,6 +51,7 @@ import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.j
import { chargeSubscription, failPayment } from '../_lib/subscription-billing.js';
import { sendEmail } from '../_lib/email.js';
import { fetchSafePublicUrl } from '../_lib/ssrf-guard.js';
+import { runPumpAlertRules } from '../_lib/pump-alert-runner.js';
import { constantTimeEquals } from '../_lib/crypto.js';
// ─── Cron auth ───────────────────────────────────────────────────────────────
@@ -1042,7 +1043,7 @@ async function handlePumpfunMonitor(req, res) {
// attester provisioning, so /api/healthz reports real bot status and the
// dashboard's server-side alerts fire even when no tab is open.
await writeBotHeartbeat();
- const alertReport = await evaluateUserAlerts().catch((e) => ({
+ const alertReport = await runPumpAlertRules().catch((e) => ({
error: e?.message || String(e),
}));
@@ -1171,130 +1172,12 @@ async function writeBotHeartbeat() {
}
// ── Server-side alert delivery ──────────────────────────────────────────────
-// Evaluates each user's graduation alert rule against the real pumpfun_graduations
-// table and delivers via an in-app notification (user_notifications, type
-// 'pump_alert') plus the per-rule webhook when set. Honors cooldown_seconds and
-// dedupes via user_alert_fires.last_event_id so the same graduation is never
-// delivered twice. Whale / launch / fee rules are evaluated client-side from the
-// live feed for immediate, tab-open feedback; graduation is the persisted,
-// cross-session channel because it's the event type recorded server-side.
-const ALERT_GRADS_PER_RUN = 50;
-const ALERT_DELIVER_CAP = 10;
-
-async function evaluateUserAlerts() {
- const report = { users: 0, delivered: 0, webhooks: 0, errors: 0 };
-
- let configs;
- try {
- configs = await sql`
- SELECT user_id, cooldown_seconds, webhook_url
- FROM user_alert_configs
- WHERE graduation = true
- `;
- } catch (e) {
- // Table not migrated yet — skip cleanly.
- return { skipped: 'alert_config_unavailable', detail: e?.message || String(e) };
- }
- if (!configs.length) return report;
-
- const grads = await sql`
- SELECT tx_signature, mint, name, symbol, amount_sol, market_cap_usd, seen_at
- FROM pumpfun_graduations
- WHERE seen_at > now() - interval '15 minutes'
- ORDER BY seen_at ASC
- LIMIT ${ALERT_GRADS_PER_RUN}
- `;
- if (!grads.length) return report;
-
- for (const cfg of configs) {
- report.users++;
- try {
- const [fire] = await sql`
- SELECT last_fired_at, last_event_id FROM user_alert_fires
- WHERE user_id = ${cfg.user_id} AND rule_type = 'graduation'
- `;
-
- // Cooldown gate.
- if (fire?.last_fired_at) {
- const sinceMs = Date.now() - new Date(fire.last_fired_at).getTime();
- if (sinceMs < (cfg.cooldown_seconds || 30) * 1000) continue;
- }
-
- // Only graduations newer than the last delivered event.
- let fresh = grads;
- if (fire?.last_event_id) {
- const idx = grads.findIndex((g) => g.tx_signature === fire.last_event_id);
- if (idx >= 0) fresh = grads.slice(idx + 1);
- }
- if (!fresh.length) continue;
-
- const toDeliver = fresh.slice(-ALERT_DELIVER_CAP);
- for (const g of toDeliver) {
- const payload = {
- kind: 'graduation',
- mint: g.mint,
- name: g.name,
- symbol: g.symbol,
- amount_sol: g.amount_sol != null ? Number(g.amount_sol) : null,
- market_cap_usd: g.market_cap_usd != null ? Number(g.market_cap_usd) : null,
- tx: g.tx_signature,
- at: g.seen_at,
- };
- try {
- await sql`
- insert into user_notifications (user_id, type, payload)
- values (${cfg.user_id}, 'pump_alert', ${JSON.stringify(payload)}::jsonb)
- `;
- report.delivered++;
- } catch {
- report.errors++;
- }
- if (cfg.webhook_url) {
- const ok = await postAlertWebhook(cfg.webhook_url, payload);
- if (ok) report.webhooks++;
- }
- }
-
- const latest = toDeliver[toDeliver.length - 1];
- await sql`
- insert into user_alert_fires (user_id, rule_type, last_fired_at, last_event_id)
- values (${cfg.user_id}, 'graduation', now(), ${latest.tx_signature})
- on conflict (user_id, rule_type) do update set
- last_fired_at = now(),
- last_event_id = excluded.last_event_id
- `;
- } catch (e) {
- report.errors++;
- console.error(
- '[pumpfun-monitor] alert eval failed for user',
- cfg.user_id,
- e?.message || e,
- );
- }
- }
-
- return report;
-}
-
-// SSRF-guarded webhook POST. Returns true on a 2xx delivery.
-async function postAlertWebhook(url, payload) {
- try {
- const resp = await fetchSafePublicUrl(
- url,
- {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ type: 'pump_alert', data: payload }),
- signal: AbortSignal.timeout(8000),
- },
- { allowHttp: false },
- );
- return resp.ok;
- } catch (e) {
- console.error('[pumpfun-monitor] webhook delivery failed:', e?.message || e);
- return false;
- }
-}
+// Pump dashboard alert rules are evaluated and delivered by the dedicated runner
+// module (api/_lib/pump-alert-runner.js), invoked as runPumpAlertRules() at the
+// top of handlePumpfunMonitor. It matches every enabled pump_alert_rules row
+// against the live pump.fun event stream (graduations, agent mints, prices,
+// whale buys), honors each rule's cooldown, dedupes, and fans matches out across
+// the in-app / webhook / Telegram delivery channels with per-channel isolation.
/** Map a single (stats, cursor) row to the attestation events to emit. */
function detectEvents(r) {
@@ -1568,6 +1451,43 @@ async function buybackLoadRelayer() {
return Keypair.fromSecretKey(Buffer.from(b64, 'base64'));
}
+/**
+ * Resolve the quote currency a coin's autonomous lanes (buyback, distribute) must
+ * operate in. A coin's vaults, swaps, and burns all settle in its quote asset:
+ * USDC for USDC-paired coins, native SOL (wSOL) for SOL-paired coins. The
+ * authoritative source is the on-chain bonding curve — the same field the trade
+ * builders read — so this stays correct even for coins launched before the
+ * `quote_mint` column existed (their DB value is null but their curve is not).
+ *
+ * Falls back to the recorded `dbQuoteMint`, then to USDC (the agent earn
+ * currency), when the curve can't be read — so a transient RPC miss never
+ * silently switches a USDC coin onto the SOL vault.
+ *
+ * @returns {Promise<{ currencyStr: string, quoteSymbol: 'SOL'|'USDC'|'OTHER', source: 'chain'|'db'|'fallback' }>}
+ */
+async function resolveCoinQuoteCurrency({ network, mint, dbQuoteMint = null }) {
+ const { resolveCustodialQuote } = await import('../_lib/pump-trade-args.js');
+ try {
+ const { bondingCurvePda, PUMP_SDK } = await import('@pump-fun/pump-sdk');
+ const info = await getConnection({ network }).getAccountInfo(
+ bondingCurvePda(solanaPubkey(mint)),
+ );
+ if (info) {
+ const bc = PUMP_SDK.decodeBondingCurve(info);
+ const q = resolveCustodialQuote(bc.quoteMint, network);
+ return { currencyStr: q.quoteMint, quoteSymbol: q.quoteSymbol, source: 'chain' };
+ }
+ } catch {
+ // fall through to the DB hint / USDC default below
+ }
+ if (dbQuoteMint) {
+ const q = resolveCustodialQuote(dbQuoteMint, network);
+ return { currencyStr: q.quoteMint, quoteSymbol: q.quoteSymbol, source: 'db' };
+ }
+ const usdc = network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;
+ return { currencyStr: usdc, quoteSymbol: 'USDC', source: 'fallback' };
+}
+
async function handleRunBuyback(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
@@ -1580,7 +1500,7 @@ async function handleRunBuyback(req, res) {
// legacy "always eligible, burn-only" behaviour via coalesce, so existing
// coins keep working until an owner opts into autopilot from /autopilot.
const mints = await sql`
- select m.id, m.mint, m.network, m.slippage_bps,
+ select m.id, m.mint, m.network, m.slippage_bps, m.quote_mint,
coalesce(ap.buyback_full_swap, m.full_swap) as full_swap,
coalesce(ap.buyback_min_atomics, 0) as buyback_min_atomics
from pump_agent_mints m
@@ -1592,7 +1512,15 @@ async function handleRunBuyback(req, res) {
const results = [];
for (const m of mints) {
- const currencyStr = m.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;
+ // Operate in the coin's quote asset — the currency its vault holds and its
+ // curve swaps. USDC coins buy back with USDC, SOL coins with SOL. Anything
+ // the lane can't operate in still records a run row below (never a silent
+ // no-op): empty vaults → 'skipped', build/swap errors → 'failed'.
+ const { currencyStr } = await resolveCoinQuoteCurrency({
+ network: m.network,
+ mint: m.mint,
+ dbQuoteMint: m.quote_mint,
+ });
const currency = solanaPubkey(currencyStr);
const fullSwap = m.full_swap === true;
const minAtomics = BigInt(m.buyback_min_atomics ?? 0);
@@ -2188,7 +2116,7 @@ async function handleRunDistributePayments(req, res) {
// Pick mints to consider: those with confirmed payments since last
// distribute run, or never run before.
const mints = await sql`
- select m.id, m.mint, m.network, m.buyback_bps,
+ select m.id, m.mint, m.network, m.buyback_bps, m.quote_mint,
coalesce(ap.distribute_min_atomics, 0) as distribute_min_atomics
from pump_agent_mints m
left join pump_autopilot ap on ap.mint_id = m.id
@@ -2211,7 +2139,16 @@ async function handleRunDistributePayments(req, res) {
const results = [];
for (const m of mints) {
- const currencyStr = m.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;
+ // Distribute the payment vault in the coin's quote asset so the whole
+ // earn → distribute → buyback → burn loop stays in one currency that the
+ // curve can swap. USDC coins distribute USDC, SOL coins SOL. Empty vaults
+ // record 'skipped' and SDK errors record 'failed' below — never a silent
+ // no-op.
+ const { currencyStr } = await resolveCoinQuoteCurrency({
+ network: m.network,
+ mint: m.mint,
+ dbQuoteMint: m.quote_mint,
+ });
const currency = solanaPubkey(currencyStr);
try {
diff --git a/api/erc8004/[action].js b/api/erc8004/[action].js
index 341ff909c..db0cfe1c9 100644
--- a/api/erc8004/[action].js
+++ b/api/erc8004/[action].js
@@ -12,13 +12,19 @@ import { PutObjectCommand } from '@aws-sdk/client-s3';
import { z } from 'zod';
import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { resolveOnChainAgent, SERVER_CHAIN_META } from '../_lib/onchain.js';
+import {
+ resolveOnChainAgent,
+ resolveLatestValidation,
+ invalidateValidationCache,
+ SERVER_CHAIN_META,
+} from '../_lib/onchain.js';
import { r2, publicUrl } from '../_lib/r2.js';
import { env } from '../_lib/env.js';
+import { attestValidation, AttestError } from '../_lib/validation-attest.js';
export default wrap(async (req, res) => {
const action = req.query?.action;
@@ -30,6 +36,10 @@ export default wrap(async (req, res) => {
return handleImport(req, res);
case 'pin':
return handlePin(req, res);
+ case 'validate':
+ return handleValidate(req, res);
+ case 'validation':
+ return handleValidationRead(req, res);
default:
return error(res, 404, 'not_found', 'unknown erc8004 action');
}
@@ -211,6 +221,156 @@ async function handleImport(req, res) {
});
}
+// ── validate (POST) ──────────────────────────────────────────────────────────
+// Run an agent's GLB through the platform glTF validator and record a signed
+// attestation on the ValidationRegistry. Re-runnable: each call records a fresh
+// attestation, so the badge reflects the latest GLB. Best-effort — config /
+// allow-list / undeployed-registry problems return a clear ops error and never
+// affect the agent's registration.
+
+const validateBodySchema = z.object({
+ chainId: z.number().int().positive().max(2_147_483_647),
+ agentId: agentIdSchema,
+ // Optional — when omitted we resolve the GLB from the index / on-chain manifest.
+ glbUrl: z.string().url().max(2048).optional(),
+});
+
+// AttestError.code → HTTP status. Config/precondition problems are 503 (the
+// platform must be wired), model/transport problems are 422/502.
+const ATTEST_STATUS = {
+ validator_key_not_configured: 503,
+ validation_registry_not_deployed: 503,
+ validator_not_allowlisted: 503,
+ no_rpc: 503,
+ unsupported_chain: 400,
+ invalid_glb_url: 422,
+ glb_fetch_failed: 502,
+ glb_too_large: 413,
+ registry_read_failed: 502,
+ record_failed: 502,
+};
+
+async function handleValidate(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ if (bearer && !hasScope(bearer.scope, 'avatars:write'))
+ return error(res, 403, 'insufficient_scope', 'avatars:write scope required');
+
+ const rl = await limits.registerIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = parse(validateBodySchema, await readJson(req));
+ const chainMeta = SERVER_CHAIN_META[body.chainId];
+ if (!chainMeta) return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);
+
+ // Resolve the GLB to validate: explicit > index row > on-chain manifest body.
+ let glbUrl = body.glbUrl || null;
+ if (!glbUrl) {
+ const [row] = await sql`
+ SELECT glb_url FROM erc8004_agents_index
+ WHERE chain_id = ${body.chainId} AND agent_id = ${body.agentId}
+ `;
+ glbUrl = row?.glb_url || null;
+ }
+ if (!glbUrl) {
+ const resolved = await resolveOnChainAgent({
+ chainId: body.chainId,
+ agentId: body.agentId,
+ fetchManifest: true,
+ timeoutMs: 5000,
+ }).catch(() => null);
+ glbUrl = resolved?.bodyURI || null;
+ }
+ if (!glbUrl) {
+ return error(res, 422, 'no_glb', 'no GLB found for this agent to validate');
+ }
+
+ const validatedAt = new Date().toISOString();
+ let result;
+ try {
+ result = await attestValidation({
+ chainId: body.chainId,
+ agentId: body.agentId,
+ glbUrl,
+ validatedAt,
+ });
+ } catch (err) {
+ const code = err instanceof AttestError ? err.code : 'attest_failed';
+ const status = ATTEST_STATUS[code] || 500;
+ // Record the ops error for visibility — best-effort, never blocks.
+ await sql`
+ UPDATE erc8004_agents_index
+ SET validation_error = ${code}, validation_at = now()
+ WHERE chain_id = ${body.chainId} AND agent_id = ${body.agentId}
+ `.catch(() => {});
+ return error(res, status, code, err.message);
+ }
+
+ // Persist the latest attestation to the index cache (best-effort) and bust the
+ // on-chain read cache so the badge reflects this attestation immediately.
+ await sql`
+ UPDATE erc8004_agents_index
+ SET validation_passed = ${result.passed},
+ validation_kind = ${result.kind},
+ validation_proof_hash = ${result.proofHash},
+ validation_proof_uri = ${result.proofURI},
+ validation_tx = ${result.txHash},
+ validator_address = ${result.validator.toLowerCase()},
+ validation_at = ${validatedAt},
+ validation_error = null
+ WHERE chain_id = ${body.chainId} AND agent_id = ${body.agentId}
+ `.catch(() => {});
+ await invalidateValidationCache({ chainId: body.chainId, agentId: body.agentId }).catch(() => {});
+
+ const explorerTx = `${chainMeta.explorer}/tx/${result.txHash}`;
+ return json(res, 200, {
+ ok: true,
+ validation: {
+ chainId: body.chainId,
+ agentId: body.agentId,
+ passed: result.passed,
+ kind: result.kind,
+ proofHash: result.proofHash,
+ proofURI: result.proofURI,
+ txHash: result.txHash,
+ txExplorer: explorerTx,
+ validator: result.validator,
+ validatedAt,
+ byteCheckSha256: result.sha256,
+ issues: result.report.issues,
+ },
+ });
+}
+
+// ── validation (GET) ─────────────────────────────────────────────────────────
+// Walletless read of the latest on-chain attestation — powers the "Validated"
+// badge on any surface without a wallet or RPC in the browser.
+
+async function handleValidationRead(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.pumpMetaIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const chainId = Number(req.query?.chainId);
+ const agentId = String(req.query?.agentId ?? '').trim();
+ if (!Number.isInteger(chainId) || chainId <= 0) {
+ return error(res, 400, 'bad_request', 'chainId is required');
+ }
+ if (!/^\d{1,78}$/.test(agentId)) {
+ return error(res, 400, 'bad_request', 'agentId must be a non-negative integer');
+ }
+
+ const validation = await resolveLatestValidation({ chainId, agentId });
+ res.setHeader('cache-control', 'public, max-age=30, s-maxage=60');
+ return json(res, 200, { validation });
+}
+
// ── pin ────────────────────────────────────────────────────────────────────
const ALLOWED = new Set([
diff --git a/api/erc8004/register-confirm.js b/api/erc8004/register-confirm.js
index c03c83a59..34a494929 100644
--- a/api/erc8004/register-confirm.js
+++ b/api/erc8004/register-confirm.js
@@ -15,6 +15,10 @@ const bodySchema = z.object({
agentId: z.union([z.string(), z.number()]).transform(String),
metadataUri: z.string().min(1),
ownerAddress: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
+ // Optional: when binding an EXISTING three.ws agent on-chain, the agent's
+ // UUID. After the mint is verified below we write the unified meta.onchain
+ // block onto that row so the agent profile shows the on-chain badge on reload.
+ agentDbId: z.string().uuid().optional(),
});
export default wrap(async (req, res) => {
@@ -51,9 +55,80 @@ export default wrap(async (req, res) => {
ON CONFLICT (chain_id, agent_id) DO NOTHING
`;
await enrichMetadata(body.chainId, onChainId, body.metadataUri).catch(() => {});
- return json(res, 200, { success: true, agentId: onChainId, chainId: body.chainId });
+
+ // When binding an existing three.ws agent, persist the unified on-chain block
+ // onto its agent_identities row. Owner-scoped: only the user who owns the row
+ // (or a bearer with avatars:write for their own row) may write it. The tx was
+ // just verified above (Registered event, agentId + owner match), so this is a
+ // trustworthy source for meta.onchain.
+ let bound = false;
+ if (body.agentDbId) {
+ const userId = session?.id || bearer?.userId || null;
+ if (userId) {
+ bound = await bindAgentOnchain({
+ agentDbId: body.agentDbId,
+ userId,
+ chainId: body.chainId,
+ registry: chain.registry,
+ onChainId,
+ ownerHex,
+ metadataUri: body.metadataUri,
+ txHash: body.txHash,
+ }).catch(() => false);
+ }
+ }
+
+ return json(res, 200, { success: true, agentId: onChainId, chainId: body.chainId, bound });
});
+/**
+ * Write the canonical meta.onchain block (per 2026-04-29-onchain-unified.sql)
+ * onto an owned agent_identities row. Last-write-wins on re-bind; merges into
+ * any existing meta. Returns true when a row was updated.
+ */
+async function bindAgentOnchain({
+ agentDbId,
+ userId,
+ chainId,
+ registry,
+ onChainId,
+ ownerHex,
+ metadataUri,
+ txHash,
+}) {
+ const [existing] = await sql`
+ SELECT id, meta FROM agent_identities
+ WHERE id = ${agentDbId} AND user_id = ${userId} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!existing) return false;
+
+ const onchain = {
+ chain: `eip155:${chainId}`,
+ family: 'evm',
+ tx_hash: txHash,
+ onchain_id: String(onChainId),
+ contract_or_mint: registry,
+ wallet: ownerHex,
+ metadata_uri: metadataUri,
+ confirmed_at: new Date().toISOString(),
+ };
+ const mergedMeta = { ...(existing.meta || {}), onchain };
+
+ await sql`
+ UPDATE agent_identities
+ SET meta = ${JSON.stringify(mergedMeta)}::jsonb,
+ wallet_address = ${ownerHex},
+ chain_id = ${chainId},
+ erc8004_agent_id = ${BigInt(onChainId)},
+ erc8004_registry = ${registry},
+ registration_cid = ${metadataUri},
+ updated_at = now()
+ WHERE id = ${agentDbId} AND user_id = ${userId}
+ `;
+ return true;
+}
+
async function rpcCall(urls, m, params) {
const urlList = Array.isArray(urls) ? urls : [urls];
let lastErr;
diff --git a/api/healthz.js b/api/healthz.js
index 96566cfac..acea61559 100644
--- a/api/healthz.js
+++ b/api/healthz.js
@@ -59,8 +59,7 @@ async function probeMonitor() {
SELECT count(*)::int AS graduations FROM pumpfun_graduations
`;
const [{ watches }] = await sql`
- SELECT count(*)::int AS watches FROM user_alert_configs
- WHERE graduation OR whale OR fees OR launch
+ SELECT count(*)::int AS watches FROM pump_alert_rules WHERE enabled
`;
const beatMs = beat?.last_beat_at ? new Date(beat.last_beat_at).getTime() : 0;
const fresh = beatMs > 0 && now - beatMs < HEARTBEAT_FRESH_MS;
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 9366f7135..9b9320fb3 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -95,7 +95,12 @@ import {
releaseSpend,
} from '../_lib/agent-spend-policy.js';
import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET, toUsdcAtomics } from '../payments/_config.js';
-import { classifyLaunchQuote, usdcMintFor } from '../_lib/pump-quote.js';
+import {
+ classifyLaunchQuote,
+ usdcMintFor,
+ tradeQuoteColumns,
+ walletQuoteDeltaAtomics,
+} from '../_lib/pump-quote.js';
import {
slippagePercentFromBps,
resolveTokenProgramForMintOwner,
@@ -496,7 +501,7 @@ async function handleBuyConfirm(req, res) {
const body = parse(buyConfirmSchema, await readJson(req));
const [mintRow] = await sql`
- select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
+ select id, quote_mint from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
`;
const mintId = mintRow?.id ?? null;
@@ -513,16 +518,37 @@ async function handleBuyConfirm(req, res) {
return error(res, 422, 'wallet_not_in_tx', 'wallet not in tx');
if (mintId) {
- // `sol_amount` is a lamports column — only set for SOL-paired buys. USDC
- // buys leave it null (no quote-amount column yet; see AUDIT follow-ups).
+ // Resolve the quote asset authoritatively from the coin's recorded pairing
+ // mint (NULL = SOL-paired), so a USDC buy never lands in the lamports
+ // column. `sol_amount` stays a SOL-only lamports field for legacy readers;
+ // `quote_amount` carries the spend in whichever quote's atomic units.
+ const { quote_mint, quote_symbol } = tradeQuoteColumns({
+ quoteMint: mintRow?.quote_mint,
+ network: body.network,
+ });
const lamports =
- body.sol && body.sol > 0 ? BigInt(Math.floor(body.sol * 1_000_000_000)) : null;
+ quote_symbol === 'SOL' && body.sol > 0
+ ? BigInt(Math.floor(body.sol * 1_000_000_000)).toString()
+ : null;
+ const quoteAmount =
+ quote_symbol === 'SOL'
+ ? lamports
+ : body.usdc_amount > 0
+ ? String(Math.round(body.usdc_amount * 1_000_000))
+ : walletQuoteDeltaAtomics({
+ tx,
+ wallet: body.wallet_address,
+ quoteSymbol: quote_symbol,
+ quoteMint: quote_mint,
+ });
await sql`
insert into pump_agent_trades
- (mint_id, user_id, wallet, direction, route, sol_amount, slippage_bps, tx_signature, network)
+ (mint_id, user_id, wallet, direction, route, sol_amount,
+ quote_mint, quote_symbol, quote_amount, slippage_bps, tx_signature, network)
values
(${mintId}, ${user.id}, ${body.wallet_address}, 'buy', ${body.route},
- ${lamports != null ? lamports.toString() : null}, ${body.slippage_bps ?? null}, ${body.tx_signature}, ${body.network})
+ ${lamports}, ${quote_mint}, ${quote_symbol}, ${quoteAmount},
+ ${body.slippage_bps ?? null}, ${body.tx_signature}, ${body.network})
on conflict (tx_signature, network) do nothing
`;
}
@@ -765,7 +791,7 @@ async function handleSellConfirm(req, res) {
const body = parse(sellConfirmSchema, await readJson(req));
const [mintRow] = await sql`
- select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
+ select id, quote_mint from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
`;
const mintId = mintRow?.id ?? null;
@@ -782,12 +808,29 @@ async function handleSellConfirm(req, res) {
return error(res, 422, 'wallet_not_in_tx', 'wallet not in tx');
if (mintId) {
+ // The sell-confirm payload only carries the token quantity, so derive the
+ // proceeds (quote received) from the verified tx's on-chain balance delta
+ // rather than trusting client input — real settled amount, not an estimate.
+ const { quote_mint, quote_symbol } = tradeQuoteColumns({
+ quoteMint: mintRow?.quote_mint,
+ network: body.network,
+ });
+ const quoteAmount = walletQuoteDeltaAtomics({
+ tx,
+ wallet: body.wallet_address,
+ quoteSymbol: quote_symbol,
+ quoteMint: quote_mint,
+ });
+ // Keep sol_amount in sync for SOL sells so legacy readers see proceeds too.
+ const lamports = quote_symbol === 'SOL' ? quoteAmount : null;
await sql`
insert into pump_agent_trades
- (mint_id, user_id, wallet, direction, route, token_amount, slippage_bps, tx_signature, network)
+ (mint_id, user_id, wallet, direction, route, sol_amount, token_amount,
+ quote_mint, quote_symbol, quote_amount, slippage_bps, tx_signature, network)
values
(${mintId}, ${user.id}, ${body.wallet_address}, 'sell', ${body.route},
- ${body.tokens}, ${body.slippage_bps ?? null}, ${body.tx_signature}, ${body.network})
+ ${lamports}, ${body.tokens}, ${quote_mint}, ${quote_symbol}, ${quoteAmount},
+ ${body.slippage_bps ?? null}, ${body.tx_signature}, ${body.network})
on conflict (tx_signature, network) do nothing
`;
}
@@ -2217,11 +2260,24 @@ async function handlePortfolio(req, res) {
const conn = solanaConnection(network);
const owner = new PublicKey(address);
- const [lamports, tokenResp, recentBuys] = await Promise.all([
+ const [lamports, tokenResp, tradeRows, recentBuys] = await Promise.all([
conn.getBalance(owner),
conn.getParsedTokenAccountsByOwner(owner, { programId: TOKEN_PROGRAM_ID }),
+ // Quote-aware cost basis from the trade ledger: net quote spent (buys −
+ // sells) per mint, in the quote asset's own atomic units, grouped by quote
+ // so SOL and USDC are never summed together.
sql`
- SELECT payload, created_at FROM agent_actions
+ SELECT pam.mint, t.quote_symbol,
+ COALESCE(SUM(CASE WHEN t.direction='buy' THEN t.quote_amount ELSE 0 END), 0)::text AS buy_quote,
+ COALESCE(SUM(CASE WHEN t.direction='sell' THEN t.quote_amount ELSE 0 END), 0)::text AS sell_quote
+ FROM pump_agent_trades t
+ JOIN pump_agent_mints pam ON pam.id = t.mint_id
+ WHERE t.wallet = ${address} AND t.network = ${network}
+ GROUP BY pam.mint, t.quote_symbol
+ `.catch(() => []),
+ // Legacy fallback for SOL coins whose buys predate the trade ledger.
+ sql`
+ SELECT payload FROM agent_actions
WHERE agent_id = ${agentId}
AND type IN ('pumpfun.buy', 'buy')
ORDER BY created_at DESC
@@ -2240,48 +2296,106 @@ async function handlePortfolio(req, res) {
})
.filter((h) => h.amount > 0);
- // Cost basis from recorded buys.
- const basisByMint = new Map();
+ // Atomic→UI divisor per quote asset (lamports for SOL, 6-dec for USDC).
+ const QUOTE_ATOMS = { SOL: 1e9, USDC: 1e6 };
+
+ // Cost basis + quote asset per mint from the quote-aware trade ledger.
+ const basisByMint = new Map(); // mint -> { quoteSymbol, costBasis }
+ for (const r of tradeRows) {
+ const quoteSymbol = r.quote_symbol || 'SOL';
+ const net = BigInt(r.buy_quote || '0') - BigInt(r.sell_quote || '0');
+ const div = QUOTE_ATOMS[quoteSymbol] ?? null;
+ basisByMint.set(r.mint, {
+ quoteSymbol,
+ costBasis: div != null ? Number(net) / div : null,
+ });
+ }
+ // Supplement SOL basis from legacy agent_actions only for mints with no ledger
+ // rows — keeps historical portfolios intact without double-counting.
for (const row of recentBuys) {
const p = row.payload || {};
- if (!p.mint) continue;
- const prev = basisByMint.get(p.mint) ?? { sol: 0, tokens: 0 };
- prev.sol += Number(p.amountSol) || 0;
- prev.tokens += Number(p.amountTokens) || 0;
+ if (!p.mint || basisByMint.has(p.mint)) continue;
+ const prev = basisByMint.get(p.mint) ?? { quoteSymbol: 'SOL', costBasis: 0 };
+ prev.costBasis = (prev.costBasis ?? 0) + (Number(p.amountSol) || 0);
basisByMint.set(p.mint, prev);
}
+ // Authoritative quote asset for held agent coins not seen in the ledger.
+ const unknownMints = holdings.map((h) => h.mint).filter((m) => !basisByMint.has(m));
+ const quoteByMint = new Map();
+ if (unknownMints.length) {
+ const mintRows = await sql`
+ SELECT mint, quote_mint FROM pump_agent_mints
+ WHERE network = ${network} AND mint = ANY(${unknownMints})
+ `.catch(() => []);
+ for (const r of mintRows) {
+ quoteByMint.set(r.mint, tradeQuoteColumns({ quoteMint: r.quote_mint, network }).quote_symbol);
+ }
+ }
+
// Live price per holding via the read-only pump-fun MCP (parallelized).
const rt = makeRuntime();
const priced = await Promise.all(
holdings.map(async (h) => {
- const [curve, basis] = [
- await rt
- .invoke('pump-fun.getBondingCurve', { mint: h.mint })
- .catch(() => ({ ok: false })),
- basisByMint.get(h.mint),
- ];
- const priceSol = curve?.ok ? (curve.data?.priceSol ?? curve.data?.price ?? null) : null;
- const valueSol = priceSol != null ? priceSol * h.amount : null;
- const costBasisSol = basis ? basis.sol : null;
- const unrealizedSol =
- valueSol != null && costBasisSol != null ? valueSol - costBasisSol : null;
+ const curve = await rt
+ .invoke('pump-fun.getBondingCurve', { mint: h.mint })
+ .catch(() => ({ ok: false }));
+ const basis = basisByMint.get(h.mint);
+ const quoteSymbol = basis?.quoteSymbol ?? quoteByMint.get(h.mint) ?? 'SOL';
+ // A bonding-curve price is quote-per-token in the coin's OWN quote unit
+ // (SOL/token for SOL-paired, USDC/token for USDC-paired), so value and
+ // cost basis are always expressed in the same currency.
+ const priceQuote = curve?.ok ? (curve.data?.priceSol ?? curve.data?.price ?? null) : null;
+ const valueQuote = priceQuote != null ? priceQuote * h.amount : null;
+ const costBasis = basis?.costBasis ?? null;
+ const unrealized =
+ valueQuote != null && costBasis != null ? valueQuote - costBasis : null;
+ const isSol = quoteSymbol === 'SOL';
return {
...h,
- priceSol,
- valueSol,
- costBasisSol,
- unrealizedPnlSol: unrealizedSol,
+ quoteSymbol,
+ priceQuote,
+ valueQuote,
+ costBasis,
+ unrealizedPnl: unrealized,
unrealizedPnlPct:
- unrealizedSol != null && costBasisSol > 0
- ? (unrealizedSol / costBasisSol) * 100
- : null,
+ unrealized != null && costBasis > 0 ? (unrealized / costBasis) * 100 : null,
+ // Backward-compat SOL-named fields, populated only for SOL-paired
+ // coins so existing consumers never read a USDC figure as SOL.
+ priceSol: isSol ? priceQuote : null,
+ valueSol: isSol ? valueQuote : null,
+ costBasisSol: isSol ? costBasis : null,
+ unrealizedPnlSol: isSol ? unrealized : null,
};
}),
);
- const totalValueSol = priced.reduce((s, p) => s + (p.valueSol ?? 0), 0);
- const totalCostBasisSol = priced.reduce((s, p) => s + (p.costBasisSol ?? 0), 0);
+ // Per-quote subtotals — the fix for summing mismatched units. Each quote
+ // asset (SOL, USDC, …) gets its own value / cost-basis / PnL totals.
+ const subtotals = {};
+ for (const p of priced) {
+ const s = (subtotals[p.quoteSymbol] ??= {
+ quoteSymbol: p.quoteSymbol,
+ positions: 0,
+ value: 0,
+ costBasis: 0,
+ unrealizedPnl: 0,
+ unrealizedPnlPct: null,
+ });
+ s.positions += 1;
+ s.value += p.valueQuote ?? 0;
+ s.costBasis += p.costBasis ?? 0;
+ }
+ for (const s of Object.values(subtotals)) {
+ s.unrealizedPnl = s.value - s.costBasis;
+ s.unrealizedPnlPct = s.costBasis > 0 ? (s.unrealizedPnl / s.costBasis) * 100 : null;
+ }
+
+ // Top-level SOL totals stay backward-compatible — now scoped to SOL-paired
+ // holdings only (no cross-unit summing).
+ const solSub = subtotals.SOL ?? { value: 0, costBasis: 0 };
+ const totalValueSol = solSub.value;
+ const totalCostBasisSol = solSub.costBasis;
const unrealizedPnlSol = totalValueSol - totalCostBasisSol;
return json(res, 200, {
@@ -2291,6 +2405,7 @@ async function handlePortfolio(req, res) {
lamports,
sol: lamports / LAMPORTS_PER_SOL,
holdings: priced,
+ subtotals,
totalValueSol,
totalCostBasisSol,
unrealizedPnlSol,
@@ -2962,8 +3077,24 @@ async function handleStrategyBacktest(req, res) {
const body = await readJson(req);
if (!body?.strategy) return error(res, 400, 'validation_error', 'strategy required');
+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
const rt = makeRuntime();
+
+ // Reject a semantically-broken spec up front with field-level issues, before
+ // sourcing mints or replaying — same validator the validate endpoint uses.
+ const vr = await rt.invoke('pump-fun-strategy.validateStrategy', {
+ strategy: body.strategy,
+ network,
+ mintInfo: await resolveStrategyMintInfo(body.strategy?.scan?.mints, network),
+ });
+ if (vr.data && !vr.data.valid) {
+ return error(res, 400, 'validation_error', vr.error || 'strategy is invalid', {
+ issues: vr.data.issues,
+ report: vr.data,
+ });
+ }
+
let mints;
try {
mints = await resolveStrategyMints(rt.invoke, body.strategy, body.mints, body.limit);
@@ -3067,6 +3198,25 @@ async function handleStrategyRun(req, res) {
const mode = body.mode === 'live' ? 'live' : 'simulate';
const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
+ // Pre-flight semantic validation BEFORE switching to SSE, so a broken spec
+ // (or a quote-asset mismatch on a listed coin) is rejected with a clean JSON
+ // error rather than streaming a doomed run. Same validator the validate
+ // endpoint and the runner use — they cannot disagree.
+ {
+ const mintInfo = await resolveStrategyMintInfo(body.strategy?.scan?.mints, network);
+ const vr = await makeRuntime().invoke('pump-fun-strategy.validateStrategy', {
+ strategy: body.strategy,
+ network,
+ mintInfo,
+ });
+ if (vr.data && !vr.data.valid) {
+ return error(res, 400, 'validation_error', vr.error || 'strategy is invalid', {
+ issues: vr.data.issues,
+ report: vr.data,
+ });
+ }
+ }
+
let wallet = null,
walletAddress = null,
agentMeta = null;
@@ -3232,6 +3382,33 @@ async function handleLiveStream(req, res) {
// ── strategy-validate ──────────────────────────────────────────────────────
+// Resolve authoritative agent-coin facts (existence + quote pairing) for the
+// mints a strategy explicitly lists. pump_agent_mints is the only place a
+// three.ws coin's quote asset is reliably known (the on-chain bonding curve
+// read does not surface it). Returns a map keyed by mint, or null on DB error
+// (the handler then falls back to an on-chain existence probe).
+async function resolveStrategyMintInfo(mints, network) {
+ const listed = Array.isArray(mints)
+ ? [...new Set(mints.filter((m) => typeof m === 'string' && m.trim()).map((m) => m.trim()))]
+ : [];
+ if (!listed.length) return null;
+ try {
+ const rows = await sql`
+ SELECT mint, quote_mint FROM pump_agent_mints
+ WHERE mint = ANY(${listed}) AND network = ${network}
+ `;
+ const info = {};
+ for (const row of rows) {
+ const q = classifyLaunchQuote({ quoteMint: row.quote_mint, network });
+ info[row.mint] = { isAgentCoin: true, quoteIsUsdc: q.isUsdc, quoteSymbol: q.label };
+ }
+ return info;
+ } catch (e) {
+ console.error('[strategy-validate] mint info lookup failed', e?.message);
+ return null;
+ }
+}
+
async function handleStrategyValidate(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['POST'])) return;
@@ -3243,11 +3420,29 @@ async function handleStrategyValidate(req, res) {
if (!body?.strategy || typeof body.strategy !== 'object') {
return error(res, 400, 'validation_error', 'strategy required');
}
+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
+
+ const mintInfo = await resolveStrategyMintInfo(body.strategy?.scan?.mints, network);
const rt = makeRuntime();
- const r = await rt.invoke('pump-fun-strategy.validateStrategy', { strategy: body.strategy });
- if (!r.ok) return error(res, 400, 'validation_error', r.error);
- return json(res, 200, { data: r.data });
+ const r = await rt.invoke('pump-fun-strategy.validateStrategy', {
+ strategy: body.strategy,
+ network,
+ mintInfo,
+ });
+ const report = r.data ?? {
+ valid: false,
+ issues: [{ level: 'error', field: 'strategy', code: 'validate_failed', message: r.error || 'validation failed' }],
+ errorCount: 1,
+ warningCount: 0,
+ };
+ if (!report.valid) {
+ return error(res, 400, 'validation_error', r.error || 'strategy is invalid', {
+ issues: report.issues,
+ report,
+ });
+ }
+ return json(res, 200, { data: report });
}
// ── channel-feed ──────────────────────────────────────────────────────────────
@@ -3431,16 +3626,39 @@ async function handleCoinTrades(req, res) {
}
const raw = Array.isArray(body) ? body : Array.isArray(body?.trades) ? body.trades : [];
const trades = raw
- .map((t) => ({
- tx: t.tx,
- timestamp: t.timestamp,
- user: t.userAddress || t.user || null,
- is_buy: String(t.type).toLowerCase() === 'buy',
- sol_amount: Number(t.amountSol),
- usd_amount: t.amountUsd != null ? Number(t.amountUsd) : null,
- price_usd: t.priceUsd != null ? Number(t.priceUsd) : null,
- }))
- .filter((t) => t.tx && isFinite(t.sol_amount) && t.sol_amount > 0);
+ .map((t) => {
+ const solAmount = Number(t.amountSol);
+ const usdAmount = t.amountUsd != null ? Number(t.amountUsd) : null;
+ // pump.fun v2 USDC-paired coins report the quote spend on amountQuote/
+ // amountUsdc rather than amountSol. Surface whichever quote the upstream
+ // used (with a stable symbol) so USDC trades are no longer silently
+ // dropped by a SOL-only filter or shown as a misleading 0 SOL.
+ const usdcRaw = t.amountQuote ?? t.amountUsdc ?? null;
+ const isUsdcQuote = usdcRaw != null && (!isFinite(solAmount) || solAmount === 0);
+ const quoteSymbol = isUsdcQuote ? 'USDC' : 'SOL';
+ const quoteAmount = isUsdcQuote
+ ? Number(usdcRaw)
+ : isFinite(solAmount)
+ ? solAmount
+ : null;
+ return {
+ tx: t.tx,
+ timestamp: t.timestamp,
+ user: t.userAddress || t.user || null,
+ is_buy: String(t.type).toLowerCase() === 'buy',
+ sol_amount: isFinite(solAmount) ? solAmount : null,
+ quote_symbol: quoteSymbol,
+ quote_amount: quoteAmount,
+ usd_amount: usdAmount,
+ price_usd: t.priceUsd != null ? Number(t.priceUsd) : null,
+ };
+ })
+ .filter(
+ (t) =>
+ t.tx &&
+ ((t.quote_amount != null && t.quote_amount > 0) ||
+ (t.usd_amount != null && t.usd_amount > 0)),
+ );
res.setHeader('cache-control', 'public, max-age=3');
return json(res, 200, { mint, trades });
}
diff --git a/contracts/agent-invocation/Anchor.toml b/contracts/agent-invocation/Anchor.toml
new file mode 100644
index 000000000..fe4c83756
--- /dev/null
+++ b/contracts/agent-invocation/Anchor.toml
@@ -0,0 +1,30 @@
+[toolchain]
+
+[features]
+resolver = "2"
+
+# Same program id on every cluster — it is the program keypair's pubkey, baked
+# into `declare_id!`. See DEPLOYMENT.md for deploy signatures + upgrade authority.
+[programs.localnet]
+agent_invocation = "AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo"
+
+[programs.devnet]
+agent_invocation = "AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo"
+
+[programs.mainnet]
+agent_invocation = "AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo"
+
+[registry]
+url = "https://api.apr.dev"
+
+[provider]
+cluster = "devnet"
+# Deploy/upgrade authority keypair — kept OUT of the repo (~/.config/solana,
+# mirrored to the secret manager as AGENT_INVOCATION_DEPLOY_AUTHORITY).
+wallet = "~/.config/solana/agent-invocation-deployer.json"
+
+[workspace]
+members = ["."]
+
+[scripts]
+smoke = "node ../../scripts/agent-invocation-smoke.mjs"
diff --git a/contracts/agent-invocation/Cargo.lock b/contracts/agent-invocation/Cargo.lock
new file mode 100644
index 000000000..ec23cfbbf
--- /dev/null
+++ b/contracts/agent-invocation/Cargo.lock
@@ -0,0 +1,2342 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "agent-invocation"
+version = "0.2.0"
+dependencies = [
+ "anchor-lang",
+]
+
+[[package]]
+name = "ahash"
+version = "0.8.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "version_check",
+ "zerocopy",
+]
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "anchor-attribute-access-control"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f70fd141a4d18adf11253026b32504f885447048c7494faf5fa83b01af9c0cf"
+dependencies = [
+ "anchor-syn",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "anchor-attribute-account"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "715a261c57c7679581e06f07a74fa2af874ac30f86bd8ea07cca4a7e5388a064"
+dependencies = [
+ "anchor-syn",
+ "bs58",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "anchor-attribute-constant"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "730d6df8ae120321c5c25e0779e61789e4b70dc8297102248902022f286102e4"
+dependencies = [
+ "anchor-syn",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "anchor-attribute-error"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27e6e449cc3a37b2880b74dcafb8e5a17b954c0e58e376432d7adc646fb333ef"
+dependencies = [
+ "anchor-syn",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "anchor-attribute-event"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7710e4c54adf485affcd9be9adec5ef8846d9c71d7f31e16ba86ff9fc1dd49f"
+dependencies = [
+ "anchor-syn",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "anchor-attribute-program"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05ecfd49b2aeadeb32f35262230db402abed76ce87e27562b34f61318b2ec83c"
+dependencies = [
+ "anchor-lang-idl",
+ "anchor-syn",
+ "anyhow",
+ "bs58",
+ "heck",
+ "proc-macro2",
+ "quote",
+ "serde_json",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "anchor-derive-accounts"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be89d160793a88495af462a7010b3978e48e30a630c91de47ce2c1d3cb7a6149"
+dependencies = [
+ "anchor-syn",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "anchor-derive-serde"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "abc6ee78acb7bfe0c2dd2abc677aaa4789c0281a0c0ef01dbf6fe85e0fd9e6e4"
+dependencies = [
+ "anchor-syn",
+ "borsh-derive-internal",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "anchor-derive-space"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "134a01c0703f6fd355a0e472c033f6f3e41fac1ef6e370b20c50f4c8d022cea7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "anchor-lang"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6bab117055905e930f762c196e08f861f8dfe7241b92cee46677a3b15561a0a"
+dependencies = [
+ "anchor-attribute-access-control",
+ "anchor-attribute-account",
+ "anchor-attribute-constant",
+ "anchor-attribute-error",
+ "anchor-attribute-event",
+ "anchor-attribute-program",
+ "anchor-derive-accounts",
+ "anchor-derive-serde",
+ "anchor-derive-space",
+ "anchor-lang-idl",
+ "base64 0.21.7",
+ "bincode",
+ "borsh 0.10.4",
+ "bytemuck",
+ "solana-program",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "anchor-lang-idl"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "308910c7570f3598e631648dd33ce1a6016cfcb019542667f696b0ffb37e7001"
+dependencies = [
+ "anchor-lang-idl-spec",
+ "anyhow",
+ "heck",
+ "regex",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+]
+
+[[package]]
+name = "anchor-lang-idl-spec"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2bdf143115440fe621bdac3a29a1f7472e09f6cd82b2aa569429a0c13f103838"
+dependencies = [
+ "anyhow",
+ "serde",
+]
+
+[[package]]
+name = "anchor-syn"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5dc7a6d90cc643df0ed2744862cdf180587d1e5d28936538c18fc8908489ed67"
+dependencies = [
+ "anyhow",
+ "bs58",
+ "cargo_toml",
+ "heck",
+ "proc-macro2",
+ "quote",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "syn 1.0.109",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
+
+[[package]]
+name = "arrayref"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
+
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "base64"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3441f0f7b02788e948e47f457ca01f1d7e6d92c693bc132c22b087d3141c03ff"
+
+[[package]]
+name = "base64"
+version = "0.21.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "bincode"
+version = "1.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "bitflags"
+version = "2.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
+
+[[package]]
+name = "blake3"
+version = "1.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0aa83c34e62843d924f905e0f5c866eb1dd6545fc4d719e803d9ba6030371fce"
+dependencies = [
+ "arrayref",
+ "arrayvec",
+ "cc",
+ "cfg-if",
+ "constant_time_eq",
+ "cpufeatures 0.3.0",
+ "digest 0.11.3",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "borsh"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "115e54d64eb62cdebad391c19efc9dce4981c690c85a33a12199d99bb9546fee"
+dependencies = [
+ "borsh-derive 0.10.4",
+ "hashbrown 0.13.2",
+]
+
+[[package]]
+name = "borsh"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfd1e3f8955a5d7de9fab72fc8373fade9fb8a703968cb200ae3dc6cf08e185a"
+dependencies = [
+ "borsh-derive 1.6.1",
+ "bytes",
+ "cfg_aliases",
+]
+
+[[package]]
+name = "borsh-derive"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "831213f80d9423998dd696e2c5345aba6be7a0bd8cd19e31c5243e13df1cef89"
+dependencies = [
+ "borsh-derive-internal",
+ "borsh-schema-derive-internal",
+ "proc-macro-crate 0.1.5",
+ "proc-macro2",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "borsh-derive"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfcfdc083699101d5a7965e49925975f2f55060f94f9a05e7187be95d530ca59"
+dependencies = [
+ "once_cell",
+ "proc-macro-crate 3.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "borsh-derive-internal"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65d6ba50644c98714aa2a70d13d7df3cd75cd2b523a2b452bf010443800976b3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "borsh-schema-derive-internal"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "276691d96f063427be83e6692b86148e488ebba9f48f77788724ca027ba3b6d4"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "bs58"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bv"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8834bb1d8ee5dc048ee3124f2c7c1afcc6bc9aed03f11e9dfd8c69470a5db340"
+dependencies = [
+ "feature-probe",
+ "serde",
+]
+
+[[package]]
+name = "bytemuck"
+version = "1.25.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"
+
+[[package]]
+name = "bytemuck_derive"
+version = "1.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "bytes"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
+
+[[package]]
+name = "cargo_toml"
+version = "0.19.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a98356df42a2eb1bd8f1793ae4ee4de48e384dd974ce5eac8eee802edb7492be"
+dependencies = [
+ "serde",
+ "toml 0.8.23",
+]
+
+[[package]]
+name = "cc"
+version = "1.2.64"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dad887fd958be91b5098c0248def011f4523ab786cd411be668777e55063501f"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
+
+[[package]]
+name = "cmov"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
+
+[[package]]
+name = "console_error_panic_hook"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
+dependencies = [
+ "cfg-if",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "console_log"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e89f72f65e8501878b8a004d5a1afb780987e2ce2b4532c562e367a72c57499f"
+dependencies = [
+ "log",
+ "web-sys",
+]
+
+[[package]]
+name = "constant_time_eq"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "ctutils"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
+dependencies = [
+ "cmov",
+]
+
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "curve25519-dalek-derive",
+ "digest 0.10.7",
+ "fiat-crypto",
+ "rand_core 0.6.4",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "digest"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer 0.10.4",
+ "crypto-common 0.1.7",
+]
+
+[[package]]
+name = "digest"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
+dependencies = [
+ "block-buffer 0.12.1",
+ "crypto-common 0.2.2",
+ "ctutils",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "feature-probe"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "835a3dc7d1ec9e75e2b5fb4ba75396837112d2060b03f7d43bc1897c7f7211da"
+
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
+
+[[package]]
+name = "five8"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a75b8549488b4715defcb0d8a8a1c1c76a80661b5fa106b4ca0e7fce59d7d875"
+dependencies = [
+ "five8_core",
+]
+
+[[package]]
+name = "five8_const"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26dec3da8bc3ef08f2c04f61eab298c3ab334523e55f076354d6d6f613799a7b"
+dependencies = [
+ "five8_core",
+]
+
+[[package]]
+name = "five8_core"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2551bf44bc5f776c15044b9b94153a00198be06743e262afaaa61f11ac7523a5"
+
+[[package]]
+name = "futures-core"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
+
+[[package]]
+name = "futures-task"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
+
+[[package]]
+name = "futures-util"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.1.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi 0.9.0+wasi-snapshot-preview1",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "wasi 0.11.1+wasi-snapshot-preview1",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e"
+dependencies = [
+ "ahash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "heck"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "js-sys"
+version = "0.3.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03d04c30968dffe80775bd4d7fb676131cd04a1fb46d2686dbffbaec2d9dfd31"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "keccak"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653"
+dependencies = [
+ "cpufeatures 0.2.17",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+
+[[package]]
+name = "libc"
+version = "0.2.186"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
+
+[[package]]
+name = "libsecp256k1"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9d220bc1feda2ac231cb78c3d26f27676b8cf82c96971f7aeef3d0cf2797c73"
+dependencies = [
+ "arrayref",
+ "base64 0.12.3",
+ "digest 0.9.0",
+ "libsecp256k1-core",
+ "libsecp256k1-gen-ecmult",
+ "libsecp256k1-gen-genmult",
+ "rand 0.7.3",
+ "serde",
+ "sha2 0.9.9",
+]
+
+[[package]]
+name = "libsecp256k1-core"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0f6ab710cec28cef759c5f18671a27dae2a5f952cdaaee1d8e2908cb2478a80"
+dependencies = [
+ "crunchy",
+ "digest 0.9.0",
+ "subtle",
+]
+
+[[package]]
+name = "libsecp256k1-gen-ecmult"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccab96b584d38fac86a83f07e659f0deafd0253dc096dab5a36d53efe653c5c3"
+dependencies = [
+ "libsecp256k1-core",
+]
+
+[[package]]
+name = "libsecp256k1-gen-genmult"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67abfe149395e3aa1c48a2beb32b068e2334402df8181f818d3aee2b304c4f5d"
+dependencies = [
+ "libsecp256k1-core",
+]
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "953f07c43838f8e6f9758cab68bf5bed85465e7587ebe0b823f1bcd81978ad3a"
+
+[[package]]
+name = "memchr"
+version = "2.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"
+
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "num-bigint"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-derive"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "num-integer"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "proc-macro-crate"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785"
+dependencies = [
+ "toml 0.5.11",
+]
+
+[[package]]
+name = "proc-macro-crate"
+version = "3.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
+dependencies = [
+ "toml_edit 0.25.12+spec-1.1.0",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "rand"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"
+dependencies = [
+ "getrandom 0.1.16",
+ "libc",
+ "rand_chacha 0.2.2",
+ "rand_core 0.5.1",
+ "rand_hc",
+]
+
+[[package]]
+name = "rand"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"
+dependencies = [
+ "libc",
+ "rand_chacha 0.3.1",
+ "rand_core 0.6.4",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.5.1",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.6.4",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"
+dependencies = [
+ "getrandom 0.1.16",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.17",
+]
+
+[[package]]
+name = "rand_hc"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c"
+dependencies = [
+ "rand_core 0.5.1",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "regex"
+version = "1.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_bytes"
+version = "0.11.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
+dependencies = [
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.150"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "sha2"
+version = "0.9.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800"
+dependencies = [
+ "block-buffer 0.9.0",
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest 0.9.0",
+ "opaque-debug",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest 0.10.7",
+]
+
+[[package]]
+name = "sha3"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874"
+dependencies = [
+ "digest 0.10.7",
+ "keccak",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.15.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
+
+[[package]]
+name = "solana-account"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f949fe4edaeaea78c844023bfc1c898e0b1f5a100f8a8d2d0f85d0a7b090258"
+dependencies = [
+ "solana-account-info",
+ "solana-clock",
+ "solana-instruction",
+ "solana-pubkey",
+ "solana-sdk-ids",
+]
+
+[[package]]
+name = "solana-account-info"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8f5152a288ef1912300fc6efa6c2d1f9bb55d9398eb6c72326360b8063987da"
+dependencies = [
+ "bincode",
+ "serde",
+ "solana-program-error",
+ "solana-program-memory",
+ "solana-pubkey",
+]
+
+[[package]]
+name = "solana-address-lookup-table-interface"
+version = "2.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1673f67efe870b64a65cb39e6194be5b26527691ce5922909939961a6e6b395"
+dependencies = [
+ "bincode",
+ "bytemuck",
+ "serde",
+ "serde_derive",
+ "solana-clock",
+ "solana-instruction",
+ "solana-pubkey",
+ "solana-sdk-ids",
+ "solana-slot-hashes",
+]
+
+[[package]]
+name = "solana-atomic-u64"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d52e52720efe60465b052b9e7445a01c17550666beec855cce66f44766697bc2"
+dependencies = [
+ "parking_lot",
+]
+
+[[package]]
+name = "solana-big-mod-exp"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75db7f2bbac3e62cfd139065d15bcda9e2428883ba61fc8d27ccb251081e7567"
+dependencies = [
+ "num-bigint",
+ "num-traits",
+ "solana-define-syscall",
+]
+
+[[package]]
+name = "solana-bincode"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19a3787b8cf9c9fe3dd360800e8b70982b9e5a8af9e11c354b6665dd4a003adc"
+dependencies = [
+ "bincode",
+ "serde",
+ "solana-instruction",
+]
+
+[[package]]
+name = "solana-blake3-hasher"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1a0801e25a1b31a14494fc80882a036be0ffd290efc4c2d640bfcca120a4672"
+dependencies = [
+ "blake3",
+ "solana-define-syscall",
+ "solana-hash",
+ "solana-sanitize",
+]
+
+[[package]]
+name = "solana-borsh"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "718333bcd0a1a7aed6655aa66bef8d7fb047944922b2d3a18f49cbc13e73d004"
+dependencies = [
+ "borsh 0.10.4",
+ "borsh 1.6.1",
+]
+
+[[package]]
+name = "solana-clock"
+version = "2.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8584296123df8fe229b95e2ebfd37ae637fe9db9b7d4dd677ac5a78e80dbfce"
+dependencies = [
+ "serde",
+ "serde_derive",
+ "solana-sdk-ids",
+ "solana-sdk-macro",
+ "solana-sysvar-id",
+]
+
+[[package]]
+name = "solana-cpi"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8dc71126edddc2ba014622fc32d0f5e2e78ec6c5a1e0eb511b85618c09e9ea11"
+dependencies = [
+ "solana-account-info",
+ "solana-define-syscall",
+ "solana-instruction",
+ "solana-program-error",
+ "solana-pubkey",
+ "solana-stable-layout",
+]
+
+[[package]]
+name = "solana-decode-error"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c781686a18db2f942e70913f7ca15dc120ec38dcab42ff7557db2c70c625a35"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "solana-define-syscall"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ae3e2abcf541c8122eafe9a625d4d194b4023c20adde1e251f94e056bb1aee2"
+
+[[package]]
+name = "solana-epoch-rewards"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "86b575d3dd323b9ea10bb6fe89bf6bf93e249b215ba8ed7f68f1a3633f384db7"
+dependencies = [
+ "serde",
+ "serde_derive",
+ "solana-hash",
+ "solana-sdk-ids",
+ "solana-sdk-macro",
+ "solana-sysvar-id",
+]
+
+[[package]]
+name = "solana-epoch-schedule"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3fce071fbddecc55d727b1d7ed16a629afe4f6e4c217bc8d00af3b785f6f67ed"
+dependencies = [
+ "serde",
+ "serde_derive",
+ "solana-sdk-ids",
+ "solana-sdk-macro",
+ "solana-sysvar-id",
+]
+
+[[package]]
+name = "solana-example-mocks"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "84461d56cbb8bb8d539347151e0525b53910102e4bced875d49d5139708e39d3"
+dependencies = [
+ "serde",
+ "serde_derive",
+ "solana-address-lookup-table-interface",
+ "solana-clock",
+ "solana-hash",
+ "solana-instruction",
+ "solana-keccak-hasher",
+ "solana-message",
+ "solana-nonce",
+ "solana-pubkey",
+ "solana-sdk-ids",
+ "solana-system-interface",
+ "thiserror 2.0.18",
+]
+
+[[package]]
+name = "solana-feature-gate-interface"
+version = "2.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43f5c5382b449e8e4e3016fb05e418c53d57782d8b5c30aa372fc265654b956d"
+dependencies = [
+ "bincode",
+ "serde",
+ "serde_derive",
+ "solana-account",
+ "solana-account-info",
+ "solana-instruction",
+ "solana-program-error",
+ "solana-pubkey",
+ "solana-rent",
+ "solana-sdk-ids",
+ "solana-system-interface",
+]
+
+[[package]]
+name = "solana-fee-calculator"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d89bc408da0fb3812bc3008189d148b4d3e08252c79ad810b245482a3f70cd8d"
+dependencies = [
+ "log",
+ "serde",
+ "serde_derive",
+]
+
+[[package]]
+name = "solana-hash"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5b96e9f0300fa287b545613f007dfe20043d7812bee255f418c1eb649c93b63"
+dependencies = [
+ "borsh 1.6.1",
+ "bytemuck",
+ "bytemuck_derive",
+ "five8",
+ "js-sys",
+ "serde",
+ "serde_derive",
+ "solana-atomic-u64",
+ "solana-sanitize",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "solana-instruction"
+version = "2.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bab5682934bd1f65f8d2c16f21cb532526fcc1a09f796e2cacdb091eee5774ad"
+dependencies = [
+ "bincode",
+ "borsh 1.6.1",
+ "getrandom 0.2.17",
+ "js-sys",
+ "num-traits",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "solana-define-syscall",
+ "solana-pubkey",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "solana-instructions-sysvar"
+version = "2.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e0e85a6fad5c2d0c4f5b91d34b8ca47118fc593af706e523cdbedf846a954f57"
+dependencies = [
+ "bitflags",
+ "solana-account-info",
+ "solana-instruction",
+ "solana-program-error",
+ "solana-pubkey",
+ "solana-sanitize",
+ "solana-sdk-ids",
+ "solana-serialize-utils",
+ "solana-sysvar-id",
+]
+
+[[package]]
+name = "solana-keccak-hasher"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7aeb957fbd42a451b99235df4942d96db7ef678e8d5061ef34c9b34cae12f79"
+dependencies = [
+ "sha3",
+ "solana-define-syscall",
+ "solana-hash",
+ "solana-sanitize",
+]
+
+[[package]]
+name = "solana-last-restart-slot"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a6360ac2fdc72e7463565cd256eedcf10d7ef0c28a1249d261ec168c1b55cdd"
+dependencies = [
+ "serde",
+ "serde_derive",
+ "solana-sdk-ids",
+ "solana-sdk-macro",
+ "solana-sysvar-id",
+]
+
+[[package]]
+name = "solana-loader-v2-interface"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8ab08006dad78ae7cd30df8eea0539e207d08d91eaefb3e1d49a446e1c49654"
+dependencies = [
+ "serde",
+ "serde_bytes",
+ "serde_derive",
+ "solana-instruction",
+ "solana-pubkey",
+ "solana-sdk-ids",
+]
+
+[[package]]
+name = "solana-loader-v3-interface"
+version = "5.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f7162a05b8b0773156b443bccd674ea78bb9aa406325b467ea78c06c99a63a2"
+dependencies = [
+ "serde",
+ "serde_bytes",
+ "serde_derive",
+ "solana-instruction",
+ "solana-pubkey",
+ "solana-sdk-ids",
+ "solana-system-interface",
+]
+
+[[package]]
+name = "solana-loader-v4-interface"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "706a777242f1f39a83e2a96a2a6cb034cb41169c6ecbee2cf09cb873d9659e7e"
+dependencies = [
+ "serde",
+ "serde_bytes",
+ "serde_derive",
+ "solana-instruction",
+ "solana-pubkey",
+ "solana-sdk-ids",
+ "solana-system-interface",
+]
+
+[[package]]
+name = "solana-message"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1796aabce376ff74bf89b78d268fa5e683d7d7a96a0a4e4813ec34de49d5314b"
+dependencies = [
+ "bincode",
+ "blake3",
+ "lazy_static",
+ "serde",
+ "serde_derive",
+ "solana-bincode",
+ "solana-hash",
+ "solana-instruction",
+ "solana-pubkey",
+ "solana-sanitize",
+ "solana-sdk-ids",
+ "solana-short-vec",
+ "solana-system-interface",
+ "solana-transaction-error",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "solana-msg"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f36a1a14399afaabc2781a1db09cb14ee4cc4ee5c7a5a3cfcc601811379a8092"
+dependencies = [
+ "solana-define-syscall",
+]
+
+[[package]]
+name = "solana-native-token"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61515b880c36974053dd499c0510066783f0cc6ac17def0c7ef2a244874cf4a9"
+
+[[package]]
+name = "solana-nonce"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "703e22eb185537e06204a5bd9d509b948f0066f2d1d814a6f475dafb3ddf1325"
+dependencies = [
+ "serde",
+ "serde_derive",
+ "solana-fee-calculator",
+ "solana-hash",
+ "solana-pubkey",
+ "solana-sha256-hasher",
+]
+
+[[package]]
+name = "solana-program"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "98eca145bd3545e2fbb07166e895370576e47a00a7d824e325390d33bf467210"
+dependencies = [
+ "bincode",
+ "blake3",
+ "borsh 0.10.4",
+ "borsh 1.6.1",
+ "bs58",
+ "bytemuck",
+ "console_error_panic_hook",
+ "console_log",
+ "getrandom 0.2.17",
+ "lazy_static",
+ "log",
+ "memoffset",
+ "num-bigint",
+ "num-derive",
+ "num-traits",
+ "rand 0.8.6",
+ "serde",
+ "serde_bytes",
+ "serde_derive",
+ "solana-account-info",
+ "solana-address-lookup-table-interface",
+ "solana-atomic-u64",
+ "solana-big-mod-exp",
+ "solana-bincode",
+ "solana-blake3-hasher",
+ "solana-borsh",
+ "solana-clock",
+ "solana-cpi",
+ "solana-decode-error",
+ "solana-define-syscall",
+ "solana-epoch-rewards",
+ "solana-epoch-schedule",
+ "solana-example-mocks",
+ "solana-feature-gate-interface",
+ "solana-fee-calculator",
+ "solana-hash",
+ "solana-instruction",
+ "solana-instructions-sysvar",
+ "solana-keccak-hasher",
+ "solana-last-restart-slot",
+ "solana-loader-v2-interface",
+ "solana-loader-v3-interface",
+ "solana-loader-v4-interface",
+ "solana-message",
+ "solana-msg",
+ "solana-native-token",
+ "solana-nonce",
+ "solana-program-entrypoint",
+ "solana-program-error",
+ "solana-program-memory",
+ "solana-program-option",
+ "solana-program-pack",
+ "solana-pubkey",
+ "solana-rent",
+ "solana-sanitize",
+ "solana-sdk-ids",
+ "solana-sdk-macro",
+ "solana-secp256k1-recover",
+ "solana-serde-varint",
+ "solana-serialize-utils",
+ "solana-sha256-hasher",
+ "solana-short-vec",
+ "solana-slot-hashes",
+ "solana-slot-history",
+ "solana-stable-layout",
+ "solana-stake-interface",
+ "solana-system-interface",
+ "solana-sysvar",
+ "solana-sysvar-id",
+ "solana-vote-interface",
+ "thiserror 2.0.18",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "solana-program-entrypoint"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32ce041b1a0ed275290a5008ee1a4a6c48f5054c8a3d78d313c08958a06aedbd"
+dependencies = [
+ "solana-account-info",
+ "solana-msg",
+ "solana-program-error",
+ "solana-pubkey",
+]
+
+[[package]]
+name = "solana-program-error"
+version = "2.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ee2e0217d642e2ea4bee237f37bd61bb02aec60da3647c48ff88f6556ade775"
+dependencies = [
+ "borsh 1.6.1",
+ "num-traits",
+ "serde",
+ "serde_derive",
+ "solana-decode-error",
+ "solana-instruction",
+ "solana-msg",
+ "solana-pubkey",
+]
+
+[[package]]
+name = "solana-program-memory"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a5426090c6f3fd6cfdc10685322fede9ca8e5af43cd6a59e98bfe4e91671712"
+dependencies = [
+ "solana-define-syscall",
+]
+
+[[package]]
+name = "solana-program-option"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc677a2e9bc616eda6dbdab834d463372b92848b2bfe4a1ed4e4b4adba3397d0"
+
+[[package]]
+name = "solana-program-pack"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "319f0ef15e6e12dc37c597faccb7d62525a509fec5f6975ecb9419efddeb277b"
+dependencies = [
+ "solana-program-error",
+]
+
+[[package]]
+name = "solana-pubkey"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b62adb9c3261a052ca1f999398c388f1daf558a1b492f60a6d9e64857db4ff1"
+dependencies = [
+ "borsh 0.10.4",
+ "borsh 1.6.1",
+ "bytemuck",
+ "bytemuck_derive",
+ "curve25519-dalek",
+ "five8",
+ "five8_const",
+ "getrandom 0.2.17",
+ "js-sys",
+ "num-traits",
+ "serde",
+ "serde_derive",
+ "solana-atomic-u64",
+ "solana-decode-error",
+ "solana-define-syscall",
+ "solana-sanitize",
+ "solana-sha256-hasher",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "solana-rent"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1aea8fdea9de98ca6e8c2da5827707fb3842833521b528a713810ca685d2480"
+dependencies = [
+ "serde",
+ "serde_derive",
+ "solana-sdk-ids",
+ "solana-sdk-macro",
+ "solana-sysvar-id",
+]
+
+[[package]]
+name = "solana-sanitize"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61f1bc1357b8188d9c4a3af3fc55276e56987265eb7ad073ae6f8180ee54cecf"
+
+[[package]]
+name = "solana-sdk-ids"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c5d8b9cc68d5c88b062a33e23a6466722467dde0035152d8fb1afbcdf350a5f"
+dependencies = [
+ "solana-pubkey",
+]
+
+[[package]]
+name = "solana-sdk-macro"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "86280da8b99d03560f6ab5aca9de2e38805681df34e0bb8f238e69b29433b9df"
+dependencies = [
+ "bs58",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "solana-secp256k1-recover"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baa3120b6cdaa270f39444f5093a90a7b03d296d362878f7a6991d6de3bbe496"
+dependencies = [
+ "libsecp256k1",
+ "solana-define-syscall",
+ "thiserror 2.0.18",
+]
+
+[[package]]
+name = "solana-serde-varint"
+version = "2.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a7e155eba458ecfb0107b98236088c3764a09ddf0201ec29e52a0be40857113"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "solana-serialize-utils"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "817a284b63197d2b27afdba829c5ab34231da4a9b4e763466a003c40ca4f535e"
+dependencies = [
+ "solana-instruction",
+ "solana-pubkey",
+ "solana-sanitize",
+]
+
+[[package]]
+name = "solana-sha256-hasher"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5aa3feb32c28765f6aa1ce8f3feac30936f16c5c3f7eb73d63a5b8f6f8ecdc44"
+dependencies = [
+ "sha2 0.10.9",
+ "solana-define-syscall",
+ "solana-hash",
+]
+
+[[package]]
+name = "solana-short-vec"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c54c66f19b9766a56fa0057d060de8378676cb64987533fa088861858fc5a69"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "solana-slot-hashes"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c8691982114513763e88d04094c9caa0376b867a29577939011331134c301ce"
+dependencies = [
+ "serde",
+ "serde_derive",
+ "solana-hash",
+ "solana-sdk-ids",
+ "solana-sysvar-id",
+]
+
+[[package]]
+name = "solana-slot-history"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97ccc1b2067ca22754d5283afb2b0126d61eae734fc616d23871b0943b0d935e"
+dependencies = [
+ "bv",
+ "serde",
+ "serde_derive",
+ "solana-sdk-ids",
+ "solana-sysvar-id",
+]
+
+[[package]]
+name = "solana-stable-layout"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f14f7d02af8f2bc1b5efeeae71bc1c2b7f0f65cd75bcc7d8180f2c762a57f54"
+dependencies = [
+ "solana-instruction",
+ "solana-pubkey",
+]
+
+[[package]]
+name = "solana-stake-interface"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5269e89fde216b4d7e1d1739cf5303f8398a1ff372a81232abbee80e554a838c"
+dependencies = [
+ "borsh 0.10.4",
+ "borsh 1.6.1",
+ "num-traits",
+ "serde",
+ "serde_derive",
+ "solana-clock",
+ "solana-cpi",
+ "solana-decode-error",
+ "solana-instruction",
+ "solana-program-error",
+ "solana-pubkey",
+ "solana-system-interface",
+ "solana-sysvar-id",
+]
+
+[[package]]
+name = "solana-system-interface"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94d7c18cb1a91c6be5f5a8ac9276a1d7c737e39a21beba9ea710ab4b9c63bc90"
+dependencies = [
+ "js-sys",
+ "num-traits",
+ "serde",
+ "serde_derive",
+ "solana-decode-error",
+ "solana-instruction",
+ "solana-pubkey",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "solana-sysvar"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8c3595f95069f3d90f275bb9bd235a1973c4d059028b0a7f81baca2703815db"
+dependencies = [
+ "base64 0.22.1",
+ "bincode",
+ "bytemuck",
+ "bytemuck_derive",
+ "lazy_static",
+ "serde",
+ "serde_derive",
+ "solana-account-info",
+ "solana-clock",
+ "solana-define-syscall",
+ "solana-epoch-rewards",
+ "solana-epoch-schedule",
+ "solana-fee-calculator",
+ "solana-hash",
+ "solana-instruction",
+ "solana-instructions-sysvar",
+ "solana-last-restart-slot",
+ "solana-program-entrypoint",
+ "solana-program-error",
+ "solana-program-memory",
+ "solana-pubkey",
+ "solana-rent",
+ "solana-sanitize",
+ "solana-sdk-ids",
+ "solana-sdk-macro",
+ "solana-slot-hashes",
+ "solana-slot-history",
+ "solana-stake-interface",
+ "solana-sysvar-id",
+]
+
+[[package]]
+name = "solana-sysvar-id"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5762b273d3325b047cfda250787f8d796d781746860d5d0a746ee29f3e8812c1"
+dependencies = [
+ "solana-pubkey",
+ "solana-sdk-ids",
+]
+
+[[package]]
+name = "solana-transaction-error"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "222a9dc8fdb61c6088baab34fc3a8b8473a03a7a5fd404ed8dd502fa79b67cb1"
+dependencies = [
+ "solana-instruction",
+ "solana-sanitize",
+]
+
+[[package]]
+name = "solana-vote-interface"
+version = "2.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b80d57478d6599d30acc31cc5ae7f93ec2361a06aefe8ea79bc81739a08af4c3"
+dependencies = [
+ "bincode",
+ "num-derive",
+ "num-traits",
+ "serde",
+ "serde_derive",
+ "solana-clock",
+ "solana-decode-error",
+ "solana-hash",
+ "solana-instruction",
+ "solana-pubkey",
+ "solana-rent",
+ "solana-sdk-ids",
+ "solana-serde-varint",
+ "solana-serialize-utils",
+ "solana-short-vec",
+ "solana-system-interface",
+]
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl 1.0.69",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
+dependencies = [
+ "thiserror-impl 2.0.18",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
+[[package]]
+name = "toml"
+version = "0.5.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "toml"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
+dependencies = [
+ "serde",
+ "serde_spanned",
+ "toml_datetime 0.6.11",
+ "toml_edit 0.22.27",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "1.1.1+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.22.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
+dependencies = [
+ "indexmap",
+ "serde",
+ "serde_spanned",
+ "toml_datetime 0.6.11",
+ "toml_write",
+ "winnow 0.7.15",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.25.12+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2153edc6955a6c354fad8f5efd38b6a8769bdccf9fe50f8e1329f81b0baa5d7"
+dependencies = [
+ "indexmap",
+ "toml_datetime 1.1.1+spec-1.1.0",
+ "toml_parser",
+ "winnow 1.0.3",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
+dependencies = [
+ "winnow 1.0.3",
+]
+
+[[package]]
+name = "toml_write"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "wasi"
+version = "0.9.0+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.125"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ddb3f79143bced6de84270411622a2699cee572fc0875aeaf1e7867cf9fca1a"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.125"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e21a184b13fb19e157296e2c46056aec9092264fab83e4ba59e68c61b323c3d"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.125"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fecefd9c35bd935a20fc3fc344b5f29138961e4f47fb03297d88f2587afb5ebd"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.125"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23939e44bb9a5d7576fa2b563dc2e136628f1224e88a8deed09e04858b77871f"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6430a72df5eb332242960fe84b3002a241163998241eb596d4f739b9757061d"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "winnow"
+version = "0.7.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "winnow"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+
+[[package]]
+name = "zmij"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
diff --git a/contracts/agent-invocation/src/lib.rs b/contracts/agent-invocation/src/lib.rs
index 4e403621c..3fc956318 100644
--- a/contracts/agent-invocation/src/lib.rs
+++ b/contracts/agent-invocation/src/lib.rs
@@ -1,6 +1,6 @@
use anchor_lang::prelude::*;
-declare_id!("CcdC7xDhQ9r2PoafbsfWVewcbuAYozECHJEXWe4ELnqR");
+declare_id!("AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo");
/// Max accepted length (bytes) for `skill_name`, bounding the size of the
/// emitted event and the compute spent formatting it.
diff --git a/data/changelog.json b/data/changelog.json
index 0624c7fc5..e34cf0cd6 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,40 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-15",
+ "title": "Agents can autonomously trade USDC-paired coins",
+ "summary": "An agent's own wallet can now buy and sell USDC-paired coins on its own — not just SOL ones. Until now the autonomous lanes (an agent's buy/sell endpoints, scheduled buybacks, and creator-fee distributions) assumed every coin priced in SOL, so on a USDC coin they would have built a SOL trade the market refuses. Now the agent reads each coin's real pairing straight from the chain and trades in the matching currency: a USDC coin is bought and sold in USDC, with the agent's USDC account opened automatically and its balance checked up front so a trade fails clearly instead of reverting on-chain. Buybacks and fee distributions follow the same rule — they run in the coin's own currency, and if a coin's setup genuinely can't support a run, it's recorded with the reason rather than silently skipped. Every trade is now logged with the exact quote asset and amount, so prices and volumes stay correct for USDC and SOL coins alike. SOL coins behave exactly as before.",
+ "tags": ["feature"],
+ "link": "/pump-dashboard"
+ },
+ {
+ "date": "2026-06-15",
+ "title": "Rate and vouch for Solana agents from their passport",
+ "summary": "Every Solana agent passport already showed its on-chain reputation — now you can add to it. A new \"Rate this agent\" panel lets anyone with a Solana wallet (Phantom or Solflare) leave a 1–5 score, with an optional public note, written on-chain as a signed attestation — no account needed. You can also back your rating with a SOL stake (from 0.001 SOL) sent to the agent's owner for an economically-weighted vouch. Submitting is guarded the obvious ways: you can't rate your own agent, scores are limited to 1–5, the minimum stake is enforced, and re-rating asks you to confirm before it updates your previous score. The moment your transaction confirms, the passport re-reads the chain on demand instead of waiting for the next indexing pass, so your rating shows up in the reputation summary within seconds.",
+ "tags": ["feature"],
+ "link": "/agent-passport.html"
+ },
+ {
+ "date": "2026-06-15",
+ "title": "Register an existing agent on-chain in one click",
+ "summary": "Any agent you already built can now be given an ERC-8004 on-chain identity straight from its profile — no re-entering its name, 3D model, voice, or skills. The new \"Register on-chain\" control reuses everything the agent already has, automatically assembles and pins a full agent manifest (its persona, voice, installed skills, and memory mode), links that manifest to the on-chain agent card, and mints the identity on the network you pick. Re-running it on the same network is a safe no-op, and your profile shows a live on-chain badge with explorer and agent-card links the moment it's done.",
+ "tags": ["feature"],
+ "link": "/agents"
+ },
+ {
+ "date": "2026-06-15",
+ "title": "The pump.fun graduations feed stays fresh around the clock",
+ "summary": "The recent-graduations feed and the graduation data behind pump.fun signals and MCP tools now refresh continuously in the background, instead of only updating while someone had the live feed open. A new scheduled job listens to the real pump.fun migration stream and records graduations as they happen, so the feed shows up-to-date tokens even after quiet periods. Graduation data is also served straight from our own live records, so it never silently falls back to an empty list.",
+ "tags": ["infra", "improvement"]
+ },
+ {
+ "date": "2026-06-15",
+ "title": "After you launch a coin, jump straight to viewing or managing it",
+ "summary": "The success screen you see right after launching a coin no longer dead-ends. Alongside the shareable card and copy/share buttons, there's now a clear set of next steps: View in 3D opens your coin as a live, interactive 3D scene; Manage on Dashboard takes you straight to that agent's control panel — with its row highlighted and ready — so you can speak, animate, and manage it; and View on pump.fun opens the coin on pump.fun. Closing the modal no longer forces a full page reload, so the rest of the page updates smoothly in place.",
+ "tags": ["improvement"],
+ "link": "/pump-dashboard"
+ },
{
"date": "2026-06-15",
"title": "three.ws now registers itself as an on-chain agent (ERC-8004)",
diff --git a/examples/skills/pump-fun-strategy/dsl.js b/examples/skills/pump-fun-strategy/dsl.js
index 02a156f87..be6ea30bd 100644
--- a/examples/skills/pump-fun-strategy/dsl.js
+++ b/examples/skills/pump-fun-strategy/dsl.js
@@ -71,6 +71,36 @@ export function compileStrategy(spec) {
};
}
+// ── Metric catalog ───────────────────────────────────────────────────────────
+// The explicit schema for predicate left-hand-sides. This is the single source
+// of truth for which paths a strategy may reference, the natural domain of each
+// (used to detect impossible thresholds), and the run contexts in which the
+// value actually exists:
+// - 'filter': the entry-candidate view (no open position yet).
+// - 'exit': the open-position view (has position.*).
+// buildView() below MUST stay in sync with this table — every populated path is
+// listed, and nothing is listed that buildView never populates. Keeping the two
+// together is what lets the validator promise that a strategy which validates
+// will run with the same meaning.
+//
+// domain: { min, max } — null means unbounded on that side. `integer` flags
+// counts (== on a fractional rhs is then impossible).
+export const METRICS = {
+ 'holders.total': { min: 0, max: null, integer: true, contexts: ['filter', 'exit'], label: 'holder count' },
+ 'holders.topHolderPct': { min: 0, max: 100, integer: false, contexts: ['filter', 'exit'], label: 'top-holder %' },
+ 'creator.rugCount': { min: 0, max: null, integer: true, contexts: ['filter', 'exit'], label: 'creator rug count' },
+ 'curve.graduationPct': { min: 0, max: 100, integer: false, contexts: ['filter', 'exit'], label: 'graduation %' },
+ 'curve.priceSol': { min: 0, max: null, integer: false, contexts: ['filter', 'exit'], label: 'price (SOL)' },
+ 'token.ageSec': { min: 0, max: null, integer: false, contexts: ['filter', 'exit'], label: 'token age (s)' },
+ 'token.marketCapSol': { min: 0, max: null, integer: false, contexts: ['filter', 'exit'], label: 'market cap (SOL)' },
+ 'position.pnlPct': { min: -100, max: null, integer: false, contexts: ['exit'], label: 'position PnL %' },
+ 'position.ageSec': { min: 0, max: null, integer: false, contexts: ['exit'], label: 'position age (s)' },
+ 'position.amountTokens': { min: 0, max: null, integer: false, contexts: ['exit'], label: 'position size (tokens)' },
+ 'position.entryPriceSol':{ min: 0, max: null, integer: false, contexts: ['exit'], label: 'entry price (SOL)' },
+};
+
+export const SCAN_KINDS = ['newTokens', 'trending', 'mintList'];
+
// Build the `view` object the predicates evaluate against. Pure: takes raw
// pump-fun-style payloads + (optional) position state.
export function buildView({ details, holders, creator, curve, position, trades }) {
@@ -109,3 +139,339 @@ export function buildView({ details, holders, creator, curve, position, trades }
}
return v;
}
+
+// ── Semantic validation ──────────────────────────────────────────────────────
+// validateStrategySpec is pure: structure + predicate-path + numeric-domain +
+// cross-rule reachability analysis, with no I/O. It is the shared gate run by
+// the validate endpoint, runStrategy, and backtestStrategy so the three can
+// never disagree about whether a spec is operationally sound. Live checks that
+// need the chain or the DB (mint existence, quote-asset pairing) layer on top in
+// the handler/endpoint — they are not part of this pure function.
+//
+// Returns { issues, meta } where each issue is
+// { level: 'error' | 'warning' | 'info', field, code, message }
+// An 'error' means the strategy is operationally broken and must not run.
+
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+function isFiniteNum(n) {
+ return typeof n === 'number' && Number.isFinite(n);
+}
+
+// Classify a single `<path> <op> <rhs>` predicate against a metric's domain.
+function classifyThreshold(metric, op, rhs) {
+ const { min, max, integer } = metric;
+ const hasMin = min != null;
+ const hasMax = max != null;
+ let impossible = false;
+ let alwaysTrue = false;
+ switch (op) {
+ case '>':
+ if (hasMax && rhs >= max) impossible = true;
+ else if (hasMin && rhs < min) alwaysTrue = true;
+ break;
+ case '>=':
+ if (hasMax && rhs > max) impossible = true;
+ else if (hasMin && rhs <= min) alwaysTrue = true;
+ break;
+ case '<':
+ if (hasMin && rhs <= min) impossible = true;
+ else if (hasMax && rhs > max) alwaysTrue = true;
+ break;
+ case '<=':
+ if (hasMin && rhs < min) impossible = true;
+ else if (hasMax && rhs >= max) alwaysTrue = true;
+ break;
+ case '==':
+ if ((hasMin && rhs < min) || (hasMax && rhs > max) || (integer && !Number.isInteger(rhs)))
+ impossible = true;
+ break;
+ // '!=' is satisfiable across any of our ranged metrics.
+ }
+ return { impossible, alwaysTrue };
+}
+
+// Detect filters on the same path whose intersection is empty (the strategy
+// could never enter). Only inspects individually-satisfiable numeric filters.
+function detectFilterContradictions(parsed, issues) {
+ const byPath = new Map();
+ for (const p of parsed) {
+ if (!byPath.has(p.pred.lhs)) byPath.set(p.pred.lhs, []);
+ byPath.get(p.pred.lhs).push(p);
+ }
+ for (const [path, list] of byPath) {
+ if (list.length < 2) continue;
+ const metric = METRICS[path];
+ let lo = { v: metric.min ?? -Infinity, incl: true };
+ let hi = { v: metric.max ?? Infinity, incl: true };
+ const eqs = [];
+ for (const { pred } of list) {
+ const { op, rhs } = pred;
+ if (op === '>') lo = rhs > lo.v ? { v: rhs, incl: false } : rhs === lo.v ? { v: rhs, incl: false } : lo;
+ else if (op === '>=') lo = rhs > lo.v ? { v: rhs, incl: true } : lo;
+ else if (op === '<') hi = rhs < hi.v ? { v: rhs, incl: false } : rhs === hi.v ? { v: rhs, incl: false } : hi;
+ else if (op === '<=') hi = rhs < hi.v ? { v: rhs, incl: true } : hi;
+ else if (op === '==') eqs.push(rhs);
+ }
+ const sources = list.map((p) => p.pred.src);
+ const within = (e) =>
+ (e > lo.v || (e === lo.v && lo.incl)) && (e < hi.v || (e === hi.v && hi.incl));
+ let empty = false;
+ if (eqs.length) {
+ if (new Set(eqs).size > 1) empty = true;
+ else if (!within(eqs[0])) empty = true;
+ } else if (lo.v > hi.v) {
+ empty = true;
+ } else if (lo.v === hi.v && (!lo.incl || !hi.incl)) {
+ empty = true;
+ }
+ if (empty) {
+ issues.push({
+ level: 'error',
+ field: list[0].field,
+ code: 'contradictory_filters',
+ message: `Filters on ${metric.label} (${path}) can never be true together: ${sources.join(' AND ')}. The strategy would never enter a position.`,
+ });
+ }
+ }
+}
+
+// Exits are evaluated top-down and the first match wins. Flag any later rule
+// that an earlier rule on the same path always pre-empts.
+function detectShadowedExits(parsed, issues) {
+ for (let j = 0; j < parsed.length; j++) {
+ for (let i = 0; i < j; i++) {
+ const a = parsed[i].pred;
+ const b = parsed[j].pred;
+ if (a.lhs !== b.lhs) continue;
+ const aUp = a.op === '>' || a.op === '>=';
+ const bUp = b.op === '>' || b.op === '>=';
+ const aDown = a.op === '<' || a.op === '<=';
+ const bDown = b.op === '<' || b.op === '<=';
+ const shadowed = (aUp && bUp && a.rhs <= b.rhs) || (aDown && bDown && a.rhs >= b.rhs);
+ if (shadowed) {
+ issues.push({
+ level: 'warning',
+ field: `exit[${parsed[j].idx}]`,
+ code: 'shadowed_exit',
+ message: `Exit rule "${b.src}" is unreachable — the earlier rule "${a.src}" always matches first (exits are checked top-down, first match wins). Order exits most-specific first.`,
+ });
+ break;
+ }
+ }
+ }
+}
+
+// Validate + classify a single predicate string for the given context. Returns
+// the parsed predicate (or null if it could not be parsed / is unusable).
+function checkPredicate(src, context, field, issues) {
+ if (typeof src !== 'string') {
+ issues.push({ level: 'error', field, code: 'bad_predicate_type', message: `${field} must be a predicate string like "holders.total > 50".` });
+ return null;
+ }
+ let pred;
+ try {
+ pred = parsePredicate(src);
+ } catch (e) {
+ issues.push({ level: 'error', field, code: 'unparseable_predicate', message: `${field}: ${e.message}. Expected "<path> <op> <number>", op one of > >= < <= == !=.` });
+ return null;
+ }
+ const metric = METRICS[pred.lhs];
+ if (!metric) {
+ const known = Object.keys(METRICS).join(', ');
+ issues.push({ level: 'error', field, code: 'unknown_path', message: `${field}: "${pred.lhs}" is not a recognized metric. A typo silently evaluates to false at runtime. Valid paths: ${known}.` });
+ return null;
+ }
+ if (!metric.contexts.includes(context)) {
+ issues.push({ level: 'error', field, code: 'path_unavailable_in_context', message: `${field}: "${pred.lhs}" is only available in ${metric.contexts.join('/')} rules. ${context === 'filter' ? 'No position exists when filters run, so this can never be true and the strategy would never enter.' : `It is not populated in ${context} rules.`}` });
+ return null;
+ }
+ const { impossible, alwaysTrue } = classifyThreshold(metric, pred.op, pred.rhs);
+ if (impossible) {
+ issues.push({ level: 'error', field, code: 'impossible_threshold', message: `${field}: "${src}" can never be true — ${metric.label} is bounded to [${metric.min ?? '-∞'}, ${metric.max ?? '∞'}]${metric.integer ? ' (whole numbers)' : ''}.` });
+ return null;
+ }
+ if (alwaysTrue) {
+ issues.push({ level: 'warning', field, code: context === 'exit' ? 'exit_always_true' : 'redundant_filter', message: context === 'exit' ? `${field}: "${src}" is always true — this exit fires on the first tick, closing the position immediately.` : `${field}: "${src}" is always true for ${metric.label} and has no filtering effect.` });
+ }
+ return pred;
+}
+
+export function validateStrategySpec(spec) {
+ const issues = [];
+ const meta = {
+ scanKind: null,
+ mintList: [],
+ filterCount: 0,
+ exitCount: 0,
+ denominatedQuote: 'SOL',
+ effectivePerTradeSol: null,
+ sessionSpendCapSol: null,
+ filters: [],
+ exits: [],
+ summary: '',
+ };
+
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) {
+ issues.push({ level: 'error', field: 'strategy', code: 'not_an_object', message: 'strategy must be a JSON object.' });
+ return { issues, meta };
+ }
+
+ // ── scan ──
+ const scan = spec.scan;
+ if (!scan || typeof scan !== 'object' || Array.isArray(scan)) {
+ issues.push({ level: 'error', field: 'scan', code: 'scan_required', message: 'strategy.scan is required and must be an object: { kind, ... }.' });
+ } else {
+ meta.scanKind = scan.kind;
+ if (!SCAN_KINDS.includes(scan.kind)) {
+ issues.push({ level: 'error', field: 'scan.kind', code: 'bad_scan_kind', message: `scan.kind must be one of ${SCAN_KINDS.join(', ')} (got ${JSON.stringify(scan.kind)}).` });
+ }
+ if (scan.kind === 'mintList') {
+ if (!Array.isArray(scan.mints) || scan.mints.length === 0) {
+ issues.push({ level: 'error', field: 'scan.mints', code: 'empty_mint_list', message: 'scan.kind "mintList" requires a non-empty scan.mints array.' });
+ } else {
+ scan.mints.forEach((m, i) => {
+ if (typeof m !== 'string' || !m.trim()) {
+ issues.push({ level: 'error', field: `scan.mints[${i}]`, code: 'bad_mint', message: `scan.mints[${i}] must be a non-empty mint address string.` });
+ } else {
+ meta.mintList.push(m.trim());
+ if (!BASE58_RE.test(m.trim())) {
+ issues.push({ level: 'warning', field: `scan.mints[${i}]`, code: 'malformed_mint', message: `scan.mints[${i}] "${m}" does not look like a base58 Solana mint (32–44 chars); it will likely fail to resolve at run time.` });
+ }
+ }
+ });
+ }
+ }
+ if (scan.limit != null) {
+ if (!isFiniteNum(scan.limit) || scan.limit < 1 || !Number.isInteger(scan.limit)) {
+ issues.push({ level: 'error', field: 'scan.limit', code: 'bad_limit', message: 'scan.limit must be a positive integer.' });
+ } else if (scan.limit > 100) {
+ issues.push({ level: 'warning', field: 'scan.limit', code: 'large_limit', message: 'scan.limit above 100 is clamped by the upstream feed; lower it to stay predictable.' });
+ }
+ }
+ }
+
+ // ── entry ──
+ const entry = spec.entry;
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
+ issues.push({ level: 'error', field: 'entry', code: 'entry_required', message: 'strategy.entry is required: { side: "buy", amountSol }.' });
+ } else {
+ if (entry.side !== 'buy') {
+ issues.push({ level: 'error', field: 'entry.side', code: 'bad_entry_side', message: `entry.side must be "buy" (got ${JSON.stringify(entry.side)}). Exits are the only sell path.` });
+ }
+ if (!isFiniteNum(entry.amountSol) || entry.amountSol <= 0) {
+ issues.push({ level: 'error', field: 'entry.amountSol', code: 'bad_amount', message: 'entry.amountSol must be a positive number — it is the SOL spent per entry.' });
+ } else {
+ meta.effectivePerTradeSol = entry.amountSol;
+ if (entry.amountSol > 10) {
+ issues.push({ level: 'warning', field: 'entry.amountSol', code: 'large_entry', message: `entry.amountSol of ${entry.amountSol} SOL per trade is unusually large — confirm this is intended.` });
+ }
+ }
+ if (entry.slippageBps != null && (!Number.isInteger(entry.slippageBps) || entry.slippageBps < 0 || entry.slippageBps > 10000)) {
+ issues.push({ level: 'error', field: 'entry.slippageBps', code: 'bad_slippage', message: 'entry.slippageBps must be an integer between 0 and 10000 (basis points).' });
+ }
+ }
+
+ // ── filters ──
+ const parsedFilters = [];
+ if (spec.filters != null) {
+ if (!Array.isArray(spec.filters)) {
+ issues.push({ level: 'error', field: 'filters', code: 'bad_filters', message: 'strategy.filters must be an array of predicate strings.' });
+ } else {
+ meta.filterCount = spec.filters.length;
+ spec.filters.forEach((src, i) => {
+ const field = `filters[${i}]`;
+ const pred = checkPredicate(src, 'filter', field, issues);
+ if (pred) {
+ meta.filters.push(pred.src);
+ parsedFilters.push({ pred, field });
+ }
+ });
+ detectFilterContradictions(parsedFilters, issues);
+ }
+ }
+
+ // ── exits ──
+ const parsedExits = [];
+ if (spec.exit != null) {
+ if (!Array.isArray(spec.exit)) {
+ issues.push({ level: 'error', field: 'exit', code: 'bad_exit', message: 'strategy.exit must be an array of { if, do } rules.' });
+ } else {
+ meta.exitCount = spec.exit.length;
+ spec.exit.forEach((rule, i) => {
+ if (!rule || typeof rule !== 'object') {
+ issues.push({ level: 'error', field: `exit[${i}]`, code: 'bad_exit_rule', message: `exit[${i}] must be an object { if, do }.` });
+ return;
+ }
+ const pred = checkPredicate(rule.if, 'exit', `exit[${i}].if`, issues);
+ const action = rule.do;
+ if (!action || typeof action !== 'object') {
+ issues.push({ level: 'error', field: `exit[${i}].do`, code: 'bad_exit_action', message: `exit[${i}].do must be an object { side: "sell", percent | amountTokens }.` });
+ } else {
+ if (action.side !== 'sell') {
+ issues.push({ level: 'error', field: `exit[${i}].do.side`, code: 'bad_exit_side', message: `exit[${i}].do.side must be "sell".` });
+ }
+ const hasPct = action.percent != null;
+ const hasTok = action.amountTokens != null;
+ if (hasPct === hasTok) {
+ issues.push({ level: 'error', field: `exit[${i}].do`, code: 'bad_exit_size', message: `exit[${i}].do must specify exactly one of percent (1–100) or amountTokens.` });
+ } else if (hasPct && (!isFiniteNum(action.percent) || action.percent <= 0 || action.percent > 100)) {
+ issues.push({ level: 'error', field: `exit[${i}].do.percent`, code: 'bad_exit_percent', message: `exit[${i}].do.percent must be a number in (0, 100].` });
+ } else if (hasTok && (!isFiniteNum(action.amountTokens) || action.amountTokens <= 0)) {
+ issues.push({ level: 'error', field: `exit[${i}].do.amountTokens`, code: 'bad_exit_tokens', message: `exit[${i}].do.amountTokens must be a positive number.` });
+ }
+ }
+ if (pred) {
+ meta.exits.push({ if: pred.src, do: action });
+ parsedExits.push({ pred, idx: i, src: pred.src });
+ }
+ });
+ detectShadowedExits(parsedExits, issues);
+ }
+ }
+
+ // ── caps ──
+ const caps = spec.caps;
+ if (caps != null) {
+ if (typeof caps !== 'object' || Array.isArray(caps)) {
+ issues.push({ level: 'error', field: 'caps', code: 'bad_caps', message: 'strategy.caps must be an object.' });
+ } else {
+ if (caps.sessionSpendCapSol != null) {
+ if (!isFiniteNum(caps.sessionSpendCapSol) || caps.sessionSpendCapSol <= 0) {
+ issues.push({ level: 'error', field: 'caps.sessionSpendCapSol', code: 'bad_session_cap', message: 'caps.sessionSpendCapSol must be a positive number of SOL.' });
+ } else {
+ meta.sessionSpendCapSol = caps.sessionSpendCapSol;
+ }
+ }
+ if (caps.maxOpenPositions != null && (!Number.isInteger(caps.maxOpenPositions) || caps.maxOpenPositions < 1)) {
+ issues.push({ level: 'error', field: 'caps.maxOpenPositions', code: 'bad_max_positions', message: 'caps.maxOpenPositions must be a positive integer (≥ 1).' });
+ }
+ if (caps.perTradeSol != null) {
+ if (!isFiniteNum(caps.perTradeSol) || caps.perTradeSol <= 0) {
+ issues.push({ level: 'error', field: 'caps.perTradeSol', code: 'bad_per_trade', message: 'caps.perTradeSol must be a positive number of SOL.' });
+ } else if (meta.effectivePerTradeSol != null && caps.perTradeSol !== meta.effectivePerTradeSol) {
+ issues.push({ level: 'warning', field: 'caps.perTradeSol', code: 'per_trade_ignored', message: `caps.perTradeSol (${caps.perTradeSol}) is not used at run time — entry.amountSol (${meta.effectivePerTradeSol}) is the per-trade size. Align them to avoid confusion.` });
+ }
+ }
+ // The real gate in the runner is `spent + perTrade <= cap`.
+ if (meta.effectivePerTradeSol != null && meta.sessionSpendCapSol != null && meta.effectivePerTradeSol > meta.sessionSpendCapSol) {
+ issues.push({ level: 'error', field: 'caps.sessionSpendCapSol', code: 'cap_below_per_trade', message: `caps.sessionSpendCapSol (${meta.sessionSpendCapSol}) is smaller than the per-trade size entry.amountSol (${meta.effectivePerTradeSol}) — the strategy can never place a trade.` });
+ }
+ }
+ }
+
+ meta.summary = [
+ meta.scanKind ? `scan: ${meta.scanKind}` : null,
+ `${meta.filterCount} filter${meta.filterCount === 1 ? '' : 's'}`,
+ `${meta.exitCount} exit${meta.exitCount === 1 ? '' : 's'}`,
+ meta.effectivePerTradeSol != null ? `${meta.effectivePerTradeSol} SOL/trade` : null,
+ ].filter(Boolean).join(' · ');
+
+ return { issues, meta };
+}
+
+// Convenience: the fatal subset. Used by runStrategy/backtestStrategy as their
+// pre-flight gate so a broken spec fails before any RPC or signing.
+export function strategyErrors(spec) {
+ return validateStrategySpec(spec).issues.filter((i) => i.level === 'error');
+}
diff --git a/examples/skills/pump-fun-strategy/handlers.js b/examples/skills/pump-fun-strategy/handlers.js
index 733939d39..6bb90b799 100644
--- a/examples/skills/pump-fun-strategy/handlers.js
+++ b/examples/skills/pump-fun-strategy/handlers.js
@@ -2,31 +2,108 @@
// in dsl.js is the single source of truth: live runs and backtests share it,
// so a backtest is a faithful preview of a live run.
-import { compileStrategy, buildView, parsePredicate, evalPredicate } from './dsl.js';
+import {
+ compileStrategy,
+ buildView,
+ parsePredicate,
+ evalPredicate,
+ validateStrategySpec,
+ strategyErrors,
+} from './dsl.js';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+// Patterns in a read-MCP error that mean a mint definitively does not exist
+// (as opposed to a transient upstream/RPC failure, which must NOT fail-closed
+// a structurally-valid strategy).
+const MINT_MISSING_RE = /not found|invalid mint|no .*found|account not found|does not exist/i;
+
async function call(ctx, tool, args) {
const res = await ctx.skills.invoke(tool, args);
if (!res?.ok) throw new Error(`${tool}: ${res?.error ?? 'unknown'}`);
return res.data;
}
-export async function validateStrategy({ strategy }) {
- try {
- const compiled = compileStrategy(strategy);
- return {
- ok: true,
- data: {
- filterCount: compiled.filters.length,
- exitCount: compiled.exits.length,
- filters: compiled.filters.map((p) => p.src),
- exits: compiled.exits.map((e) => ({ if: e.when.src, do: e.action })),
- },
- };
- } catch (e) {
- return { ok: false, error: e.message };
+// validateStrategy — genuine semantic validation, not a syntax pass.
+//
+// Layer 1 (pure, always): validateStrategySpec — structure, predicate paths,
+// numeric domains, contradictory/unreachable rules, cap sanity.
+// Layer 2 (live, best-effort): for explicitly-listed mints, confirm they exist
+// and that their quote asset matches the strategy's SOL denomination.
+// - `mintInfo[mint]` (supplied by the endpoint from launch records) is the
+// authoritative agent-coin + quote-pairing source.
+// - mints not in mintInfo are probed on-chain via ctx.skills.invoke.
+// - A transient upstream failure downgrades to a warning so a working
+// strategy is never falsely rejected; only a definitive "not found" or a
+// confirmed quote mismatch is a hard error.
+export async function validateStrategy({ strategy, network = 'mainnet', mintInfo = null } = {}, ctx = null) {
+ const { issues, meta } = validateStrategySpec(strategy);
+
+ for (let i = 0; i < meta.mintList.length; i++) {
+ const mint = meta.mintList[i];
+ const field = `scan.mints[${i}]`;
+ const info = mintInfo?.[mint];
+
+ if (info?.isAgentCoin) {
+ if (info.quoteIsUsdc && meta.denominatedQuote === 'SOL') {
+ issues.push({
+ level: 'error',
+ field,
+ code: 'quote_asset_mismatch',
+ message: `${mint} is a ${info.quoteSymbol || 'USDC'}-paired agent coin, but this strategy denominates entry/exit in SOL (entry.amountSol, caps.*Sol). A live run would build a SOL trade against a ${info.quoteSymbol || 'USDC'} curve. Target a SOL-paired coin or re-denominate the strategy.`,
+ });
+ }
+ continue; // Known agent coin — it exists; no on-chain probe needed.
+ }
+
+ if (ctx?.skills?.invoke) {
+ let r;
+ try {
+ r = await ctx.skills.invoke('pump-fun.getTokenDetails', { mint, network });
+ } catch (e) {
+ r = { ok: false, error: e?.message };
+ }
+ if (r?.ok) {
+ if (info === undefined) {
+ issues.push({ level: 'info', field, code: 'not_agent_coin', message: `${mint} exists on ${network} but is not a three.ws agent coin — trading it is fine, but quote-asset pairing cannot be verified here.` });
+ }
+ } else if (MINT_MISSING_RE.test(String(r?.error ?? ''))) {
+ issues.push({ level: 'error', field, code: 'mint_not_found', message: `${mint} does not exist on ${network}. Check the address.` });
+ } else {
+ issues.push({ level: 'warning', field, code: 'mint_unverified', message: `Could not verify ${mint} right now (${r?.error || 'upstream unavailable'}). It is re-checked at run time.` });
+ }
+ }
}
+
+ // Final agreement guarantee: anything we deem valid must also compile for the
+ // runner. If compileStrategy disagrees, surface it rather than silently OK'ing.
+ const errors = issues.filter((x) => x.level === 'error');
+ if (!errors.length) {
+ try {
+ compileStrategy(strategy);
+ } catch (e) {
+ errors.push({ level: 'error', field: 'strategy', code: 'compile_failed', message: e.message });
+ issues.push(errors[errors.length - 1]);
+ }
+ }
+
+ const warnings = issues.filter((x) => x.level === 'warning');
+ const valid = errors.length === 0;
+ return {
+ ok: valid,
+ error: valid ? undefined : errors[0].message,
+ data: {
+ valid,
+ issues,
+ errorCount: errors.length,
+ warningCount: warnings.length,
+ filterCount: meta.filterCount,
+ exitCount: meta.exitCount,
+ filters: meta.filters,
+ exits: meta.exits,
+ summary: meta.summary,
+ },
+ };
}
async function fetchCandidates(ctx, scan) {
@@ -64,6 +141,10 @@ async function maybeSell(ctx, simulate, args) {
}
export async function runStrategy(args, ctx) {
+ // Pre-flight: refuse a semantically-broken spec before any RPC or signing,
+ // so validate and run can never disagree about what is runnable.
+ const fatal = strategyErrors(args.strategy);
+ if (fatal.length) throw new Error(`invalid strategy — ${fatal[0].message}`);
const compiled = compileStrategy(args.strategy);
const simulate = !!args.simulate;
const deadline = Date.now() + args.durationSec * 1000;
@@ -176,6 +257,8 @@ function priceFromTrade(t) {
}
export async function backtestStrategy(args, ctx) {
+ const fatal = strategyErrors(args.strategy);
+ if (fatal.length) return { ok: false, error: fatal[0].message };
const compiled = compileStrategy(args.strategy);
const mints = args.mints ?? args.strategy?.scan?.mints ?? [];
if (!mints.length) return { ok: false, error: 'backtest requires mints (in args or strategy.scan.mints)' };
@@ -346,4 +429,4 @@ export async function closeAllPositions(args, ctx) {
}
// Re-exported for tests.
-export { parsePredicate, evalPredicate, buildView, compileStrategy };
+export { parsePredicate, evalPredicate, buildView, compileStrategy, validateStrategySpec, strategyErrors };
diff --git a/pages/pump-live.html b/pages/pump-live.html
index cfc044a8a..63fc4e307 100644
--- a/pages/pump-live.html
+++ b/pages/pump-live.html
@@ -245,11 +245,13 @@
::-webkit-scrollbar-thumb { background: var(--medium-grey); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: var(--light-grey); }
- /* ── Responsive ────────────────────────────────────── */
+ /* ── Responsive ──────────────────────────────────────
+ Below 900px the kiosk row stacks vertically: the reacting 3D agent on
+ top, the live feed (with its own scroll region) beneath it. */
@media (max-width: 900px) {
- #main-container { flex-direction: column-reverse; }
- #feed-container { width: 100%; height: 50%; border-top: 1px solid var(--dark-grey); }
- #viewer-container { border-right: none; }
+ #main-container { flex-direction: column; }
+ #viewer-container { height: 45vh; min-height: 240px; border-right: none; border-bottom: 1px solid var(--dark-grey); }
+ #feed-container { width: 100%; flex: 1; min-height: 0; }
}
</style>
<link rel="stylesheet" href="/nav.css" />
@@ -314,28 +316,33 @@
import { Viewer } from '/src/viewer.js';
// ════════════════════════════════════════════════════════════════════
- // 3D Agent Setup — the avatar reacts to each new launch. If the GLB or
- // WebGL context fails to load we degrade gracefully: the feed must still
- // connect and render, so the whole viewer init is isolated in try/catch.
+ // 3D Agent Setup — the avatar reacts to each new launch. The viewer loads
+ // asynchronously and is NEVER awaited at the top level: the live feed is the
+ // primary content, so it must connect immediately regardless of how long
+ // WebGL/GLB init takes (or whether it fails on a no-GPU/locked-down client).
+ // If the viewer never finishes loading, playAnimation() simply no-ops.
// ════════════════════════════════════════════════════════════════════
let viewer = null;
- try {
- const viewerEl = document.getElementById('viewer-container');
- viewer = new Viewer(viewerEl, { kiosk: true });
- window.viewer = viewer;
+ async function initViewer() {
+ try {
+ const viewerEl = document.getElementById('viewer-container');
+ const v = new Viewer(viewerEl, { kiosk: true });
- await viewer.load('/animations/robotexpressive.glb', '', new Map());
+ await v.load('/animations/robotexpressive.glb', '', new Map());
- const idleClip =
- viewer.clips.find((c) => /^idle$/i.test(c.name)) || viewer.clips[0];
- if (idleClip && viewer.mixer) {
- viewer.mixer.clipAction(idleClip).play();
+ const idleClip =
+ v.clips.find((c) => /^idle$/i.test(c.name)) || v.clips[0];
+ if (idleClip && v.mixer) {
+ v.mixer.clipAction(idleClip).play();
+ }
+ viewer = v; // only expose once fully loaded so playAnimation() is safe
+ window.viewer = v;
+ } catch (err) {
+ console.warn('[pump-live] 3D viewer unavailable, continuing with feed only:', err?.message || err);
+ viewer = null;
}
- } catch (err) {
- console.warn('[pump-live] 3D viewer unavailable, continuing with feed only:', err?.message || err);
- viewer = null;
}
function playAnimation(animationName, { loop = false } = {}) {
@@ -617,12 +624,15 @@
$status.className = `status ${className}`;
}
- // Fetch the SOL price up front (so the first cards show USD), then poll it,
- // and open the live feed.
- await refreshSolPrice();
- setInterval(refreshSolPrice, 60000);
+ // Bootstrap. The feed opens first and never waits on anything else — the
+ // SOL price and the 3D viewer hydrate in the background. Until the first
+ // price lands, market caps render in SOL (real data) and upgrade to USD on
+ // the next paint; cards are never blocked behind a price or a WebGL context.
renderStats();
connect();
+ refreshSolPrice();
+ setInterval(refreshSolPrice, 60000);
+ initViewer();
</script>
<div id="footer-container"></div>
diff --git a/public/agent-passport.html b/public/agent-passport.html
index add7fd813..36a1994c3 100644
--- a/public/agent-passport.html
+++ b/public/agent-passport.html
@@ -428,6 +428,140 @@
font-size: 1.05rem;
}
}
+
+ /* ── Rate / vouch panel ─────────────────────────────────────── */
+ .rate-panel {
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ padding: 0.9rem 1rem;
+ margin: 0.6rem 0 0.2rem;
+ background: var(--bg);
+ }
+ .rate-panel[hidden] {
+ display: none;
+ }
+ .rate-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+ }
+ .rate-title {
+ font-weight: 600;
+ font-size: 0.95rem;
+ }
+ .rate-sub {
+ color: var(--muted);
+ font-size: 0.78rem;
+ }
+ .rate-stars {
+ display: inline-flex;
+ gap: 0.15rem;
+ margin: 0.55rem 0 0.3rem;
+ }
+ .rate-star {
+ font: inherit;
+ font-size: 1.5rem;
+ line-height: 1;
+ background: none;
+ border: none;
+ padding: 0 0.05rem;
+ cursor: pointer;
+ color: #cbb73a;
+ filter: grayscale(1) opacity(0.5);
+ transition:
+ filter 0.12s ease,
+ transform 0.12s ease;
+ }
+ .rate-star.on {
+ filter: none;
+ }
+ .rate-star:hover {
+ transform: scale(1.15);
+ }
+ .rate-star:focus-visible {
+ outline: 2px solid var(--info-fg);
+ border-radius: 4px;
+ }
+ .rate-row {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+ margin-top: 0.5rem;
+ }
+ .rate-row label {
+ font-size: 0.82rem;
+ color: var(--muted);
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ }
+ .rate-panel input[type='text'],
+ .rate-panel input[type='number'] {
+ font: inherit;
+ padding: 0.35rem 0.5rem;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: #fff;
+ color: var(--fg);
+ }
+ .rate-panel input[type='text'] {
+ flex: 1;
+ min-width: 180px;
+ }
+ .rate-panel input[type='number'] {
+ width: 110px;
+ }
+ .rate-actions {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+ margin-top: 0.7rem;
+ }
+ .rate-btn {
+ font: inherit;
+ padding: 0.45rem 0.8rem;
+ border: 1px solid #111;
+ border-radius: 6px;
+ background: #111;
+ color: #fff;
+ cursor: pointer;
+ transition:
+ opacity 0.12s ease,
+ transform 0.08s ease;
+ }
+ .rate-btn.ghost {
+ background: #fff;
+ color: var(--fg);
+ border-color: var(--border);
+ }
+ .rate-btn:hover:not(:disabled) {
+ transform: translateY(-1px);
+ }
+ .rate-btn:active:not(:disabled) {
+ transform: translateY(0);
+ }
+ .rate-btn:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+ }
+ .rate-status {
+ font-size: 0.8rem;
+ margin-top: 0.55rem;
+ min-height: 1.1em;
+ }
+ .rate-status.err {
+ color: var(--bad-fg);
+ }
+ .rate-status.ok {
+ color: var(--ok-fg);
+ }
+ .rate-status.work {
+ color: var(--muted);
+ }
</style>
</head>
<body>
@@ -460,6 +594,8 @@
<h2>Reputation <span class="hint" id="rep-hint"></span></h2>
<div id="reputation"></div>
+ <div id="rate" class="rate-panel" hidden></div>
+
<h2>
Recent attestations <span class="hint" id="atts-count"></span>
<span id="live" class="live-dot off" title="Live updates">off</span>
@@ -483,6 +619,7 @@
let cache = { rows: [], net: 'devnet', knownSigs: new Set(), freshSigs: new Set() };
let activeFilter = 'all';
let pollTimer = null;
+ let currentRep = null;
const POLL_MS = 8000;
const PUBKEY_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
@@ -598,6 +735,7 @@
const initialRows = atts.data || [];
renderIdentity(card, rep, asset, network, hist?.series || []);
renderTokenStats(card?.token_stats);
+ currentRep = rep;
renderReputation(rep);
cache = {
rows: initialRows,
@@ -607,6 +745,7 @@
};
$('filters').hidden = false;
renderAttestations();
+ renderRatePanel({ asset, network, owner: card?.identity?.owner || null });
startPolling(asset, network);
} catch (e) {
showError('identity', `Failed to load: ${e.message || e}`);
@@ -641,6 +780,7 @@
cache.knownSigs = new Set(rows.map((r) => r.signature));
cache.freshSigs = freshSigs;
renderAttestations();
+ currentRep = rep;
renderReputation(rep);
// clear the highlight class after the animation
setTimeout(() => {
@@ -1041,6 +1181,309 @@
}
}
+ // ── Rate / vouch (the write path) ─────────────────────────────────
+ // Lets any visitor with a Solana wallet submit an on-chain feedback
+ // attestation (SPL Memo, kind=threews.feedback.v1) about this agent —
+ // optionally backed by a SOL stake (kind=threews.stake.v1) sent to the
+ // agent owner. Both reference the agent asset pubkey as a read-only key
+ // so the indexer (getSignaturesForAddress(asset)) folds them into the
+ // reputation summary shown above.
+ const MEMO_PROGRAM = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';
+ const MIN_STAKE_SOL = 0.001;
+ const WEB3_CDN = 'https://esm.sh/@solana/[email protected]';
+ let web3Lib = null;
+ let rateState = { score: 0, asset: null, network: 'devnet', owner: null };
+
+ async function loadWeb3() {
+ if (web3Lib) return web3Lib;
+ web3Lib = await import(/* @vite-ignore */ WEB3_CDN);
+ return web3Lib;
+ }
+
+ function getSolanaWallet() {
+ if (typeof window === 'undefined') return null;
+ if (window.solflare?.isSolflare) return window.solflare;
+ if (window.solana?.isPhantom) return window.solana;
+ return window.solana || null;
+ }
+
+ function rpcUrl(network) {
+ return network === 'devnet'
+ ? `${location.origin}/api/solana-rpc?net=devnet`
+ : `${location.origin}/api/solana-rpc`;
+ }
+
+ function setRateStatus(kind, text) {
+ const el = $('rate-status');
+ if (!el) return;
+ el.className = `rate-status ${kind}`;
+ el.textContent = text;
+ }
+
+ function isUserRejection(err) {
+ if (!err) return false;
+ if (err.code === 4001 || err.code === 'ACTION_REJECTED') return true;
+ return /reject|denied|cancel/i.test(err.message || '');
+ }
+
+ function renderRatePanel({ asset, network, owner }) {
+ rateState = { score: 0, asset, network, owner: owner || null };
+ const el = $('rate');
+ el.hidden = false;
+ const stakeDisabled = !owner;
+ el.innerHTML = `
+ <div class="rate-head">
+ <span class="rate-title">Rate this agent</span>
+ <span class="rate-sub">Signs an on-chain attestation from your Solana wallet · ${escapeHtml(network)}</span>
+ </div>
+ <div class="rate-stars" role="radiogroup" aria-label="Score, 1 to 5">
+ ${[1, 2, 3, 4, 5]
+ .map(
+ (n) =>
+ `<button type="button" class="rate-star" data-score="${n}" role="radio" aria-checked="false" aria-label="${n} star${n === 1 ? '' : 's'}" tabindex="${n === 1 ? '0' : '-1'}">★</button>`,
+ )
+ .join('')}
+ </div>
+ <div class="rate-row">
+ <label style="flex:1">
+ Note (optional, public, on-chain)
+ <input type="text" id="rate-comment" maxlength="280" placeholder="e.g. fast, accurate, great at X" />
+ </label>
+ </div>
+ <div class="rate-row">
+ <label title="${stakeDisabled ? 'No owner wallet on record to receive a stake' : 'Send SOL to the agent owner alongside your rating'}">
+ <input type="checkbox" id="rate-stake-toggle" ${stakeDisabled ? 'disabled' : ''} />
+ Back it with a SOL stake ${stakeDisabled ? '(owner wallet unknown)' : '(economically-weighted vouch)'}
+ </label>
+ <span id="rate-stake-wrap" hidden>
+ <input type="number" id="rate-stake-amount" value="0.01" min="${MIN_STAKE_SOL}" max="100" step="0.001" aria-label="Stake amount in SOL" />
+ <span class="rate-sub">SOL → owner (min ${MIN_STAKE_SOL})</span>
+ </span>
+ </div>
+ <div class="rate-actions">
+ <button type="button" class="rate-btn" id="rate-submit" disabled>Sign &amp; submit</button>
+ <button type="button" class="rate-btn ghost" id="rate-refresh" title="Re-read reputation from chain">Refresh from chain</button>
+ </div>
+ <div class="rate-status work" id="rate-status" role="status" aria-live="polite"></div>
+ `;
+ wireRatePanel();
+ }
+
+ function wireRatePanel() {
+ const panel = $('rate');
+ const stars = Array.from(panel.querySelectorAll('.rate-star'));
+ const submitBtn = $('rate-submit');
+
+ function paint(score) {
+ stars.forEach((s) => {
+ const n = Number(s.dataset.score);
+ s.classList.toggle('on', n <= score);
+ s.setAttribute('aria-checked', n === score ? 'true' : 'false');
+ s.tabIndex = n === (score || 1) ? 0 : -1;
+ });
+ }
+ function pick(score) {
+ rateState.score = score;
+ paint(score);
+ submitBtn.disabled = false;
+ }
+ stars.forEach((s) => {
+ const n = Number(s.dataset.score);
+ s.addEventListener('mouseenter', () => paint(n));
+ s.addEventListener('mouseleave', () => paint(rateState.score));
+ s.addEventListener('click', () => pick(n));
+ s.addEventListener('keydown', (e) => {
+ if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
+ e.preventDefault();
+ const next = Math.min(5, (rateState.score || 0) + 1);
+ pick(next);
+ stars[next - 1].focus();
+ } else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
+ e.preventDefault();
+ const next = Math.max(1, (rateState.score || 1) - 1);
+ pick(next);
+ stars[next - 1].focus();
+ } else if (e.key === ' ' || e.key === 'Enter') {
+ e.preventDefault();
+ pick(n);
+ }
+ });
+ });
+
+ const toggle = $('rate-stake-toggle');
+ toggle.addEventListener('change', () => {
+ $('rate-stake-wrap').hidden = !toggle.checked;
+ submitBtn.textContent = toggle.checked ? 'Stake & vouch' : 'Sign & submit';
+ });
+
+ submitBtn.addEventListener('click', submitRating);
+ $('rate-refresh').addEventListener('click', async () => {
+ setRateStatus('work', 'Reading latest from chain…');
+ await refreshFromChain(rateState.asset, rateState.network, { force: true });
+ setRateStatus('work', '');
+ });
+ }
+
+ async function submitRating() {
+ const submitBtn = $('rate-submit');
+ const score = rateState.score;
+ if (!(score >= 1 && score <= 5)) {
+ setRateStatus('err', 'Pick a score from 1 to 5.');
+ return;
+ }
+ const comment = ($('rate-comment').value || '').trim().slice(0, 280);
+ const useStake = $('rate-stake-toggle').checked;
+ let stakeSol = 0;
+ if (useStake) {
+ stakeSol = parseFloat($('rate-stake-amount').value) || 0;
+ if (stakeSol < MIN_STAKE_SOL) {
+ setRateStatus('err', `Minimum stake is ${MIN_STAKE_SOL} SOL.`);
+ return;
+ }
+ if (!rateState.owner) {
+ setRateStatus('err', 'No owner wallet on record to receive a stake.');
+ return;
+ }
+ }
+ const wallet = getSolanaWallet();
+ if (!wallet) {
+ setRateStatus('err', 'No Solana wallet found — install Phantom or Solflare.');
+ return;
+ }
+
+ submitBtn.disabled = true;
+ setRateStatus('work', 'Connecting wallet…');
+ try {
+ const resp = await wallet.connect();
+ const payer = wallet.publicKey || resp?.publicKey;
+ if (!payer) throw new Error('Wallet returned no account');
+ const payerStr = payer.toString();
+
+ if (rateState.owner && payerStr === rateState.owner) {
+ setRateStatus('err', "You can't rate your own agent — connect a different wallet.");
+ submitBtn.disabled = false;
+ return;
+ }
+
+ // Double-review guard: the system averages each attester's ratings,
+ // so a second rating updates rather than duplicates. Confirm intent.
+ const already = (cache.rows || []).some(
+ (r) => r.kind === 'threews.feedback.v1' && r.attester === payerStr,
+ );
+ if (already && submitBtn.dataset.confirmed !== '1') {
+ submitBtn.dataset.confirmed = '1';
+ submitBtn.textContent = 'Update my rating';
+ setRateStatus('work', 'You have rated this agent before — submit again to update it.');
+ submitBtn.disabled = false;
+ return;
+ }
+
+ const web3 = await loadWeb3();
+ setRateStatus('work', useStake ? 'Building stake transaction…' : 'Building attestation…');
+ const conn = new web3.Connection(rpcUrl(rateState.network), 'confirmed');
+
+ const memo = {
+ v: 1,
+ kind: useStake ? 'threews.stake.v1' : 'threews.feedback.v1',
+ agent: rateState.asset,
+ score,
+ ...(comment ? { comment } : {}),
+ ts: Math.floor(Date.now() / 1000),
+ };
+
+ const ixs = [];
+ if (useStake) {
+ ixs.push(
+ web3.SystemProgram.transfer({
+ fromPubkey: payer,
+ toPubkey: new web3.PublicKey(rateState.owner),
+ lamports: Math.round(stakeSol * 1e9),
+ }),
+ );
+ }
+ ixs.push(
+ new web3.TransactionInstruction({
+ programId: new web3.PublicKey(MEMO_PROGRAM),
+ keys: [{ pubkey: new web3.PublicKey(rateState.asset), isSigner: false, isWritable: false }],
+ data: new TextEncoder().encode(JSON.stringify(memo)),
+ }),
+ );
+
+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('finalized');
+ const tx = new web3.Transaction({ feePayer: payer, blockhash, lastValidBlockHeight });
+ tx.add(...ixs);
+
+ setRateStatus('work', 'Approve in your wallet…');
+ const sent = await wallet.signAndSendTransaction(tx);
+ const sig = sent?.signature || sent;
+
+ setRateStatus('work', 'Confirming on-chain…');
+ await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
+
+ // Optimistic projection — corrected by the from-chain refresh below.
+ optimisticBump(score, useStake);
+
+ setRateStatus('ok', 'Submitted ✓ — ');
+ const a = document.createElement('a');
+ a.href = explorer(sig, rateState.network);
+ a.target = '_blank';
+ a.rel = 'noopener';
+ a.textContent = 'view tx ↗';
+ $('rate-status').appendChild(a);
+
+ submitBtn.textContent = useStake ? 'Stake & vouch' : 'Sign & submit';
+ delete submitBtn.dataset.confirmed;
+ refreshFromChain(rateState.asset, rateState.network, { force: true });
+ } catch (e) {
+ if (isUserRejection(e)) setRateStatus('err', 'Cancelled.');
+ else setRateStatus('err', `Failed: ${e?.message || e}`);
+ } finally {
+ submitBtn.disabled = false;
+ }
+ }
+
+ function optimisticBump(score, useStake) {
+ if (!currentRep) return;
+ const rep = JSON.parse(JSON.stringify(currentRep));
+ rep.feedback = rep.feedback || {};
+ const prevTotal = rep.feedback.total || 0;
+ const prevAvg = rep.feedback.score_avg_weighted || rep.feedback.score_avg || 0;
+ const newTotal = prevTotal + 1;
+ rep.feedback.total = newTotal;
+ rep.feedback.unique_attesters = (rep.feedback.unique_attesters || 0) + 1;
+ rep.feedback.score_avg = (prevAvg * prevTotal + score) / newTotal;
+ rep.feedback.score_avg_weighted = rep.feedback.score_avg;
+ if (useStake) {
+ rep.stake = rep.stake || { total_lamports: '0', count: 0, unique_stakers: 0, top_stakers: [] };
+ rep.stake.count = (rep.stake.count || 0) + 1;
+ }
+ currentRep = rep;
+ renderReputation(rep);
+ }
+
+ async function refreshFromChain(asset, network, { force = false } = {}) {
+ if (!asset) return;
+ try {
+ if (force) {
+ await fetch(
+ `/api/agents/solana-attestations?asset=${asset}&network=${network}&limit=25&refresh=1`,
+ ).catch(() => {});
+ }
+ const [atts, rep] = await Promise.all([
+ fetch(`/api/agents/solana-attestations?asset=${asset}&network=${network}&limit=25`).then((r) => r.json()),
+ fetch(`/api/agents/solana-reputation?asset=${asset}&network=${network}`).then((r) => r.json()),
+ ]);
+ const rows = atts.data || [];
+ cache.rows = rows;
+ cache.knownSigs = new Set(rows.map((r) => r.signature));
+ renderAttestations();
+ currentRep = rep;
+ renderReputation(rep);
+ } catch {
+ /* transient — live poll will catch up */
+ }
+ }
+
function escapeHtml(s) {
return String(s ?? '').replace(
/[&<>"']/g,
diff --git a/public/changelog.json b/public/changelog.json
index 71e9b3229..d76ed0ba5 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-15T02:40:35.792Z",
+ "generated_at": "2026-06-15T02:58:27.553Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "After you launch a coin, jump straight to viewing or managing it",
+ "summary": "The success screen you see right after launching a coin no longer dead-ends. Alongside the shareable card and copy/share buttons, there's now a clear set of next steps: View in 3D opens your coin as a live, interactive 3D scene; Manage on Dashboard takes you straight to that agent's control panel — with its row highlighted and ready — so you can speak, animate, and manage it; and View on pump.fun opens the coin on pump.fun. Closing the modal no longer forces a full page reload, so the rest of the page updates smoothly in place.",
+ "link": "/pump-dashboard",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-06-15",
"type": "update",
@@ -39,6 +49,37 @@
"improvement"
]
},
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "Rate and vouch for Solana agents from their passport",
+ "summary": "Every Solana agent passport already showed its on-chain reputation — now you can add to it. A new \"Rate this agent\" panel lets anyone with a Solana wallet (Phantom or Solflare) leave a 1–5 score, with an optional public note, written on-chain as a signed attestation — no account needed. You can also back your rating with a SOL stake (from 0.001 SOL) sent to the agent's owner for an economically-weighted vouch. Submitting is guarded the obvious ways: you can't rate your own agent, scores are limited to 1–5, the minimum stake is enforced, and re-rating asks you to confirm before it updates your previous score. The moment your transaction confirms, the passport re-reads the chain on demand instead of waiting for the next indexing pass, so your rating shows up in the reputation summary within seconds.",
+ "link": "/agent-passport.html",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "Register an existing agent on-chain in one click",
+ "summary": "Any agent you already built can now be given an ERC-8004 on-chain identity straight from its profile — no re-entering its name, 3D model, voice, or skills. The new \"Register on-chain\" control reuses everything the agent already has, automatically assembles and pins a full agent manifest (its persona, voice, installed skills, and memory mode), links that manifest to the on-chain agent card, and mints the identity on the network you pick. Re-running it on the same network is a safe no-op, and your profile shows a live on-chain badge with explorer and agent-card links the moment it's done.",
+ "link": "/agents",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "The pump.fun graduations feed stays fresh around the clock",
+ "summary": "The recent-graduations feed and the graduation data behind pump.fun signals and MCP tools now refresh continuously in the background, instead of only updating while someone had the live feed open. A new scheduled job listens to the real pump.fun migration stream and records graduations as they happen, so the feed shows up-to-date tokens even after quiet periods. Graduation data is also served straight from our own live records, so it never silently falls back to an empty list.",
+ "link": null,
+ "tags": [
+ "infra",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-15",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index f008fd404..85af46587 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>After you launch a coin, jump straight to viewing or managing it</title>
+ <link>https://three.ws/pump-dashboard</link>
+ <guid isPermaLink="false">2026-06-15:After you launch a coin, jump straight to viewing or managing it</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>The success screen you see right after launching a coin no longer dead-ends. Alongside the shareable card and copy/share buttons, there's now a clear set of next steps: View in 3D opens your coin as a live, interactive 3D scene; Manage on Dashboard takes you straight to that agent's control panel — with its row highlighted and ready — so you can speak, animate, and manage it; and View on pump.fun opens the coin on pump.fun. Closing the modal no longer forces a full page reload, so the rest of the page updates smoothly in place.</description>
+ </item>
<item>
<title>Autonomous coin buybacks and creator-fee distributions now run on schedule</title>
<link>https://three.ws/changelog</link>
@@ -30,6 +38,30 @@
<category>fix</category>
<description>The Trending mode of the 3D Pump Visualizer (three.ws/pump-visualizer) now renders correctly: every coin appears as a sphere sized by its real USD market cap, textured with its actual logo, with a full detail panel showing market cap, all-time-high, replies, age, and socials. Previously Trending failed to load because the market data it relied on wasn’t reaching the scene. Click a sphere to inspect it, or double-click to open the full 3D coin page. The live Firehose and Migrations modes are unchanged.</description>
</item>
+ <item>
+ <title>Rate and vouch for Solana agents from their passport</title>
+ <link>https://three.ws/agent-passport.html</link>
+ <guid isPermaLink="false">2026-06-15:Rate and vouch for Solana agents from their passport</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every Solana agent passport already showed its on-chain reputation — now you can add to it. A new &quot;Rate this agent&quot; panel lets anyone with a Solana wallet (Phantom or Solflare) leave a 1–5 score, with an optional public note, written on-chain as a signed attestation — no account needed. You can also back your rating with a SOL stake (from 0.001 SOL) sent to the agent's owner for an economically-weighted vouch. Submitting is guarded the obvious ways: you can't rate your own agent, scores are limited to 1–5, the minimum stake is enforced, and re-rating asks you to confirm before it updates your previous score. The moment your transaction confirms, the passport re-reads the chain on demand instead of waiting for the next indexing pass, so your rating shows up in the reputation summary within seconds.</description>
+ </item>
+ <item>
+ <title>Register an existing agent on-chain in one click</title>
+ <link>https://three.ws/agents</link>
+ <guid isPermaLink="false">2026-06-15:Register an existing agent on-chain in one click</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Any agent you already built can now be given an ERC-8004 on-chain identity straight from its profile — no re-entering its name, 3D model, voice, or skills. The new &quot;Register on-chain&quot; control reuses everything the agent already has, automatically assembles and pins a full agent manifest (its persona, voice, installed skills, and memory mode), links that manifest to the on-chain agent card, and mints the identity on the network you pick. Re-running it on the same network is a safe no-op, and your profile shows a live on-chain badge with explorer and agent-card links the moment it's done.</description>
+ </item>
+ <item>
+ <title>The pump.fun graduations feed stays fresh around the clock</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-15:The pump.fun graduations feed stays fresh around the clock</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>infra</category>
+ <description>The recent-graduations feed and the graduation data behind pump.fun signals and MCP tools now refresh continuously in the background, instead of only updating while someone had the live feed open. A new scheduled job listens to the real pump.fun migration stream and records graduations as they happen, so the feed shows up-to-date tokens even after quiet periods. Graduation data is also served straight from our own live records, so it never silently falls back to an empty list.</description>
+ </item>
<item>
<title>three.ws now registers itself as an on-chain agent (ERC-8004)</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 6baac99f3..2bb049070 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-15T02:40:34.256Z",
+ "generated_at": "2026-06-15T02:58:27.488Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/strategy-lab.html b/public/strategy-lab.html
index 34b17dac7..a553f983a 100644
--- a/public/strategy-lab.html
+++ b/public/strategy-lab.html
@@ -48,6 +48,20 @@
.status.warn { background: var(--warn-bg); color: var(--warn-fg); }
.status.info { background: var(--info-bg); color: var(--info-fg); }
+ .issues { margin-top: .5rem; display: flex; flex-direction: column; gap: .35rem; }
+ .issue { display: grid; grid-template-columns: auto auto 1fr; gap: .4rem; align-items: start;
+ font-size: .78rem; padding: .4rem .55rem; border-radius: 6px; border-left: 3px solid transparent; }
+ .issue .badge { text-transform: uppercase; font-size: .6rem; font-weight: 700; letter-spacing: .05em;
+ padding: .1rem .35rem; border-radius: 4px; align-self: center; }
+ .issue code { font-size: .72rem; opacity: .85; align-self: center; white-space: nowrap; }
+ .issue .msg { line-height: 1.4; }
+ .issue.error { background: var(--bad-bg); color: var(--bad-fg); border-left-color: var(--bad-fg); }
+ .issue.error .badge { background: var(--bad-fg); color: #fff; }
+ .issue.warning { background: var(--warn-bg); color: var(--warn-fg); border-left-color: var(--warn-fg); }
+ .issue.warning .badge { background: var(--warn-fg); color: #fff; }
+ .issue.info { background: var(--info-bg); color: var(--info-fg); border-left-color: var(--info-fg); }
+ .issue.info .badge { background: var(--info-fg); color: #fff; }
+
.metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: .5rem; margin: .5rem 0; }
.metric { border: 1px solid var(--border); border-radius: 8px; padding: .5rem .7rem; background: var(--bg); }
.metric .v { font-size: 1.3rem; font-weight: 600; line-height: 1.1; }
@@ -155,11 +169,15 @@
<button id="stop" disabled>Stop</button>
</div>
<div id="status" class="status info">Edit the spec and hit Validate.</div>
+ <div id="issues" class="issues" style="display:none"></div>
<div style="margin-top:.5rem; font-size:.75rem;" class="muted">
- Predicate paths: <code>holders.total</code>, <code>holders.topHolderPct</code>,
- <code>creator.rugCount</code>, <code>curve.priceSol</code>,
- <code>position.pnlPct</code>, <code>position.ageSec</code>.
- Ops: <code>&gt; &gt;= &lt; &lt;= == !=</code>.
+ Filter &amp; exit paths: <code>holders.total</code>, <code>holders.topHolderPct</code>,
+ <code>creator.rugCount</code>, <code>curve.graduationPct</code>, <code>curve.priceSol</code>,
+ <code>token.ageSec</code>, <code>token.marketCapSol</code>.
+ Exit-only (open position): <code>position.pnlPct</code>, <code>position.ageSec</code>,
+ <code>position.amountTokens</code>, <code>position.entryPriceSol</code>.
+ Ops: <code>&gt; &gt;= &lt; &lt;= == !=</code>. Validation flags unknown paths,
+ impossible thresholds, contradictory filters, and unreachable exit rules.
</div>
</section>
@@ -233,6 +251,19 @@
let currentWallet = null; // { address, sol }
function setStatus(msg, kind = 'info') { status.className = 'status ' + kind; status.textContent = msg; }
+ const issuesEl = $('issues');
+ const ISSUE_ORDER = { error: 0, warning: 1, info: 2 };
+ function renderIssues(issues) {
+ if (!issues || !issues.length) { issuesEl.style.display = 'none'; issuesEl.innerHTML = ''; return; }
+ const sorted = [...issues].sort((a, b) => (ISSUE_ORDER[a.level] ?? 9) - (ISSUE_ORDER[b.level] ?? 9));
+ issuesEl.style.display = '';
+ issuesEl.innerHTML = sorted.map((i) => `
+ <div class="issue ${i.level || 'info'}">
+ <span class="badge">${escapeHtml(i.level || 'info')}</span>
+ <code>${escapeHtml(i.field || '—')}</code>
+ <span class="msg">${escapeHtml(i.message || '')}</span>
+ </div>`).join('');
+ }
function setWalletStatus(msg, kind) {
if (!msg) { walletStatus.style.display = 'none'; return; }
walletStatus.style.display = ''; walletStatus.className = 'status ' + (kind || 'info'); walletStatus.textContent = msg;
@@ -329,25 +360,42 @@
// ── Validate / Backtest / Run ──────────────────────────────────────
$('validate').onclick = async () => {
- spec.classList.remove('invalid');
+ spec.classList.remove('invalid'); renderIssues([]);
let s; try { s = getSpec(); } catch { return; }
setStatus('Validating…');
const r = await fetch('/api/pump/strategy-validate', {
- method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ strategy: s }),
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ strategy: s, network: netSel.value }),
}).then((r) => r.json()).catch((e) => ({ error: e.message }));
- if (r.error) { setStatus('Invalid: ' + (r.error_description || r.error), 'bad'); spec.classList.add('invalid'); return; }
- setStatus(`OK — ${r.data.filterCount} filter(s), ${r.data.exitCount} exit rule(s)`, 'ok');
+ if (r.error) {
+ const issues = r.issues || r.report?.issues || [{ level: 'error', field: '', message: r.error_description || r.error }];
+ const errCount = issues.filter((i) => i.level === 'error').length || 1;
+ setStatus(`Invalid — ${errCount} error${errCount === 1 ? '' : 's'} to fix`, 'bad');
+ spec.classList.add('invalid');
+ renderIssues(issues);
+ return;
+ }
+ const d = r.data || {};
+ const notes = (d.issues || []).filter((i) => i.level !== 'error');
+ setStatus(`Valid — ${d.filterCount} filter(s), ${d.exitCount} exit rule(s)` + (notes.length ? ` · ${notes.length} note${notes.length === 1 ? '' : 's'}` : ''), notes.length ? 'warn' : 'ok');
+ renderIssues(notes);
};
$('backtest').onclick = async () => {
- spec.classList.remove('invalid');
+ spec.classList.remove('invalid'); renderIssues([]);
let s; try { s = getSpec(); } catch { return; }
setStatus('Sourcing mints from live MCP…');
clearLog(); pushLog('start', '▶ backtest started (real on-chain data)');
const r = await fetch('/api/pump/strategy-backtest', {
- method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ strategy: s }),
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ strategy: s, network: netSel.value }),
}).then((r) => r.json()).catch((e) => ({ error: e.message }));
- if (r.error) { setStatus('Backtest failed: ' + (r.error_description || r.error), 'bad'); pushLog('error', '! ' + (r.error_description || r.error)); return; }
+ if (r.error) {
+ setStatus('Backtest failed: ' + (r.error_description || r.error), 'bad');
+ pushLog('error', '! ' + (r.error_description || r.error));
+ if (r.issues) { spec.classList.add('invalid'); renderIssues(r.issues); }
+ return;
+ }
renderBacktest(r.data);
pushLog('done', `✓ ${r.data.tradeCount} trade(s), ROI ${r.data.roiPct.toFixed(1)}%, ${r.data.mintsUsed?.length} mints scanned`);
setStatus('Backtest complete', 'ok');
@@ -385,7 +433,7 @@
}
$('run').onclick = async () => {
- spec.classList.remove('invalid');
+ spec.classList.remove('invalid'); renderIssues([]);
let s; try { s = getSpec(); } catch { return; }
const network = netSel.value;
const agentId = agentSel.value;
@@ -419,7 +467,16 @@
}),
signal: ctrl.signal,
});
- if (!resp.ok) { setStatus('Run failed: HTTP ' + resp.status + ' — ' + await resp.text(), 'bad'); return; }
+ if (!resp.ok) {
+ let body = null; try { body = JSON.parse(await resp.text()); } catch {}
+ if (body?.issues) {
+ setStatus(`Run rejected — ${body.error_description || body.error}`, 'bad');
+ spec.classList.add('invalid'); renderIssues(body.issues);
+ } else {
+ setStatus('Run failed: HTTP ' + resp.status + (body?.error_description ? ' — ' + body.error_description : ''), 'bad');
+ }
+ return;
+ }
const reader = resp.body.getReader(), dec = new TextDecoder();
let buf = '';
while (true) {
@@ -513,28 +570,42 @@
function renderPortfolio(d) {
const el = $('portfolio');
if (!d) { el.innerHTML = '<p class="muted">Pick an agent above to load on-chain holdings.</p>'; return; }
- const totalPnlClass = pn(d.unrealizedPnlSol);
+ // Per-quote subtotals — SOL and USDC are tallied separately so values in
+ // different currencies are never summed together.
+ const subs = d.subtotals && Object.keys(d.subtotals).length
+ ? Object.values(d.subtotals)
+ : [];
+ const subCards = subs.map((s) => {
+ const dec = s.quoteSymbol === 'SOL' ? 4 : 2;
+ const cls = pn(s.unrealizedPnl);
+ return `
+ <div class="metric"><div class="v">${fmt(s.value, dec)} ${s.quoteSymbol}</div><div class="l">value (${s.positions} pos)</div></div>
+ <div class="metric"><div class="v">${fmt(s.costBasis, dec)} ${s.quoteSymbol}</div><div class="l">${s.quoteSymbol} cost basis</div></div>
+ <div class="metric"><div class="v ${cls}">${fmt(s.unrealizedPnl, dec)} ${s.quoteSymbol}</div><div class="l">${s.quoteSymbol} PnL (${pct(s.unrealizedPnlPct)})</div></div>`;
+ }).join('');
el.innerHTML = `
<div class="metrics" style="margin-top:.5rem">
- <div class="metric"><div class="v">${(d.sol ?? 0).toFixed(4)}</div><div class="l">SOL balance</div></div>
- <div class="metric"><div class="v">${fmt(d.totalValueSol, 4)}</div><div class="l">tokens value (SOL)</div></div>
- <div class="metric"><div class="v">${fmt(d.totalCostBasisSol, 4)}</div><div class="l">cost basis</div></div>
- <div class="metric"><div class="v ${totalPnlClass}">${fmt(d.unrealizedPnlSol, 4)}</div><div class="l">unrealized PnL</div></div>
- <div class="metric"><div class="v ${totalPnlClass}">${pct(d.unrealizedPnlPct)}</div><div class="l">unrealized %</div></div>
+ <div class="metric"><div class="v">${(d.sol ?? 0).toFixed(4)} SOL</div><div class="l">wallet balance</div></div>
<div class="metric"><div class="v">${d.holdings.length}</div><div class="l">positions</div></div>
+ ${subCards}
</div>
<table style="margin-top:.5rem">
- <thead><tr><th>Mint</th><th class="num">Amount</th><th class="num">Price</th><th class="num">Value</th><th class="num">Cost</th><th class="num">PnL</th></tr></thead>
+ <thead><tr><th>Mint</th><th>Quote</th><th class="num">Amount</th><th class="num">Price</th><th class="num">Value</th><th class="num">Cost</th><th class="num">PnL</th></tr></thead>
<tbody>
- ${d.holdings.map((h) => `
+ ${d.holdings.map((h) => {
+ const sym = h.quoteSymbol || 'SOL';
+ const dec = sym === 'SOL' ? 4 : 2;
+ return `
<tr>
<td><a href="https://pump.fun/${h.mint}" target="_blank"><code>${h.mint.slice(0, 8)}…</code></a></td>
+ <td>${sym}</td>
<td class="num">${fmt(h.amount, 2)}</td>
- <td class="num">${fmt(h.priceSol, 8)}</td>
- <td class="num">${fmt(h.valueSol, 4)}</td>
- <td class="num">${h.costBasisSol == null ? '—' : fmt(h.costBasisSol, 4)}</td>
- <td class="num"><span class="${pn(h.unrealizedPnlSol)}">${fmt(h.unrealizedPnlSol, 4)} (${pct(h.unrealizedPnlPct)})</span></td>
- </tr>`).join('') || '<tr><td colspan="6" class="muted">— no token holdings —</td></tr>'}
+ <td class="num">${fmt(h.priceQuote, 8)}</td>
+ <td class="num">${h.valueQuote == null ? '—' : `${fmt(h.valueQuote, dec)} ${sym}`}</td>
+ <td class="num">${h.costBasis == null ? '—' : `${fmt(h.costBasis, dec)} ${sym}`}</td>
+ <td class="num"><span class="${pn(h.unrealizedPnl)}">${h.unrealizedPnl == null ? '—' : `${fmt(h.unrealizedPnl, dec)} ${sym}`} (${pct(h.unrealizedPnlPct)})</span></td>
+ </tr>`;
+ }).join('') || '<tr><td colspan="7" class="muted">— no token holdings —</td></tr>'}
</tbody>
</table>
`;
diff --git a/scripts/agent-invocation-smoke.mjs b/scripts/agent-invocation-smoke.mjs
new file mode 100644
index 000000000..4801c12b1
--- /dev/null
+++ b/scripts/agent-invocation-smoke.mjs
@@ -0,0 +1,160 @@
+#!/usr/bin/env node
+/**
+ * Devnet smoke test for the deployed `agent_invocation` Solana program.
+ *
+ * Exercises the published SDK end-to-end against the LIVE program:
+ * 1. confirms the program id is deployed + executable on the target cluster,
+ * 2. mints two synthetic agent authorities (never a real third-party wallet),
+ * 3. funds the invoker (devnet airdrop, or a funder key on other clusters),
+ * 4. calls `invokeSkill()` from @three-ws/agent-protocol-sdk,
+ * 5. decodes the on-chain `SkillInvoked` event and asserts every field.
+ *
+ * Re-runnable: it generates fresh authorities each run, so it never collides
+ * with a previous invocation. Exits non-zero on any failure.
+ *
+ * Env:
+ * SOLANA_RPC_URL_DEVNET RPC endpoint (default https://api.devnet.solana.com)
+ * AGENT_INVOCATION_PROGRAM_ID override the program id (defaults to SDK value)
+ * SMOKE_FUNDER_KEYPAIR path to a funded payer keypair (required off devnet,
+ * where the faucet airdrop is unavailable)
+ */
+import { createRequire } from 'node:module';
+import fs from 'node:fs';
+
+const require = createRequire(import.meta.url);
+const { Connection, Keypair, PublicKey, LAMPORTS_PER_SOL } = require('@solana/web3.js');
+const anchor = require('@coral-xyz/anchor');
+const { invokeSkill, deriveAgentPda, AGENT_INVOCATION_PROGRAM_ID, IDL } = require(
+ '../agent-protocol-sdk/dist/index.js',
+);
+
+const RPC = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';
+const PROGRAM_ID = new PublicKey(
+ process.env.AGENT_INVOCATION_PROGRAM_ID || AGENT_INVOCATION_PROGRAM_ID,
+);
+const SKILL = 'summarize';
+const PARAMS = JSON.stringify({ url: 'https://three.ws', lang: 'en' });
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+function loadKeypair(path) {
+ const bytes = Uint8Array.from(JSON.parse(fs.readFileSync(path, 'utf8')));
+ return Keypair.fromSecretKey(bytes);
+}
+
+async function fundInvoker(connection, invoker) {
+ if (process.env.SMOKE_FUNDER_KEYPAIR) {
+ const funder = loadKeypair(process.env.SMOKE_FUNDER_KEYPAIR);
+ const { SystemProgram, Transaction, sendAndConfirmTransaction } = require('@solana/web3.js');
+ const tx = new Transaction().add(
+ SystemProgram.transfer({
+ fromPubkey: funder.publicKey,
+ toPubkey: invoker.publicKey,
+ lamports: 0.02 * LAMPORTS_PER_SOL,
+ }),
+ );
+ await sendAndConfirmTransaction(connection, tx, [funder], { commitment: 'confirmed' });
+ return;
+ }
+ // Devnet faucet — retried, it is frequently rate-limited.
+ let lastErr;
+ for (let attempt = 1; attempt <= 5; attempt++) {
+ try {
+ const sig = await connection.requestAirdrop(invoker.publicKey, 0.05 * LAMPORTS_PER_SOL);
+ const bh = await connection.getLatestBlockhash();
+ await connection.confirmTransaction({ signature: sig, ...bh }, 'confirmed');
+ return;
+ } catch (err) {
+ lastErr = err;
+ console.warn(` airdrop attempt ${attempt} failed: ${err.message}; retrying…`);
+ await sleep(2000 * attempt);
+ }
+ }
+ throw new Error(
+ `could not fund invoker via devnet faucet after retries (${lastErr?.message}). ` +
+ 'Set SMOKE_FUNDER_KEYPAIR to a funded payer and re-run.',
+ );
+}
+
+function field(data, snake, camel) {
+ return data[snake] ?? data[camel];
+}
+
+async function main() {
+ console.log(`agent_invocation smoke test`);
+ console.log(` rpc: ${RPC}`);
+ console.log(` program: ${PROGRAM_ID.toBase58()}`);
+
+ const connection = new Connection(RPC, 'confirmed');
+
+ const programAccount = await connection.getAccountInfo(PROGRAM_ID);
+ if (!programAccount || !programAccount.executable) {
+ throw new Error(
+ `program ${PROGRAM_ID.toBase58()} is not deployed/executable on ${RPC}. Deploy it first.`,
+ );
+ }
+ console.log(` program is deployed + executable ✓`);
+
+ const invokerAuthority = Keypair.generate();
+ const targetAuthority = Keypair.generate();
+ console.log(` invoker authority: ${invokerAuthority.publicKey.toBase58()}`);
+ console.log(` target authority: ${targetAuthority.publicKey.toBase58()}`);
+
+ console.log(` funding invoker…`);
+ await fundInvoker(connection, invokerAuthority);
+
+ const [invokerAgent] = deriveAgentPda(invokerAuthority.publicKey, PROGRAM_ID);
+ const [targetAgent] = deriveAgentPda(targetAuthority.publicKey, PROGRAM_ID);
+
+ console.log(` submitting invoke_skill('${SKILL}')…`);
+ const signature = await invokeSkill({
+ connection,
+ invokerAuthority,
+ targetAuthority: targetAuthority.publicKey,
+ skillName: SKILL,
+ parameters: PARAMS,
+ programId: PROGRAM_ID,
+ });
+ console.log(` tx confirmed: ${signature}`);
+
+ const tx = await connection.getTransaction(signature, {
+ commitment: 'confirmed',
+ maxSupportedTransactionVersion: 0,
+ });
+ if (!tx?.meta?.logMessages) throw new Error('confirmed tx has no log messages to parse');
+
+ const idl = { ...IDL, address: PROGRAM_ID.toBase58() };
+ const parser = new anchor.EventParser(PROGRAM_ID, new anchor.BorshCoder(idl));
+ const events = [...parser.parseLogs(tx.meta.logMessages)];
+ const event = events.find((e) => e.name === 'SkillInvoked' || e.name === 'skillInvoked');
+ if (!event) throw new Error(`no SkillInvoked event found in tx logs (${events.map((e) => e.name)})`);
+
+ const d = event.data;
+ const checks = [
+ ['invoker_agent', field(d, 'invoker_agent', 'invokerAgent').toBase58(), invokerAgent.toBase58()],
+ ['target_agent', field(d, 'target_agent', 'targetAgent').toBase58(), targetAgent.toBase58()],
+ [
+ 'invoker_authority',
+ field(d, 'invoker_authority', 'invokerAuthority').toBase58(),
+ invokerAuthority.publicKey.toBase58(),
+ ],
+ ['skill_name', field(d, 'skill_name', 'skillName'), SKILL],
+ ['parameters', d.parameters, PARAMS],
+ ];
+ for (const [name, got, want] of checks) {
+ if (got !== want) throw new Error(`event.${name} mismatch: got ${got}, expected ${want}`);
+ console.log(` event.${name} ✓`);
+ }
+ const ts = Number(field(d, 'timestamp', 'timestamp'));
+ if (!Number.isFinite(ts) || ts <= 0) throw new Error(`event.timestamp invalid: ${ts}`);
+ console.log(` event.timestamp ✓ (${new Date(ts * 1000).toISOString()})`);
+
+ const cluster = RPC.includes('devnet') ? '?cluster=devnet' : '';
+ console.log(`\n✅ SkillInvoked verified on-chain.`);
+ console.log(` https://explorer.solana.com/tx/${signature}${cluster}`);
+}
+
+main().catch((err) => {
+ console.error(`\n❌ smoke test failed: ${err.message}`);
+ process.exit(1);
+});
diff --git a/scripts/erc8004-register-self.mjs b/scripts/erc8004-register-self.mjs
index a78785176..5e89df1d7 100755
--- a/scripts/erc8004-register-self.mjs
+++ b/scripts/erc8004-register-self.mjs
@@ -246,20 +246,17 @@ async function registerOnNetwork(net, { signerKey, cardURI, dryRun, glbName, glb
console.log(` signer: ${wallet.address} (${ethers.formatEther(bal)} ETH)`);
console.log(` tokenURI: ${cardURI}`);
- // Optionally re-pin the card model + body to IPFS for this run.
- let mintURI = cardURI;
+ // Optionally pin the GLB to IPFS now. The immutable card snapshot that points
+ // at this URI is pinned AFTER the mint (below), once the agentId is known, so
+ // the on-chain card embeds its own registration. We always mint against the
+ // stable https card URL so the seed Registered event carries a resolvable URI.
+ let glbIpfs = null;
if (process.env.PINATA_JWT) {
console.log(' pinning GLB to IPFS (PINATA_JWT present)…');
- const glbIpfs = await pinToPinata(readFileSync(glbPath), glbName, 'model/gltf-binary');
- const card = loadCard();
- card.model.uri = glbIpfs;
- card.registrations = upsertRegistration(card.registrations, net.chainId, registry, 0); // placeholder id; replaced after mint below via re-pin
+ glbIpfs = await pinToPinata(readFileSync(glbPath), glbName, 'model/gltf-binary');
console.log(` GLB pinned: ${glbIpfs}`);
- // The immutable card is pinned AFTER we know the agentId (below), so the
- // on-chain card embeds its own registration. Until then mint against the
- // stable https card URL so the seed event has a resolvable URI.
- mintURI = cardURI;
}
+ const mintURI = cardURI;
const fn = contract.getFunction('register(string)');
@@ -302,6 +299,7 @@ async function registerOnNetwork(net, { signerKey, cardURI, dryRun, glbName, glb
let finalURI = cardURI;
if (process.env.PINATA_JWT) {
const card = loadCard();
+ if (glbIpfs) card.model.uri = glbIpfs;
card.registrations = upsertRegistration(card.registrations, net.chainId, registry, agentId);
const snapshot = Buffer.from(JSON.stringify(card, null, '\t'), 'utf8');
const cardIpfs = await pinToPinata(snapshot, `3d-agent-card-${net.chainId}.json`, 'application/json');
diff --git a/scripts/erc8004/provision-validator-key.mjs b/scripts/erc8004/provision-validator-key.mjs
new file mode 100644
index 000000000..144fac598
--- /dev/null
+++ b/scripts/erc8004/provision-validator-key.mjs
@@ -0,0 +1,53 @@
+#!/usr/bin/env node
+/**
+ * Provision the platform ValidationRegistry validator key.
+ *
+ * Generates a fresh EVM keypair used to sign glTF/schema validation
+ * attestations (recordValidation). The PRIVATE KEY is printed to STDERR only and
+ * is NEVER written to the repo — capture it from the terminal and store it as
+ * the `VALIDATOR_PRIVATE_KEY` secret in Vercel (and .env.local for local runs).
+ *
+ * The ADDRESS is printed to STDOUT — that's the value you allow-list on each
+ * ValidationRegistry chain via addValidator(<addr>) as the registry owner
+ * (task 01 step 6), and the value you record in DEPLOYMENTS.md.
+ *
+ * Usage:
+ * node scripts/erc8004/provision-validator-key.mjs # generate fresh
+ * node scripts/erc8004/provision-validator-key.mjs --address # print address of an existing key
+ * VALIDATOR_PRIVATE_KEY=0x… node scripts/erc8004/provision-validator-key.mjs --address
+ */
+
+import { Wallet } from 'ethers';
+
+const addressOnly = process.argv.includes('--address');
+
+if (addressOnly) {
+ const pk = process.env.VALIDATOR_PRIVATE_KEY || process.env.ERC8004_VALIDATOR_PRIVATE_KEY;
+ if (!pk) {
+ console.error('Set VALIDATOR_PRIVATE_KEY to print its address.');
+ process.exit(1);
+ }
+ const w = new Wallet(pk.trim());
+ process.stdout.write(`${w.address}\n`);
+ process.exit(0);
+}
+
+const wallet = Wallet.createRandom();
+
+// Secret → stderr only. Do not pipe stderr into any committed file.
+console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
+console.error(' PLATFORM VALIDATOR KEY (SECRET — store in Vercel, never commit)');
+console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
+console.error(` VALIDATOR_PRIVATE_KEY=${wallet.privateKey}`);
+console.error(` mnemonic: ${wallet.mnemonic?.phrase || '(n/a)'}`);
+console.error('');
+console.error(' Next steps:');
+console.error(' 1. vercel env add VALIDATOR_PRIVATE_KEY (production + preview)');
+console.error(' 2. Fund the address with gas on each ValidationRegistry chain.');
+console.error(' 3. As the registry owner, allow-list it on each chain:');
+console.error(` cast send <ValidationRegistry> "addValidator(address)" ${wallet.address} --rpc-url <chain>`);
+console.error(' 4. Record the address in contracts/DEPLOYMENTS.md.');
+console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
+
+// Address → stdout (safe to capture/log).
+process.stdout.write(`${wallet.address}\n`);
diff --git a/scripts/gen-agent-invocation-idl.mjs b/scripts/gen-agent-invocation-idl.mjs
new file mode 100644
index 000000000..249624048
--- /dev/null
+++ b/scripts/gen-agent-invocation-idl.mjs
@@ -0,0 +1,26 @@
+#!/usr/bin/env node
+/**
+ * Regenerate the committed Anchor IDL at contracts/idl/agent_invocation.json
+ * from the SDK's typed IDL (agent-protocol-sdk/src/idl.ts — the source of truth
+ * kept in sync by hand with the on-chain program). Run after changing the IDL or
+ * the program id:
+ *
+ * npm --prefix agent-protocol-sdk run build # emit dist/
+ * node scripts/gen-agent-invocation-idl.mjs
+ */
+import { createRequire } from 'node:module';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const require = createRequire(import.meta.url);
+const { IDL } = require('../agent-protocol-sdk/dist/index.js');
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const out = path.join(root, 'contracts/idl/agent_invocation.json');
+
+// Strip the `as const` readonly-ness and emit plain JSON Anchor tooling consumes.
+const idl = JSON.parse(JSON.stringify(IDL));
+fs.mkdirSync(path.dirname(out), { recursive: true });
+fs.writeFileSync(out, JSON.stringify(idl, null, 2) + '\n');
+console.log(`wrote ${path.relative(root, out)} (program ${idl.address})`);
diff --git a/scripts/verify-solana-parity.mjs b/scripts/verify-solana-parity.mjs
new file mode 100644
index 000000000..9ec7a0379
--- /dev/null
+++ b/scripts/verify-solana-parity.mjs
@@ -0,0 +1,350 @@
+#!/usr/bin/env node
+/**
+ * Solana address-parity + on-chain provenance guard.
+ *
+ * three.ws is a Solana platform. Two classes of on-chain address are hand-copied
+ * across dozens of source files and can silently drift apart — every drift is a
+ * real bug or a brand-rule violation:
+ *
+ * 1. The $THREE mint (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump). Canonical
+ * source: api/_lib/env.js → THREE_TOKEN_MINT default. It is ALSO hardcoded
+ * in ~25 other files (api/x402, src/pump, packages config modules,
+ * multiplayer, scripts). CLAUDE.md is absolute: $THREE is the only coin
+ * this platform may reference, and any other coin in source is treated like
+ * a leaked secret. So a hardcoded mint that drifts from the canonical CA —
+ * or any OTHER pump.fun mint baked into real source — is a hard failure.
+ *
+ * 2. Pump protocol program IDs and well-known Solana programs/mints. Canonical
+ * source: api/_lib/solana/programs.js (PUMP_PROGRAM_ID, PUMP_AMM_PROGRAM_ID,
+ * PUMP_FEE_PROGRAM_ID, WSOL_MINT, …) plus the immutable ecosystem constants
+ * (SPL Token, Token-2022, Memo, Associated-Token, mainnet USDC). A typo'd
+ * token-program ID or a stale pump program ID sends instructions to the
+ * wrong account and every tx fails — caught here at build time, not runtime.
+ *
+ * Two severities, mirroring scripts/audit-deploy-artifacts.mjs and
+ * scripts/verify-onchain-parity.mjs:
+ * - Address drift / a rogue non-$THREE mint — ALWAYS a real config or brand
+ * bug → hard fail (exit 1).
+ * - Live on-chain provenance — a declared account that exists but is the wrong
+ * kind (mint not owned by a token program, program not executable) is a hard
+ * fail; an RPC that is unreachable in CI degrades to a warning so transport
+ * noise never blocks a deploy.
+ *
+ * Runs standalone (`npm run verify:solana`), in scripts/build-vercel.mjs phase 1
+ * alongside audit-deploy-artifacts.mjs, and via tests/solana-parity.test.js.
+ *
+ * Live provenance is configurable:
+ * VERIFY_SOLANA_LIVE=1 (default — probe the mint + pump programs on mainnet)
+ * VERIFY_SOLANA_LIVE=0 (skip the live check entirely)
+ * SOLANA_RPC_URL / HELIUS_API_KEY honored for the RPC endpoint.
+ */
+import { execFileSync } from 'node:child_process';
+import { readFileSync, readdirSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+// The one and only coin (CLAUDE.md, absolute). The canonical default also lives
+// in api/_lib/env.js; loadCanonical() asserts the two agree so this constant can
+// never quietly disagree with the running config.
+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+// Solana base58 program addresses are owned by a loader and `executable: true`.
+const SPL_TOKEN_PROGRAM = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
+const TOKEN_2022_PROGRAM = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';
+
+// ---------------------------------------------------------------------------
+// Canonical address registry — cross-checked against the repo source-of-truth
+// files at load time so this script and the running code can never disagree.
+// ---------------------------------------------------------------------------
+
+/**
+ * Each entry: a set of constant identifiers that, wherever they are assigned a
+ * base58 literal in source, MUST hold `address`. `kind` drives the live check.
+ */
+function canonicalRegistry(pumpIds) {
+ return [
+ { label: '$THREE mint', address: THREE_MINT, kind: 'token-2022-mint', names: ['THREE_MINT', 'THREE_TOKEN_MINT', 'TOKEN_MINT'] },
+ { label: 'Pump bonding-curve program', address: pumpIds.PUMP_PROGRAM_ID, kind: 'program', names: ['PUMP_PROGRAM', 'PUMP_PROGRAM_ID'] },
+ { label: 'PumpSwap AMM program', address: pumpIds.PUMP_AMM_PROGRAM_ID, kind: 'program', names: ['PUMP_AMM_PROGRAM', 'PUMP_AMM_PROGRAM_ID'] },
+ { label: 'PumpFees program', address: pumpIds.PUMP_FEE_PROGRAM_ID, kind: 'program', names: ['PUMP_FEE_PROGRAM', 'PUMP_FEE_PROGRAM_ID'] },
+ { label: 'SPL Token program', address: SPL_TOKEN_PROGRAM, kind: 'program', names: ['TOKEN_PROGRAM', 'TOKEN_PROGRAM_ID', 'SPL_TOKEN_PROGRAM_ID'] },
+ { label: 'Token-2022 program', address: TOKEN_2022_PROGRAM, kind: 'program', names: ['TOKEN_2022_PROGRAM_ID', 'TOKEN2022_PROGRAM_ID'] },
+ { label: 'Memo program', address: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr', kind: 'program', names: ['MEMO_PROGRAM', 'MEMO_PROGRAM_ID'] },
+ { label: 'Associated-Token program', address: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL', kind: 'program', names: ['ASSOCIATED_TOKEN_PROGRAM_ID', 'ASSOCIATED_TOKEN_PROGRAM'] },
+ { label: 'Wrapped SOL mint', address: pumpIds.WSOL_MINT, kind: 'token-mint', names: ['WSOL_MINT', 'WSOL', 'NATIVE_SOL_MINT', 'SOL_MINT'] },
+ { label: 'USDC (mainnet) mint', address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', kind: 'token-mint', names: ['USDC_MINT', 'USDC_MAINNET_MINT', 'USDC_SOLANA_MINT'] },
+ ];
+}
+
+/**
+ * Loads the repo's source-of-truth values and asserts they match the constants
+ * above. Returns the canonical registry. Throws on an internal SoT disagreement
+ * (e.g. someone changed the env.js default but not this guard).
+ */
+export async function loadCanonical({ root = ROOT } = {}) {
+ // Pump IDs: import the dependency-free SoT module directly.
+ const programs = await import(pathToFileURL(resolve(root, 'api/_lib/solana/programs.js')).href);
+
+ // $THREE mint: read the env.js default by regex (importing env.js pulls the
+ // whole server config surface; the literal default is all we need).
+ const envSrc = readFileSync(resolve(root, 'api/_lib/env.js'), 'utf8');
+ const m = envSrc.match(/opt\(\s*['"]THREE_TOKEN_MINT['"]\s*,\s*['"]([1-9A-HJ-NP-Za-km-z]{32,44})['"]\s*\)/);
+ const envMint = m?.[1];
+
+ const internal = [];
+ if (envMint !== THREE_MINT) {
+ internal.push(`api/_lib/env.js THREE_TOKEN_MINT default ${JSON.stringify(envMint)} != canonical ${THREE_MINT}`);
+ }
+ if (programs.WSOL_MINT !== 'So11111111111111111111111111111111111111112') {
+ internal.push(`api/_lib/solana/programs.js WSOL_MINT drifted: ${programs.WSOL_MINT}`);
+ }
+ if (internal.length) {
+ const err = new Error('canonical source-of-truth disagreement:\n ' + internal.join('\n '));
+ err.internal = internal;
+ throw err;
+ }
+
+ return canonicalRegistry(programs);
+}
+
+// ---------------------------------------------------------------------------
+// Source file enumeration (git index, with on-disk fallback for Vercel's
+// .git-less build container — same strategy as audit-deploy-artifacts.mjs)
+// ---------------------------------------------------------------------------
+
+const SCAN_EXTS = /\.(js|mjs|ts)$/;
+// Generated bundles, vendored deps, and fixtures/tests are allowed to hold
+// arbitrary or synthetic addresses — only first-party runtime source is scanned.
+const SCAN_SKIP = /(^|\/)(node_modules|dist|dist-lib|build|\.vercel|coverage)\//;
+const SCAN_SKIP_FILE = /(\.test\.|\.spec\.|\/fixtures\/|_demo-fixtures|\/idl\/)/;
+
+export function listSourceFiles({ root = ROOT } = {}) {
+ let files;
+ try {
+ const out = execFileSync('git', ['ls-files'], { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+ files = out.split('\n').filter(Boolean);
+ } catch {
+ files = listOnDisk(root);
+ }
+ return files.filter((f) => SCAN_EXTS.test(f) && !SCAN_SKIP.test(`/${f}`) && !SCAN_SKIP_FILE.test(`/${f}`));
+}
+
+function listOnDisk(root) {
+ const out = [];
+ const stack = [''];
+ const skipDir = new Set(['node_modules', '.git', 'dist', 'dist-lib', 'build', '.vercel', 'coverage']);
+ while (stack.length) {
+ const rel = stack.pop();
+ let entries;
+ try {
+ entries = readdirSync(resolve(root, rel), { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const e of entries) {
+ if (skipDir.has(e.name)) continue;
+ const r = rel ? `${rel}/${e.name}` : e.name;
+ if (e.isDirectory()) stack.push(r);
+ else out.push(r);
+ }
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Parity / drift scan (deterministic — always runs, always hard-fails)
+// ---------------------------------------------------------------------------
+
+const BASE58 = '[1-9A-HJ-NP-Za-km-z]';
+const PUMP_LITERAL = new RegExp(`['"\`](${BASE58}{42,43}pump)['"\`]`, 'g');
+
+/**
+ * Scans first-party source for:
+ * - rogue $THREE drift: any hardcoded `…pump` mint literal that is not the
+ * canonical $THREE CA (drift OR a forbidden second coin).
+ * - named-constant drift: any assignment to a canonical constant identifier
+ * whose base58 literal differs from the canonical address.
+ *
+ * Returns { problems } — each with file, line, and a precise diff string.
+ */
+export function scanForDrift(registry, { root = ROOT, files = listSourceFiles({ root }) } = {}) {
+ const problems = [];
+ // name → {address,label} lookup for the constant-assignment scan.
+ const byName = new Map();
+ for (const entry of registry) for (const n of entry.names) byName.set(n, entry);
+ const nameAlternation = [...byName.keys()].sort((a, b) => b.length - a.length).join('|');
+ // `NAME = … 'BASE58'` or `NAME = new PublicKey('BASE58')`. \b guards against
+ // matching USDC_MINT inside USDC_MINT_DEVNET etc.
+ const assignRe = new RegExp(`\\b(${nameAlternation})\\b\\s*(?::[^=]+)?=\\s*(?:new\\s+PublicKey\\(\\s*)?['"\`](${BASE58}{32,44})['"\`]`, 'g');
+
+ for (const rel of files) {
+ let text;
+ try {
+ text = readFileSync(resolve(root, rel), 'utf8');
+ } catch {
+ continue;
+ }
+ const lines = text.split('\n');
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+
+ // 1. rogue / drifted $THREE mint
+ for (const mt of line.matchAll(PUMP_LITERAL)) {
+ if (mt[1] !== THREE_MINT) {
+ problems.push({
+ type: 'rogue-coin',
+ file: rel,
+ line: i + 1,
+ detail: `hardcoded pump.fun mint "${mt[1]}" is not the canonical $THREE CA ${THREE_MINT} — $THREE is the only coin (CLAUDE.md); fix or remove`,
+ });
+ }
+ }
+
+ // 2. drifted canonical constant
+ for (const mt of line.matchAll(assignRe)) {
+ const entry = byName.get(mt[1]);
+ const got = mt[2];
+ if (entry && got !== entry.address) {
+ // A devnet/test variant legitimately differs — skip lines that
+ // self-identify as such (e.g. SOLANA_USDC_MINT_DEVNET on its own line).
+ if (/devnet|testnet|localnet/i.test(line)) continue;
+ problems.push({
+ type: 'const-drift',
+ file: rel,
+ line: i + 1,
+ detail: `${mt[1]} = ${got} but canonical ${entry.label} is ${entry.address}`,
+ });
+ }
+ }
+ }
+ }
+ return problems;
+}
+
+// ---------------------------------------------------------------------------
+// Live on-chain provenance (best-effort — warns on transport error, fails on a
+// confirmed wrong-kind account)
+// ---------------------------------------------------------------------------
+
+function rpcEndpoint(env = process.env) {
+ if (env.SOLANA_RPC_URL && !/api\.mainnet-beta\.solana\.com/.test(env.SOLANA_RPC_URL)) return env.SOLANA_RPC_URL;
+ if (env.HELIUS_API_KEY) return `https://mainnet.helius-rpc.com/?api-key=${env.HELIUS_API_KEY}`;
+ return env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+}
+
+async function getAccountInfo(url, address) {
+ try {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getAccountInfo', params: [address, { encoding: 'jsonParsed' }] }),
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
+ const json = await res.json();
+ if (json.error) return { ok: false, error: json.error.message || 'rpc error' };
+ return { ok: true, value: json.result?.value ?? null };
+ } catch (err) {
+ return { ok: false, error: err?.message || 'unreachable' };
+ }
+}
+
+/**
+ * For each canonical address, fetch the account and assert it is the right kind:
+ * - program: exists & executable.
+ * - token-mint: exists & owned by SPL Token or Token-2022 program.
+ * - token-2022-mint: exists & owned by the Token-2022 program specifically
+ * ($THREE is a Token-2022 mint; legacy-token code paths
+ * for it would derive the wrong ATA).
+ */
+export async function checkLiveProvenance(registry, { env = process.env } = {}) {
+ const url = rpcEndpoint(env);
+ const wrong = [];
+ const unreachable = [];
+ const ok = [];
+
+ for (const entry of registry) {
+ const r = await getAccountInfo(url, entry.address);
+ const ctx = { ...entry, endpoint: url };
+ if (!r.ok) {
+ unreachable.push({ ...ctx, error: r.error });
+ continue;
+ }
+ if (r.value === null) {
+ wrong.push({ ...ctx, reason: 'account does not exist on mainnet' });
+ continue;
+ }
+ const owner = r.value.owner;
+ const program = r.value.data?.program;
+ if (entry.kind === 'program') {
+ if (r.value.executable) ok.push({ ...ctx, note: 'executable' });
+ else wrong.push({ ...ctx, reason: `not executable (owner ${owner})` });
+ } else if (entry.kind === 'token-2022-mint') {
+ if (owner === TOKEN_2022_PROGRAM && program === 'spl-token-2022') ok.push({ ...ctx, note: 'token-2022 mint' });
+ else wrong.push({ ...ctx, reason: `expected a Token-2022 mint, got owner ${owner} (${program})` });
+ } else if (entry.kind === 'token-mint') {
+ if ((owner === SPL_TOKEN_PROGRAM || owner === TOKEN_2022_PROGRAM) && program?.startsWith('spl-token')) ok.push({ ...ctx, note: `${program} mint` });
+ else wrong.push({ ...ctx, reason: `expected an SPL mint, got owner ${owner} (${program})` });
+ }
+ }
+ return { wrong, unreachable, ok };
+}
+
+// ---------------------------------------------------------------------------
+// CLI
+// ---------------------------------------------------------------------------
+
+const isMain = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
+if (isMain) {
+ const start = Date.now();
+ let failed = false;
+
+ let registry;
+ try {
+ registry = await loadCanonical();
+ } catch (err) {
+ console.error(`[verify:solana] FAIL — ${err.message}`);
+ process.exit(1);
+ }
+
+ const problems = scanForDrift(registry);
+ if (problems.length) {
+ failed = true;
+ const rogue = problems.filter((p) => p.type === 'rogue-coin');
+ const drift = problems.filter((p) => p.type === 'const-drift');
+ if (rogue.length) console.error(`[verify:solana] FAIL — ${rogue.length} non-$THREE coin / drifted mint literal(s):`);
+ for (const p of rogue) console.error(` ${p.file}:${p.line} — ${p.detail}`);
+ if (drift.length) console.error(`[verify:solana] FAIL — ${drift.length} drifted Solana constant(s):`);
+ for (const p of drift) console.error(` ${p.file}:${p.line} — ${p.detail}`);
+ } else {
+ console.log(`[verify:solana] parity OK — $THREE mint + ${registry.length - 1} canonical Solana addresses consistent across all first-party source`);
+ }
+
+ const liveOn = (process.env.VERIFY_SOLANA_LIVE ?? '1') !== '0';
+ if (liveOn) {
+ const { wrong, unreachable, ok } = await checkLiveProvenance(registry);
+ for (const e of ok) console.log(`[verify:solana] live ${e.label} ${e.address} — ${e.note}`);
+ if (unreachable.length) {
+ console.warn(`[verify:solana] WARN — ${unreachable.length} account(s) unreachable (network — not failing the build):`);
+ for (const u of unreachable) console.warn(` ${u.label} ${u.address} — ${u.error}`);
+ }
+ if (wrong.length) {
+ failed = true;
+ console.error(`[verify:solana] FAIL — ${wrong.length} account(s) are the wrong kind on-chain:`);
+ for (const w of wrong) console.error(` ${w.label} ${w.address} — ${w.reason}`);
+ }
+ console.log(`[verify:solana] live check — ${ok.length} verified, ${wrong.length} wrong, ${unreachable.length} unreachable`);
+ } else {
+ console.log('[verify:solana] live provenance check skipped (VERIFY_SOLANA_LIVE=0)');
+ }
+
+ const elapsed = ((Date.now() - start) / 1000).toFixed(1);
+ if (failed) {
+ console.error(`\n[verify:solana] failed in ${elapsed}s`);
+ process.exit(1);
+ }
+ console.log(`[verify:solana] clean in ${elapsed}s`);
+}
diff --git a/src/agent-detail.css b/src/agent-detail.css
index 62a42294a..9319432ba 100644
--- a/src/agent-detail.css
+++ b/src/agent-detail.css
@@ -2114,17 +2114,19 @@ a {
color: var(--ad-dim);
font-size: 12px;
}
-.ad-launch-mcap {
- margin-left: auto;
- font-variant-numeric: tabular-nums;
- color: var(--ad-muted);
- font-size: 12px;
-}
.ad-launch-time {
color: var(--ad-dim);
font-size: 12px;
white-space: nowrap;
}
+/* Shared coin-status `row` variant fills the launch-history anchor. */
+.ad-launch-row .csc-row {
+ width: 100%;
+}
+/* Token chip — shared coin-status `chip` variant, spaced above the CTA. */
+.ad-token-chip {
+ margin-bottom: 10px;
+}
.ad-launch-feed-link {
margin-top: 6px;
font-size: 12.5px;
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 691b8d5ec..bda2fe32e 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -26,6 +26,7 @@ const solanaWeb3 = {
};
import { openSwapModal } from './swap-jupiter.js';
import { onchainBadgeEl } from './shared/onchain-badge.js';
+import { mountValidationBadge } from './shared/validation-badge.js';
import { seeInWorldHref, agentAvatarGlb } from './shared/agent-3d.js';
import { renderError as renderAsyncError } from './shared/async-state.js';
import { openCoinLaunch } from './shared/agent-coin.js';
@@ -34,6 +35,23 @@ import { showSharePanel } from './shared/share.js';
import { enrichAgentDetail, renderEmbed as renderAgentEmbed } from './agent-detail-market.js';
import { log } from './shared/log.js';
import { mountViewSwitcher } from './view-switcher.js';
+import { mountCoinStatus } from './pump/coin-status-card.js';
+
+// Live coin-status widgets mounted on this page (token chip + launch-history
+// rows). Tracked so a re-render (e.g. avatar refresh) tears down their refresh
+// timers before remounting, rather than leaking intervals.
+const coinStatusHandles = [];
+
+function destroyCoinStatus() {
+ while (coinStatusHandles.length) {
+ const h = coinStatusHandles.pop();
+ try {
+ h.destroy();
+ } catch {
+ /* ignore */
+ }
+ }
+}
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -98,7 +116,8 @@ function pill(text, accent = '') {
// ── Launch history ───────────────────────────────────────────────────────────
// Every coin this agent has launched through the platform, newest first, from
// GET /api/pump/by-agent (pump_agent_mints registry). Live market caps stream
-// in per row from /api/pump/coin. Links into the public /launches feed.
+// in per row from the shared coin-status widget (`row` variant). Links into the
+// public /launches feed.
function launchTimeAgo(iso) {
const t = new Date(iso).getTime();
@@ -110,14 +129,6 @@ function launchTimeAgo(iso) {
return new Date(t).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
-function launchUsdCompact(n) {
- if (!Number.isFinite(n)) return '';
- if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;
- if (n >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;
- if (n >= 1e3) return `$${(n / 1e3).toFixed(1)}K`;
- return `$${n.toFixed(0)}`;
-}
-
async function renderLaunchHistory(container, agent) {
if (!agent.id) return;
let coins = [];
@@ -152,32 +163,25 @@ async function renderLaunchHistory(container, agent) {
const href = isDevnet
? `https://explorer.solana.com/address/${coin.mint}?cluster=devnet`
: `https://pump.fun/${coin.mint}`;
- const mcapEl = el('span', { class: 'ad-launch-mcap' });
- const row = el(
- 'a',
- {
- class: 'ad-launch-row',
- href,
- target: '_blank',
- rel: 'noopener noreferrer',
- 'aria-label': `${coin.symbol || coin.name || 'coin'} on ${isDevnet ? 'Solana Explorer' : 'pump.fun'}`,
- },
- [
+ const row = el('a', {
+ class: 'ad-launch-row',
+ href,
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ 'aria-label': `${coin.symbol || coin.name || 'coin'} on ${isDevnet ? 'Solana Explorer' : 'pump.fun'}`,
+ });
+ box.appendChild(row);
+ if (isDevnet) {
+ // Devnet mints have no pump.fun market data — render the static row.
+ row.append(
el('span', { class: 'ad-launch-symbol', text: coin.symbol ? `$${coin.symbol}` : coin.name || '—' }),
el('span', { class: 'ad-mono ad-launch-mint', text: shortAddr(coin.mint) }),
- mcapEl,
el('span', { class: 'ad-launch-time', text: launchTimeAgo(coin.created_at) }),
- ],
- );
- box.appendChild(row);
- if (!isDevnet) {
- fetch(`/api/pump/coin?mint=${encodeURIComponent(coin.mint)}`)
- .then((r) => (r.ok ? r.json() : null))
- .then((c) => {
- const cap = Number(c?.usd_market_cap);
- if (Number.isFinite(cap)) mcapEl.textContent = launchUsdCompact(cap);
- })
- .catch(() => {});
+ );
+ } else {
+ // Live market cap + time stream in through the shared widget — one
+ // /api/pump/coin fetch per row, mapped and formatted in one place.
+ coinStatusHandles.push(mountCoinStatus(row, coin.mint, { variant: 'row' }));
}
}
}
@@ -419,6 +423,27 @@ function render(agent) {
status.insertAdjacentElement('afterend', onchainBadge);
}
+ // Validation attestation badge — only for EVM ERC-8004 agents, read
+ // walletlessly from the on-chain ValidationRegistry. Re-mountable on refresh.
+ let validationSlot = document.getElementById('ad-validation-badge');
+ if (agent.chainId && agent.erc8004AgentId) {
+ if (!validationSlot) {
+ validationSlot = document.createElement('span');
+ validationSlot.id = 'ad-validation-badge';
+ validationSlot.style.marginLeft = '8px';
+ (onchainBadge || status).insertAdjacentElement('afterend', validationSlot);
+ }
+ mountValidationBadge({
+ container: validationSlot,
+ chainId: agent.chainId,
+ agentId: agent.erc8004AgentId,
+ isOwner: agent.isOwner,
+ glbUrl: agent.glbUrl || undefined,
+ });
+ } else {
+ validationSlot?.remove();
+ }
+
$('ad-id-short').textContent = shortAddr(agent.id);
$('ad-id-short').dataset.full = agent.id;
$('ad-asset-kind').textContent = agent.assetKind || 'Core Asset';
@@ -440,14 +465,28 @@ function render(agent) {
$('ad-holdings-addr').dataset.full = agent.wallet;
$('ad-holdings-sol').textContent = String(agent.solBalance ?? 0);
+ // A re-render (avatar refresh) clears the token body below; tear down any
+ // coin-status widgets first so their refresh timers don't leak.
+ destroyCoinStatus();
+
if (agent.token) {
$('ad-token-body').classList.remove('ad-muted');
$('ad-token-body').textContent = '';
- const tokenRow = el('div', { class: 'ad-row ad-row-split' }, [
- el('span', { text: agent.token.symbol || 'TOKEN' }),
- el('span', { class: 'ad-mono', text: shortAddr(agent.token.mint) }),
- ]);
- $('ad-token-body').appendChild(tokenRow);
+ // Live token chip — symbol · price · market cap · graduation %, streamed
+ // and formatted by the shared coin-status widget. Devnet tokens (no
+ // pump.fun market data) fall back to a static symbol + mint row.
+ if (agent.token.cluster === 'devnet') {
+ $('ad-token-body').appendChild(
+ el('div', { class: 'ad-row ad-row-split' }, [
+ el('span', { text: agent.token.symbol || 'TOKEN' }),
+ el('span', { class: 'ad-mono', text: shortAddr(agent.token.mint) }),
+ ]),
+ );
+ } else {
+ const chipBox = el('div', { class: 'ad-token-chip' });
+ $('ad-token-body').appendChild(chipBox);
+ coinStatusHandles.push(mountCoinStatus(chipBox, agent.token.mint, { variant: 'chip' }));
+ }
const dashLink =
agent.token.pumpfun_url ||
(agent.token.cluster === 'devnet'
@@ -1644,6 +1683,12 @@ function normalize(rec, avatar) {
// The /api/agents/:id endpoint only includes `user_id` in the response when
// the requester is the owner — see api/agents.js decorate(row, isOwner).
isOwner: !!rec.user_id,
+ // On-chain ERC-8004 identifiers for the validation attestation badge.
+ // Present only for EVM-registered agents (Solana token agents have no
+ // erc8004_agent_id, so the validation badge is correctly skipped for them).
+ chainId: Number(onchain?.chain_id ?? rec.chain_id) || null,
+ erc8004AgentId: rec.erc8004_agent_id != null ? String(rec.erc8004_agent_id) : null,
+ glbUrl: rec.avatar_glb_url || onchain?.body_uri || meta.glb_url || null,
rawMetadata: rec,
};
}
diff --git a/src/agent-home-pumpfun.js b/src/agent-home-pumpfun.js
index 52c62b887..63da04274 100644
--- a/src/agent-home-pumpfun.js
+++ b/src/agent-home-pumpfun.js
@@ -21,6 +21,7 @@
import { ACTION_TYPES } from './agent-protocol.js';
import { THREE_WS_MARK } from './solana/vanity/brand.js';
+import { mountCoinStatus } from './pump/coin-status-card.js';
const REFRESH_MS = 30_000;
const QUOTE_DEBOUNCE_MS = 250;
@@ -88,6 +89,16 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
cardBody.className = 'pumpfun-card-body';
root.appendChild(cardBody);
+ // Canonical live market readout (symbol · price · market cap · graduation %)
+ // rendered by the shared coin-status widget. Kept as a persistent node so the
+ // frequent innerHTML re-renders below (trade input, quotes, bot progress)
+ // re-parent it instead of remounting — the widget owns one /api/pump/coin
+ // fetch + 30s refresh, regardless of how often the card re-renders.
+ const coinStatusEl = document.createElement('div');
+ coinStatusEl.className = 'pumpfun-coin-status';
+ let coinStatusHandle = null;
+ let coinStatusMint = null;
+
const launchCard = () => {
const isGrinding = state.stampPhase === 'grinding';
const isStamped = state.stampPhase === 'done';
@@ -133,8 +144,6 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
};
const statusCard = (s) => {
- const pct = s.progressPct != null ? `${s.progressPct.toFixed(1)}%` : '—';
- const cap = s.marketCap ? formatLamports(s.marketCap) : '—';
const explorer =
s.network === 'devnet'
? `https://pump.fun/coin/${s.mint}?cluster=devnet`
@@ -147,17 +156,7 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
<span class="pumpfun-card-title">${escapeHtml(s.symbol || 'Token')}</span>
<a class="pumpfun-card-link" href="${explorer}" target="_blank" rel="noopener" title="Open on pump.fun">↗</a>
</div>
- <div class="pumpfun-stats">
- <div class="pumpfun-stat">
- <span class="pumpfun-stat-label">Market cap</span>
- <span class="pumpfun-stat-value">${cap}</span>
- </div>
- <div class="pumpfun-stat">
- <span class="pumpfun-stat-label">${grad ? 'Status' : 'To graduation'}</span>
- <span class="pumpfun-stat-value">${grad ? 'Graduated' : pct}</span>
- </div>
- </div>
- ${grad ? '' : `<div class="pumpfun-progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${(s.progressPct || 0).toFixed(1)}"><div class="pumpfun-progress-bar" style="width:${Math.min(100, s.progressPct || 0)}%"></div></div>`}
+ <div id="pf-coin-status-mount" class="pumpfun-coin-status-mount"></div>
<button class="pumpfun-card-mint" data-action="open-feed" title="Open live feed for this mint">${shortMint(s.mint)}</button>
<div class="pumpfun-card-actions">
<button class="pumpfun-btn ${s.tradeOpen === 'buy' ? 'pumpfun-btn--active' : ''}" data-action="toggle-buy">Buy</button>
@@ -307,6 +306,7 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
return;
}
cardBody.innerHTML = state.mint ? statusCard(state) : launchCard();
+ syncCoinStatus();
bind();
// Restore focus to the input after re-render so typing stays uninterrupted.
if (state.tradeOpen) {
@@ -319,6 +319,21 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
}
};
+ // Re-parent the persistent coin-status node into the freshly rendered mount
+ // point and (re)mount the shared widget when the active mint changes. Moving
+ // the live node preserves the widget's fetch + refresh timer across renders;
+ // devnet mints have no pump.fun market data, so the widget is skipped there.
+ const syncCoinStatus = () => {
+ const mountPt = cardBody.querySelector('#pf-coin-status-mount');
+ if (!mountPt || !state.mint || state.network === 'devnet') return;
+ mountPt.appendChild(coinStatusEl);
+ if (coinStatusMint !== state.mint) {
+ if (coinStatusHandle) coinStatusHandle.destroy();
+ coinStatusMint = state.mint;
+ coinStatusHandle = mountCoinStatus(coinStatusEl, state.mint, { variant: 'chip' });
+ }
+ };
+
const bind = () => {
const launchBtn = cardBody.querySelector('#pf-launch-btn');
if (launchBtn) {
@@ -827,6 +842,7 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
if (refreshTimer) clearInterval(refreshTimer);
if (quoteTimer) clearTimeout(quoteTimer);
if (unsubProtocol) unsubProtocol();
+ if (coinStatusHandle) coinStatusHandle.destroy();
root.remove();
},
refresh,
diff --git a/src/agent-home.js b/src/agent-home.js
index 04ea301b4..73e11de3c 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -14,6 +14,7 @@ import { mountPumpFunCard } from './agent-home-pumpfun.js';
import { mountAgentSolanaWalletCard } from './agent-solana-wallet.js';
import { mountAgentVanityGrinderCard } from './agent-vanity-grinder.js';
import { mountAgentEthVanityCard } from './agent-eth-vanity-card.js';
+import { mountAgentOnchainCard } from './agent-onchain-card.js';
import { mountClaimsPanel } from './agent-home-claims.js';
const ACTION_ICONS = {
@@ -71,6 +72,7 @@ export class AgentHome {
destroy() {
if (this._destroyClaims) this._destroyClaims();
+ if (this._onchainCard?.destroy) this._onchainCard.destroy();
if (this._panel) this._panel.remove();
clearInterval(this._emotionInterval);
this.protocol.off('*', this._onAnyAction);
@@ -214,6 +216,14 @@ export class AgentHome {
// with 401s. Caller can pass opts.isOwner to override identity state.
const isOwner = this.isOwner !== null ? this.isOwner : this.identity?.isOwner;
if (this.identity?.id && isOwner === true) {
+ // On-chain identity card — register an existing agent on ERC-8004,
+ // reusing its stored body/persona/voice/skills, or show its binding.
+ try {
+ this._onchainCard = mountAgentOnchainCard({ panel, identity: this.identity });
+ } catch {
+ /* card is optional */
+ }
+
let walletCard = null;
try {
walletCard = mountAgentSolanaWalletCard({
diff --git a/src/agent-identity.js b/src/agent-identity.js
index 262d5b1b1..8744f27f2 100644
--- a/src/agent-identity.js
+++ b/src/agent-identity.js
@@ -380,7 +380,16 @@ function _normalise(apiRecord) {
createdAt: apiRecord.created_at
? new Date(apiRecord.created_at).getTime()
: apiRecord.createdAt || Date.now(),
- isRegistered: Boolean(apiRecord.erc8004_agent_id || apiRecord.isRegistered),
+ // On-chain when any registration signal is present: legacy EVM column,
+ // the canonical meta.onchain block (surfaced as `onchain`/`is_registered`
+ // by api/agents decorate), or an explicit flag.
+ isRegistered: Boolean(
+ apiRecord.erc8004_agent_id ||
+ apiRecord.isRegistered ||
+ apiRecord.is_registered ||
+ apiRecord.onchain ||
+ apiRecord.meta?.onchain,
+ ),
// Server decorates owner-only fields (user_id, wallet_address, system_prompt,
// etc.) only when the requester owns the agent — see api/agents.js decorate().
// Use user_id presence as the canonical owner signal so visitor flows don't
diff --git a/src/agent-onchain-card.js b/src/agent-onchain-card.js
new file mode 100644
index 000000000..aa8e65085
--- /dev/null
+++ b/src/agent-onchain-card.js
@@ -0,0 +1,284 @@
+/**
+ * Agent On-Chain Card — owner-only profile control.
+ * -------------------------------------------------
+ * Surfaces the "Register on-chain" action on an existing agent's profile and
+ * renders every state of its ERC-8004 binding: not-registered (CTA), pending
+ * (tx in flight, live log), registered (badge + network + agent id + explorer /
+ * card links), and error (actionable + retry).
+ *
+ * Binding reuses the agent's stored body, persona, voice, and skills — no
+ * re-entry — via bindExistingAgentOnchain(). The flow is idempotent: if the
+ * agent is already bound on the chosen chain, it shows the existing identity
+ * instead of minting a second token.
+ *
+ * Mounted from src/agent-home.js alongside the other owner cards.
+ */
+
+import {
+ getOnchainStatus,
+ onchainBadgeHTML,
+ ensureOnchainBadgeStyles,
+} from './shared/onchain-badge.js';
+import {
+ CHAIN_META,
+ DEFAULT_CHAIN_ID,
+ supportedChainIdsGrouped,
+} from './erc8004/chain-meta.js';
+import { resolveURI } from './ipfs.js';
+
+const STYLE_ID = 'agent-onchain-card-styles';
+
+function esc(s) {
+ return String(s == null ? '' : s).replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+/** A minimal agent-record shape the badge + status helpers understand. */
+function statusShape(identity) {
+ const meta = identity.meta || {};
+ return {
+ onchain: meta.onchain || null,
+ meta,
+ is_registered: identity.isRegistered,
+ erc8004_agent_id: meta.onchain?.onchain_id || null,
+ };
+}
+
+/**
+ * @param {{ panel: HTMLElement, identity: import('./agent-identity.js').AgentIdentity }} opts
+ * @returns {{ destroy: () => void } | null}
+ */
+export function mountAgentOnchainCard({ panel, identity }) {
+ if (!panel || !identity?.id) return null;
+ ensureOnchainBadgeStyles();
+ ensureStyles();
+
+ const section = document.createElement('section');
+ section.className = 'agent-onchain-card';
+ section.setAttribute('aria-label', 'On-chain identity');
+
+ // Place it directly above the permissions panel (or before the memory bar).
+ const anchor =
+ panel.querySelector('#agent-permissions-container') ||
+ panel.querySelector('#agent-memory-bar');
+ if (anchor) panel.insertBefore(section, anchor);
+ else panel.appendChild(section);
+
+ let busy = false;
+
+ function render() {
+ const status = getOnchainStatus(statusShape(identity));
+ section.innerHTML = status ? registeredHTML(status) : ctaHTML();
+ wire(status);
+ }
+
+ function ctaHTML() {
+ const { mainnets, testnets } = supportedChainIdsGrouped();
+ const opt = (id) =>
+ `<option value="${id}"${id === DEFAULT_CHAIN_ID ? ' selected' : ''}>${esc(CHAIN_META[id].name)}</option>`;
+ return `
+ <div class="aoc-head">
+ <span class="aoc-title">On-chain identity</span>
+ <span class="aoc-tag">Not registered</span>
+ </div>
+ <p class="aoc-sub">Mint an ERC-8004 identity for this agent. Reuses its 3D model, persona, voice, and skills, and pins a full agent manifest so it stays portable across the open web.</p>
+ <div class="aoc-controls">
+ <label class="aoc-field">
+ <span class="aoc-field-label">Network</span>
+ <select class="aoc-chain-select" aria-label="Target network">
+ <optgroup label="Mainnet">${mainnets.map(opt).join('')}</optgroup>
+ <optgroup label="Testnet">${testnets.map(opt).join('')}</optgroup>
+ </select>
+ </label>
+ <button type="button" class="aoc-btn aoc-register">
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2 4 5v6c0 5 3.4 9.4 8 11 4.6-1.6 8-6 8-11V5l-8-3zm-1.2 14.2L7 12.4l1.4-1.4 2.4 2.4 4.8-4.8L17 10l-6.2 6.2z"/></svg>
+ <span>Register on-chain</span>
+ </button>
+ </div>
+ <div class="aoc-log" role="status" aria-live="polite" hidden></div>
+ <div class="aoc-error" role="alert" hidden></div>
+ `;
+ }
+
+ function registeredHTML(status) {
+ const badge = onchainBadgeHTML(statusShape(identity), { size: 'md', label: 'On-chain' });
+ const onchain = identity.meta?.onchain || {};
+ const cardUri = onchain.metadata_uri ? resolveURI(onchain.metadata_uri) : null;
+ const agentIdLabel = status.registry || (onchain.onchain_id ? `#${onchain.onchain_id}` : '—');
+ return `
+ <div class="aoc-head">
+ <span class="aoc-title">On-chain identity</span>
+ ${badge}
+ </div>
+ <dl class="aoc-meta">
+ <div class="aoc-meta-row"><dt>Network</dt><dd>${esc(status.chainLabel)}</dd></div>
+ <div class="aoc-meta-row"><dt>Agent ID</dt><dd>${esc(agentIdLabel)}</dd></div>
+ </dl>
+ <div class="aoc-links">
+ ${
+ status.explorerUrl
+ ? `<a class="aoc-link" href="${esc(status.explorerUrl)}" target="_blank" rel="noopener noreferrer">View on explorer ↗</a>`
+ : ''
+ }
+ ${
+ status.txExplorerUrl
+ ? `<a class="aoc-link" href="${esc(status.txExplorerUrl)}" target="_blank" rel="noopener noreferrer">View transaction ↗</a>`
+ : ''
+ }
+ ${
+ cardUri
+ ? `<a class="aoc-link" href="${esc(cardUri)}" target="_blank" rel="noopener noreferrer">View agent card ↗</a>`
+ : ''
+ }
+ </div>
+ `;
+ }
+
+ function wire(status) {
+ if (status) return; // registered state has no interactive controls beyond links
+
+ const btn = section.querySelector('.aoc-register');
+ const select = section.querySelector('.aoc-chain-select');
+ const logEl = section.querySelector('.aoc-log');
+ const errEl = section.querySelector('.aoc-error');
+
+ const appendLog = (msg) => {
+ logEl.hidden = false;
+ const line = document.createElement('div');
+ line.className = 'aoc-log-line';
+ line.textContent = msg;
+ logEl.appendChild(line);
+ logEl.scrollTop = logEl.scrollHeight;
+ };
+
+ btn?.addEventListener('click', async () => {
+ if (busy) return;
+ busy = true;
+ const chainId = Number(select.value) || DEFAULT_CHAIN_ID;
+ errEl.hidden = true;
+ errEl.textContent = '';
+ logEl.innerHTML = '';
+ logEl.hidden = false;
+ btn.disabled = true;
+ select.disabled = true;
+ btn.classList.add('is-busy');
+ btn.querySelector('span').textContent = 'Registering…';
+
+ try {
+ const { bindExistingAgentOnchain } = await import('./erc8004/agent-registry.js');
+ const result = await bindExistingAgentOnchain(identity.id, chainId, {
+ onStatus: appendLog,
+ });
+
+ // Reflect the new identity locally so the badge + state update without
+ // a reload (and persist for the next mount).
+ if (result.onchain && identity._record) {
+ identity._record.meta = { ...(identity._record.meta || {}), onchain: result.onchain };
+ identity._record.isRegistered = true;
+ identity._persist?.();
+ }
+ injectNameBadge();
+ render();
+ } catch (err) {
+ errEl.hidden = false;
+ errEl.textContent = friendlyError(err);
+ btn.disabled = false;
+ select.disabled = false;
+ btn.classList.remove('is-busy');
+ btn.querySelector('span').textContent = 'Try again';
+ } finally {
+ busy = false;
+ }
+ });
+ }
+
+ // If the name-row badge isn't already present (it keys on the agent record at
+ // first paint), inject it now that the agent is on-chain.
+ function injectNameBadge() {
+ const nameRow = panel.querySelector('.agent-home-name-row');
+ if (!nameRow || nameRow.querySelector('.agent-home-badge, .tws-ocb')) return;
+ const badge = onchainBadgeHTML(statusShape(identity), { size: 'sm', showChain: false });
+ if (!badge) return;
+ const tpl = document.createElement('template');
+ tpl.innerHTML = badge.trim();
+ const node = tpl.content.firstElementChild;
+ if (node) nameRow.appendChild(node);
+ }
+
+ render();
+
+ return {
+ destroy() {
+ section.remove();
+ },
+ };
+}
+
+function friendlyError(err) {
+ const m = String(err?.message || err || 'Registration failed.');
+ if (/user rejected|denied|rejected the request/i.test(m)) {
+ return 'You cancelled the wallet request. Click "Try again" when ready.';
+ }
+ if (/no wallet detected/i.test(m)) {
+ return 'No wallet detected. Install a wallet extension (MetaMask, Coinbase Wallet) and try again.';
+ }
+ if (/insufficient funds/i.test(m)) {
+ return 'Insufficient funds for gas on the target network. Top up and try again.';
+ }
+ return m;
+}
+
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+.agent-onchain-card{margin:12px 0;padding:14px;border:1px solid var(--border,rgba(255,255,255,.1));
+ border-radius:12px;background:var(--surface-2,rgba(255,255,255,.03));}
+.aoc-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px;}
+.aoc-title{font:600 12px/1.2 ui-sans-serif,system-ui,sans-serif;letter-spacing:.02em;
+ text-transform:uppercase;opacity:.7;}
+.aoc-tag{font:500 10px/1 ui-sans-serif,system-ui,sans-serif;padding:3px 8px;border-radius:999px;
+ color:var(--muted,#9aa);background:rgba(148,163,184,.14);border:1px solid rgba(148,163,184,.28);}
+.aoc-sub{margin:0 0 12px;font:400 12.5px/1.5 ui-sans-serif,system-ui,sans-serif;opacity:.75;}
+.aoc-controls{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap;}
+.aoc-field{display:flex;flex-direction:column;gap:4px;flex:1 1 140px;min-width:0;}
+.aoc-field-label{font:500 10.5px/1 ui-sans-serif,system-ui,sans-serif;opacity:.6;
+ text-transform:uppercase;letter-spacing:.04em;}
+.aoc-chain-select{appearance:none;width:100%;padding:8px 10px;border-radius:8px;
+ border:1px solid var(--border,rgba(255,255,255,.14));background:var(--surface,rgba(0,0,0,.25));
+ color:inherit;font:500 13px/1 ui-sans-serif,system-ui,sans-serif;cursor:pointer;}
+.aoc-chain-select:focus-visible{outline:2px solid #34d399;outline-offset:1px;}
+.aoc-btn{display:inline-flex;align-items:center;gap:7px;padding:9px 14px;border-radius:8px;border:0;
+ cursor:pointer;font:600 13px/1 ui-sans-serif,system-ui,sans-serif;color:#04130d;
+ background:linear-gradient(180deg,#5ee9b5,#2bb98a);box-shadow:0 1px 0 rgba(255,255,255,.25) inset;
+ transition:transform .12s ease,filter .12s ease,opacity .12s ease;}
+.aoc-btn:hover{filter:brightness(1.06);transform:translateY(-1px);}
+.aoc-btn:active{transform:translateY(0);}
+.aoc-btn:focus-visible{outline:2px solid #34d399;outline-offset:2px;}
+.aoc-btn:disabled{cursor:default;opacity:.7;transform:none;filter:none;}
+.aoc-btn.is-busy svg{animation:aoc-spin .9s linear infinite;}
+@keyframes aoc-spin{to{transform:rotate(360deg);}}
+@media (prefers-reduced-motion: reduce){.aoc-btn.is-busy svg{animation:none;}}
+.aoc-log{margin-top:10px;max-height:140px;overflow:auto;padding:8px 10px;border-radius:8px;
+ background:rgba(0,0,0,.28);border:1px solid rgba(255,255,255,.08);
+ font:400 11.5px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;opacity:.9;}
+.aoc-log-line{white-space:pre-wrap;word-break:break-word;}
+.aoc-log-line+.aoc-log-line{margin-top:2px;}
+.aoc-error{margin-top:10px;padding:9px 11px;border-radius:8px;color:#fca5a5;
+ background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.32);
+ font:400 12px/1.45 ui-sans-serif,system-ui,sans-serif;}
+.aoc-meta{display:flex;gap:18px;margin:0 0 10px;flex-wrap:wrap;}
+.aoc-meta-row{display:flex;flex-direction:column;gap:2px;}
+.aoc-meta dt{font:500 10px/1 ui-sans-serif,system-ui,sans-serif;opacity:.55;
+ text-transform:uppercase;letter-spacing:.04em;}
+.aoc-meta dd{margin:0;font:600 13px/1.2 ui-sans-serif,system-ui,sans-serif;}
+.aoc-links{display:flex;gap:14px;flex-wrap:wrap;}
+.aoc-link{font:500 12px/1 ui-sans-serif,system-ui,sans-serif;color:#5ee9b5;text-decoration:none;}
+.aoc-link:hover{text-decoration:underline;}
+.aoc-link:focus-visible{outline:2px solid #34d399;outline-offset:2px;border-radius:3px;}
+`;
+ (document.head || document.documentElement).appendChild(style);
+}
diff --git a/src/erc8004/agent-registry.js b/src/erc8004/agent-registry.js
index d124a671a..31bf1e723 100644
--- a/src/erc8004/agent-registry.js
+++ b/src/erc8004/agent-registry.js
@@ -452,6 +452,35 @@ export async function registerAgent({
// Non-fatal — the cron crawler will pick it up within 15 minutes.
}
+ // ── 9. Kick a best-effort glTF validation attestation. The platform
+ // validator key signs recordValidation() server-side; this is async and
+ // non-blocking — a validation failure (or unconfigured validator) never
+ // affects the registration. The "Validated" badge appears once it lands.
+ if (glbUrl) {
+ log('Requesting validation attestation…');
+ fetch('/api/erc8004/validate', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ chainId, agentId: String(agentId), glbUrl }),
+ })
+ .then(async (r) => {
+ const data = await r.json().catch(() => ({}));
+ if (r.ok && data?.validation) {
+ log(
+ data.validation.passed
+ ? 'Validation attested on-chain ✓'
+ : 'Validation recorded (model has issues).',
+ );
+ } else if (data?.code) {
+ log(`Validation deferred (${data.code}).`);
+ }
+ })
+ .catch(() => {
+ /* best-effort — badge stays "not yet validated" until re-run */
+ });
+ }
+
return { agentId, registrationUrl, txHash: tx.hash, chainId };
}
diff --git a/src/game/coin-buy.js b/src/game/coin-buy.js
index d6a71db16..667956f58 100644
--- a/src/game/coin-buy.js
+++ b/src/game/coin-buy.js
@@ -48,6 +48,28 @@ function shortAddr(a) {
return a ? `${a.slice(0, 4)}…${a.slice(-4)}` : '';
}
+/**
+ * Map a buy failure to copy the player can act on. A bare "Purchase failed."
+ * tells them nothing; each branch points at the actual next step (add SOL,
+ * widen slippage, retry, reconnect). User cancellation isn't an error to shout
+ * about, so it gets the softest message.
+ * @param {Error & {status?: number}} err
+ */
+function friendlyTradeError(err) {
+ const raw = (err && (err.message || String(err))) || '';
+ const m = raw.toLowerCase();
+ if (/reject|denied|cancell?ed|user declined/.test(m)) return 'Cancelled in wallet.';
+ if (/insufficient (lamports|funds)|custom program error: 0x1\b|debit an account/.test(m))
+ return 'Not enough SOL to cover this buy + network fees. Add SOL and try again.';
+ if (/slippage|0x1771|exceeds desired|too little output|price moved/.test(m))
+ return 'Price moved beyond your slippage limit. Raise max slippage or try again.';
+ if (/blockhash not found|block height exceeded|expired|too old/.test(m))
+ return 'The network was busy and the order expired. Try again.';
+ if (/failed to fetch|networkerror|load failed|timed out|timeout|fetch failed|did not return a transaction|502|503|504/.test(m))
+ return "Couldn't reach the network. Check your connection and try again.";
+ return raw.replace(/\s+/g, ' ').trim().slice(0, 140) || 'Purchase failed. Try again.';
+}
+
/**
* Open the buy modal for a coin. Idempotent — a second call refocuses the
* existing modal instead of stacking.
@@ -67,6 +89,10 @@ class BuyModal {
this.slippageBps = DEFAULT_SLIPPAGE_BPS;
this.busy = false;
this._quoteSeq = 0;
+ // null = unknown (first quote pending), true = graduated to the PumpSwap
+ // AMM, false = still on the bonding curve. Drives the stage pill so a
+ // graduated coin is visually unmistakable from a curve coin.
+ this.graduated = null;
this._build();
this._refreshWallet();
this._quote();
@@ -110,11 +136,16 @@ class BuyModal {
text: 'Or trade on pump.fun ↗',
});
+ this.stagePill = el('span', { class: 'cc-buy-stage', role: 'status', 'aria-live': 'polite', hidden: true });
+
const head = el('div', { class: 'cc-buy-head' }, [
this.coin.image ? el('img', { class: 'cc-buy-img', src: this.coin.image, alt: '' }) : el('div', { class: 'cc-buy-img cc-buy-img-ph', text: '◎' }),
el('div', { class: 'cc-buy-titles' }, [
el('div', { class: 'cc-buy-name', text: this.coin.name || 'Buy coin' }),
- el('div', { class: 'cc-buy-sym', text: this.coin.symbol ? '$' + this.coin.symbol.toUpperCase() : this.coin.mint.slice(0, 8) + '…' }),
+ el('div', { class: 'cc-buy-sub' }, [
+ el('span', { class: 'cc-buy-sym', text: this.coin.symbol ? '$' + this.coin.symbol.toUpperCase() : this.coin.mint.slice(0, 8) + '…' }),
+ this.stagePill,
+ ]),
]),
el('button', { class: 'cc-buy-x', type: 'button', 'aria-label': 'Close', text: '✕', onclick: () => this.close() }),
]);
@@ -192,6 +223,28 @@ class BuyModal {
this.cta.disabled = !(this.amount > 0);
}
+ // Reflect the coin's lifecycle stage (bonding curve vs graduated to the
+ // PumpSwap AMM) as a distinct, unmistakable pill next to the symbol.
+ _renderStage() {
+ const pill = this.stagePill;
+ if (!pill) return;
+ pill.classList.remove('cc-buy-stage-curve', 'cc-buy-stage-grad');
+ if (this.graduated === true) {
+ pill.hidden = false;
+ pill.classList.add('cc-buy-stage-grad');
+ pill.textContent = '🎓 Graduated · PumpSwap AMM';
+ pill.title = 'This coin filled its bonding curve and now trades on the PumpSwap AMM.';
+ } else if (this.graduated === false) {
+ pill.hidden = false;
+ pill.classList.add('cc-buy-stage-curve');
+ pill.textContent = '📈 On bonding curve';
+ pill.title = 'This coin is still on its pump.fun bonding curve and has not graduated yet.';
+ } else {
+ pill.hidden = true;
+ pill.textContent = '';
+ }
+ }
+
// --------------------------------------------------------------- quote
async _quote() {
if (!(this.amount > 0)) { this.quoteLine.textContent = ''; return; }
@@ -203,6 +256,9 @@ class BuyModal {
const { quoteSwap } = await import('../pump/pump-swap-quote.js');
const q = await quoteSwap({ inputMint: WSOL, outputMint: this.coin.mint, amountIn: lamports, slippageBps: this.slippageBps });
if (seq !== this._quoteSeq) return;
+ // A live AMM quote means the coin graduated off the bonding curve.
+ this.graduated = true;
+ this._renderStage();
const tokens = fmtTokens(q.amountOut);
const impact = (q.priceImpactBps / 100);
this.quoteLine.textContent = '';
@@ -212,9 +268,14 @@ class BuyModal {
);
} catch (err) {
if (seq !== this._quoteSeq) return;
- // No AMM pool yet → the coin is still on the bonding curve. The buy still
- // works (the server prices it on-curve); we just can't pre-quote the exact
+ // "Pool unavailable" means there's no AMM pool yet → the coin is still on
+ // the bonding curve. Any other error (RPC down, bad mint) leaves the stage
+ // unknown rather than wrongly claiming a stage. The buy still works
+ // on-curve (the server prices it); we just can't pre-quote the exact
// token amount. Say so honestly instead of pretending.
+ const onCurve = /pool unavailable|account does not exist|could not find/i.test(err?.message || '');
+ this.graduated = onCurve ? false : this.graduated;
+ this._renderStage();
this.quoteLine.classList.add('cc-buy-quote-warn');
this.quoteLine.textContent = `Still on the bonding curve — priced at buy. You'll receive ${this.sym} for ${this.amount} SOL.`;
}
@@ -287,10 +348,7 @@ class BuyModal {
]), 'err');
return;
}
- const msg = err.message || 'Purchase failed.';
- // User rejection in the wallet isn't an error worth shouting about.
- const friendly = /reject|denied|cancell?ed|user/i.test(msg) ? 'Cancelled in wallet.' : msg;
- this._setStatus(friendly, 'err');
+ this._setStatus(friendlyTradeError(err), 'err');
}
}
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index a8198343d..9cb2023b6 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -1050,7 +1050,26 @@ html, body {
.cc-buy-img-ph { display: flex; align-items: center; justify-content: center; color: var(--cc-faint); font-size: 22px; }
.cc-buy-titles { flex: 1; min-width: 0; }
.cc-buy-name { font-weight: 800; font-size: 15px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.cc-buy-sym { color: var(--cc-dim); font-size: 12px; margin-top: 2px; }
+.cc-buy-sub { display: flex; align-items: center; gap: 8px; margin-top: 2px; flex-wrap: wrap; }
+.cc-buy-sym { color: var(--cc-dim); font-size: 12px; }
+
+/* Lifecycle stage pill — a graduated coin must read as unmistakably different
+ from one still on the bonding curve. */
+.cc-buy-stage {
+ display: inline-flex; align-items: center; gap: 4px;
+ padding: 2px 8px; border-radius: 999px;
+ font-size: 10.5px; font-weight: 700; letter-spacing: 0.02em;
+ white-space: nowrap; border: 1px solid transparent;
+ transition: background 0.18s ease, border-color 0.18s ease, color 0.18s ease;
+}
+.cc-buy-stage[hidden] { display: none; }
+.cc-buy-stage-curve {
+ color: #d8c08a; background: rgba(216, 192, 138, 0.10); border-color: rgba(216, 192, 138, 0.32);
+}
+.cc-buy-stage-grad {
+ color: var(--cc-ink); background: var(--cc-accent); border-color: var(--cc-accent);
+ box-shadow: var(--cc-glow);
+}
.cc-buy-x {
flex: none; width: 28px; height: 28px; border-radius: var(--cc-radius-sm);
background: none; border: 1px solid var(--cc-edge); color: var(--cc-dim);
diff --git a/src/pump/launch-token-modal.css b/src/pump/launch-token-modal.css
index 946e76727..98273dc24 100644
--- a/src/pump/launch-token-modal.css
+++ b/src/pump/launch-token-modal.css
@@ -169,6 +169,10 @@
color: rgba(255, 255, 255, 0.95);
}
.ltm-btn:disabled { opacity: 0.4; cursor: not-allowed; }
+.ltm-btn:focus-visible {
+ outline: 2px solid rgba(120, 200, 140, 0.6);
+ outline-offset: 2px;
+}
.ltm-btn-primary {
background: rgba(120, 200, 140, 0.16);
border-color: rgba(120, 200, 140, 0.35);
diff --git a/src/pump/launch-token-modal.js b/src/pump/launch-token-modal.js
index 89b07e657..f430d49f3 100644
--- a/src/pump/launch-token-modal.js
+++ b/src/pump/launch-token-modal.js
@@ -44,6 +44,7 @@ function _solFmt(v) {
function _apiError(status, data) {
const code = data?.error || '';
const desc = data?.error_description || '';
+ const lc = `${code} ${desc}`.toLowerCase();
if (status === 429 || code === 'rate_limited')
return 'Too many launch attempts, try again tomorrow';
if (status === 404 || code === 'not_found') return null; // caller should close
@@ -51,12 +52,44 @@ function _apiError(status, data) {
status === 403 ||
code === 'forbidden' ||
code === 'wallet_mismatch' ||
- desc.toLowerCase().includes('wallet')
+ lc.includes('wallet')
)
return 'Wrong wallet — connect the wallet that owns this agent';
+ if (code === 'insufficient_funds' || lc.includes('insufficient'))
+ return 'Not enough SOL in this wallet to cover the launch. Add SOL and try again.';
+ if (status === 401 || code === 'unauthorized')
+ return 'Sign in to three.ws with this wallet, then launch again.';
+ if (status >= 500)
+ return 'three.ws had a problem preparing the launch. Try again in a moment.';
return desc || `Request failed (${status})`;
}
+/**
+ * Map a Solana broadcast / send-transaction failure to copy a user can act on.
+ * The RPC layer surfaces program errors ("custom program error: 0x1"),
+ * preflight failures, expiry, and transport errors — each needs a different
+ * next step, so a single "Connection error" catch-all is never enough.
+ * @param {unknown} err
+ */
+function _broadcastError(err) {
+ const raw = (err && (err.message || String(err))) || '';
+ const m = raw.toLowerCase();
+ if (/reject|denied|cancell?ed|user declined/.test(m))
+ return 'You cancelled the transaction in your wallet.';
+ if (/insufficient (lamports|funds)|custom program error: 0x1\b|debit an account/.test(m))
+ return 'Not enough SOL to cover the launch + network fees. Add SOL and try again.';
+ if (/slippage|0x1771|exceeds desired|too little|price moved/.test(m))
+ return 'The price moved beyond your limit (slippage). Try again.';
+ if (/blockhash not found|block height exceeded|expired|too old/.test(m))
+ return 'The network was busy and the transaction expired. Try again.';
+ if (/failed to fetch|networkerror|load failed|timed out|timeout|fetch failed|503|502|429/.test(m))
+ return "Couldn't reach the Solana network. Check your connection and try again.";
+ const short = raw.replace(/\s+/g, ' ').trim().slice(0, 120);
+ return short
+ ? `Solana rejected the transaction: ${short}`
+ : 'Solana rejected the transaction. Try again.';
+}
+
export class LaunchTokenModal {
/**
* @param {{
@@ -618,7 +651,7 @@ export class LaunchTokenModal {
} catch {
if (!this._overlay) return;
this._overlay.querySelector('#ltm-quote').innerHTML =
- `<div class="ltm-status-msg ltm-err">Connection error, please try again</div>`;
+ `<div class="ltm-status-msg ltm-err">Couldn't reach three.ws to price the launch. Check your connection and retry.</div>`;
}
}
@@ -738,8 +771,14 @@ export class LaunchTokenModal {
let signed;
try {
signed = await sol.signTransaction(tx);
- } catch {
- this._msg('Transaction signing cancelled.', true);
+ } catch (e) {
+ const m = (e?.message || String(e)).toLowerCase();
+ this._msg(
+ /reject|denied|cancell?ed|user declined/.test(m)
+ ? 'You cancelled the signature in your wallet.'
+ : 'Your wallet could not sign the transaction. Reconnect and try again.',
+ true,
+ );
reset();
return;
}
@@ -758,10 +797,7 @@ export class LaunchTokenModal {
preflightCommitment: 'confirmed',
});
} catch (e) {
- this._msg(
- `Broadcast failed: ${(e.message || String(e)).slice(0, 100)}`,
- true,
- );
+ this._msg(_broadcastError(e), true);
reset();
return;
}
@@ -791,7 +827,9 @@ export class LaunchTokenModal {
prep.cluster === 'mainnet' ? `https://pump.fun/coin/${mint}` : null;
this._renderStep4(mint, pumpUrl, this.agentId);
} catch {
- this._msg('Connection error, please try again', true);
+ // Reaches here only on a transport failure of the prep/confirm fetches
+ // (the sign + broadcast paths have their own mapped catches above).
+ this._msg("Couldn't reach three.ws to finish the launch. Check your connection and try again.", true);
reset();
}
}
diff --git a/src/shared/validation-badge.js b/src/shared/validation-badge.js
new file mode 100644
index 000000000..ee15ea737
--- /dev/null
+++ b/src/shared/validation-badge.js
@@ -0,0 +1,256 @@
+/**
+ * Shared "Validated" badge for ERC-8004 agents — single source of truth for the
+ * glTF/schema validation attestation pill, rendered identically wherever an
+ * on-chain agent is drawn (profile, marketplace, directory).
+ *
+ * Backed by a real on-chain ValidationRegistry record read walletlessly through
+ * GET /api/erc8004/validation. Four designed states:
+ *
+ * pending — fetching / a re-validation is in flight (spinner)
+ * validated — a passing attestation exists (green ✓, links to proof + validator)
+ * failed — an attestation exists but the model has errors (red, shows the reason)
+ * not-validated — registry deployed, no attestation yet (owner sees a "Validate" action)
+ *
+ * When the ValidationRegistry isn't deployed on the agent's chain the badge
+ * renders nothing — there's nothing to attest against, so we don't add noise.
+ */
+
+import { failureReason } from '../erc8004/validation-report.js';
+
+const STYLE_ID = 'tws-validation-badge-styles';
+
+function esc(s) {
+ return String(s == null ? '' : s).replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+/** Fetch the latest on-chain validation state for an agent. Never throws. */
+export async function fetchValidationState(chainId, agentId) {
+ try {
+ const r = await fetch(
+ `/api/erc8004/validation?chainId=${encodeURIComponent(chainId)}&agentId=${encodeURIComponent(agentId)}`,
+ { headers: { accept: 'application/json' } },
+ );
+ if (!r.ok) return null;
+ const data = await r.json();
+ return data?.validation || null;
+ } catch {
+ return null;
+ }
+}
+
+/** Trigger (or re-trigger) an attestation for the agent. Returns the parsed response. */
+export async function requestValidation(chainId, agentId, glbUrl) {
+ const r = await fetch('/api/erc8004/validate', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ chainId, agentId: String(agentId), ...(glbUrl ? { glbUrl } : {}) }),
+ });
+ const data = await r.json().catch(() => ({}));
+ return { ok: r.ok, status: r.status, ...data };
+}
+
+/** Inject the badge stylesheet once. Idempotent and SSR-safe. */
+export function ensureValidationBadgeStyles() {
+ if (typeof document === 'undefined') return;
+ if (document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+.tws-vb{display:inline-flex;align-items:center;gap:6px;padding:4px 11px;border-radius:999px;
+ font:600 12px/1 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;letter-spacing:.01em;
+ text-decoration:none;white-space:nowrap;vertical-align:middle;max-width:100%;
+ border:1px solid transparent;transition:background .15s ease,border-color .15s ease,transform .15s ease;}
+.tws-vb-ico{width:13px;height:13px;flex:none;display:inline-flex;align-items:center;justify-content:center;}
+.tws-vb-label{overflow:hidden;text-overflow:ellipsis;}
+.tws-vb-sub{opacity:.72;font-weight:500;}
+.tws-vb-sub::before{content:"·";margin-right:5px;opacity:.55;}
+a.tws-vb{cursor:pointer;}
+a.tws-vb:hover{transform:translateY(-1px);}
+a.tws-vb:active{transform:translateY(0);}
+a.tws-vb:focus-visible{outline:2px solid currentColor;outline-offset:2px;}
+.tws-vb--ok{color:#34d399;background:rgba(16,185,129,.12);border-color:rgba(16,185,129,.32);}
+a.tws-vb--ok:hover{background:rgba(16,185,129,.2);border-color:rgba(16,185,129,.55);}
+.tws-vb--fail{color:#f87171;background:rgba(248,113,113,.12);border-color:rgba(248,113,113,.32);}
+a.tws-vb--fail:hover{background:rgba(248,113,113,.2);border-color:rgba(248,113,113,.55);}
+.tws-vb--none{color:#94a3b8;background:rgba(148,163,184,.1);border-color:rgba(148,163,184,.26);}
+.tws-vb--pending{color:#94a3b8;background:rgba(148,163,184,.1);border-color:rgba(148,163,184,.26);}
+.tws-vb-act{margin-left:6px;padding:2px 8px;border-radius:999px;border:1px solid currentColor;
+ background:transparent;color:inherit;font:600 11px/1 inherit;cursor:pointer;opacity:.85;
+ transition:opacity .15s ease,background .15s ease;}
+.tws-vb-act:hover{opacity:1;background:rgba(148,163,184,.16);}
+.tws-vb-act:disabled{opacity:.5;cursor:default;}
+.tws-vb-spin{width:12px;height:12px;border:2px solid currentColor;border-right-color:transparent;
+ border-radius:50%;animation:tws-vb-spin .7s linear infinite;}
+@keyframes tws-vb-spin{to{transform:rotate(360deg)}}
+@media (prefers-reduced-motion: reduce){.tws-vb-spin{animation:none;}}
+`;
+ (document.head || document.documentElement).appendChild(style);
+}
+
+const CHECK_SVG =
+ '<svg class="tws-vb-ico" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M3.5 8.5l3 3 6-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
+const CROSS_SVG =
+ '<svg class="tws-vb-ico" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';
+const DASH_SVG =
+ '<svg class="tws-vb-ico" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M4 8h8" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';
+
+function badgeNode({ variant, label, sub, title, href, icon }) {
+ ensureValidationBadgeStyles();
+ const cls = `tws-vb tws-vb--${variant}`;
+ const inner = `${icon || ''}<span class="tws-vb-label">${esc(label)}</span>${
+ sub ? `<span class="tws-vb-sub">${esc(sub)}</span>` : ''
+ }`;
+ const tpl = document.createElement('template');
+ if (href) {
+ tpl.innerHTML = `<a class="${cls}" href="${esc(href)}" target="_blank" rel="noopener noreferrer" title="${esc(title || label)}">${inner}</a>`;
+ } else {
+ tpl.innerHTML = `<span class="${cls}" title="${esc(title || label)}" role="img" aria-label="${esc(label)}">${inner}</span>`;
+ }
+ const node = tpl.content.firstElementChild;
+ if (node.tagName === 'A') node.addEventListener('click', (e) => e.stopPropagation());
+ return node;
+}
+
+/**
+ * Render the badge for a resolved validation state. Returns null when there's
+ * nothing to show (registry not deployed on this chain).
+ *
+ * @param {object} state Response from GET /api/erc8004/validation.
+ * @param {object} [opts]
+ * @param {boolean} [opts.isOwner=false] Owner sees a Validate / Re-validate action.
+ * @param {() => void} [opts.onRevalidate] Invoked when the owner clicks the action.
+ * @param {string} [opts.failureText] Pre-resolved failure reason for the failed state.
+ */
+export function validationBadgeEl(state, opts = {}) {
+ if (!state || state.available === false) return null;
+ const { isOwner = false, onRevalidate, failureText } = opts;
+
+ let node;
+ if (!state.exists) {
+ node = badgeNode({
+ variant: 'none',
+ label: 'Not validated',
+ title: 'No on-chain glTF validation attestation yet',
+ icon: DASH_SVG,
+ });
+ } else if (state.passed) {
+ node = badgeNode({
+ variant: 'ok',
+ label: 'Validated',
+ sub: 'glTF',
+ title: `glTF validation passed${state.validatedAt ? ` · ${new Date(state.validatedAt).toLocaleDateString()}` : ''}${
+ state.validator ? ` · validator ${state.validator.slice(0, 6)}…` : ''
+ } · view proof →`,
+ href: state.proofUrlResolved || state.proofURI || undefined,
+ icon: CHECK_SVG,
+ });
+ } else {
+ node = badgeNode({
+ variant: 'fail',
+ label: 'Validation failed',
+ sub: failureText || undefined,
+ title: `glTF validation failed${failureText ? `: ${failureText}` : ''} · view report →`,
+ href: state.proofUrlResolved || state.proofURI || undefined,
+ icon: CROSS_SVG,
+ });
+ }
+
+ // Owner action — validate (first time) or re-validate (refresh after a GLB
+ // update). The agent is registered regardless; this only (re)records proof.
+ if (isOwner && onRevalidate) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'tws-vb-act';
+ btn.textContent = state.exists ? 'Re-validate' : 'Validate';
+ btn.addEventListener('click', (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onRevalidate();
+ });
+ const wrap = document.createElement('span');
+ wrap.style.display = 'inline-flex';
+ wrap.style.alignItems = 'center';
+ wrap.append(node, btn);
+ return wrap;
+ }
+
+ return node;
+}
+
+/** A standalone pending badge (used while fetching / attesting). */
+export function pendingBadgeEl(label = 'Validating…') {
+ ensureValidationBadgeStyles();
+ const tpl = document.createElement('template');
+ tpl.innerHTML = `<span class="tws-vb tws-vb--pending" role="status" aria-live="polite"><span class="tws-vb-spin" aria-hidden="true"></span><span class="tws-vb-label">${esc(label)}</span></span>`;
+ return tpl.content.firstElementChild;
+}
+
+/**
+ * Mount the validation badge into a container: shows a pending pill, fetches the
+ * on-chain state, renders the right variant, and (for owners) wires the
+ * Validate / Re-validate action with live pending feedback.
+ *
+ * @param {object} p
+ * @param {HTMLElement} p.container Element to render into (its contents are replaced).
+ * @param {number} p.chainId
+ * @param {string|number} p.agentId
+ * @param {boolean} [p.isOwner=false]
+ * @param {string} [p.glbUrl] Passed through to re-validation (optional — server can resolve).
+ * @returns {Promise<void>}
+ */
+export async function mountValidationBadge({ container, chainId, agentId, isOwner = false, glbUrl }) {
+ if (!container || !chainId || agentId == null) return;
+ ensureValidationBadgeStyles();
+
+ const render = (node) => {
+ container.replaceChildren();
+ if (node) container.appendChild(node);
+ };
+
+ render(pendingBadgeEl());
+
+ const state = await fetchValidationState(chainId, agentId);
+ if (!state) {
+ render(null);
+ return;
+ }
+
+ // For a failing attestation, fetch the pinned report to surface what failed.
+ let failureText = '';
+ if (state.exists && !state.passed && (state.proofUrlResolved || state.proofURI)) {
+ try {
+ const r = await fetch(state.proofUrlResolved || state.proofURI);
+ if (r.ok) failureText = failureReason(await r.json());
+ } catch {
+ /* report unreachable — badge still shows the failed state */
+ }
+ }
+
+ const onRevalidate = async () => {
+ render(pendingBadgeEl(state.exists ? 'Re-validating…' : 'Validating…'));
+ try {
+ const result = await requestValidation(chainId, agentId, glbUrl);
+ if (!result.ok) {
+ // Surface the ops state inline rather than silently reverting.
+ const failNode = badgeNode({
+ variant: 'none',
+ label: 'Validation deferred',
+ sub: result.code || `${result.status}`,
+ title: result.error || result.code || 'validation could not be recorded',
+ icon: DASH_SVG,
+ });
+ render(failNode);
+ return;
+ }
+ } catch {
+ /* fall through to a fresh re-fetch */
+ }
+ await mountValidationBadge({ container, chainId, agentId, isOwner, glbUrl });
+ };
+
+ render(validationBadgeEl(state, { isOwner, onRevalidate, failureText }));
+}
diff --git a/tests/api/pump-fun-strategy-validate.test.js b/tests/api/pump-fun-strategy-validate.test.js
new file mode 100644
index 000000000..09cb83d36
--- /dev/null
+++ b/tests/api/pump-fun-strategy-validate.test.js
@@ -0,0 +1,245 @@
+// Semantic strategy validation (Task 06). Covers the pure static validator
+// (validateStrategySpec), the live validateStrategy handler (mint existence +
+// quote-asset reconciliation), and the run/backtest pre-flight gate. Each
+// rejection class has a case, and the shipped presets are asserted clean so the
+// validator never produces a false positive on a working strategy.
+
+import { describe, it, expect } from 'vitest';
+import {
+ validateStrategySpec,
+ strategyErrors,
+} from '../../examples/skills/pump-fun-strategy/dsl.js';
+import {
+ validateStrategy,
+ runStrategy,
+ backtestStrategy,
+} from '../../examples/skills/pump-fun-strategy/handlers.js';
+
+// Clearly-synthetic, base58-shaped placeholder mint (never a real coin).
+const SYNTH_MINT = 'THREEsynthetic1111111111111111111111111111';
+
+const errorsOf = (spec) => validateStrategySpec(spec).issues.filter((i) => i.level === 'error');
+const codesOf = (spec, level) =>
+ validateStrategySpec(spec).issues.filter((i) => !level || i.level === level).map((i) => i.code);
+
+const validBase = (over = {}) => ({
+ scan: { kind: 'newTokens', limit: 10 },
+ filters: ['holders.total > 50'],
+ entry: { side: 'buy', amountSol: 0.05 },
+ exit: [{ if: 'position.pnlPct > 75', do: { side: 'sell', percent: 100 } }],
+ caps: { sessionSpendCapSol: 0.5, maxOpenPositions: 5 },
+ ...over,
+});
+
+const PRESETS = {
+ momentum: {
+ scan: { kind: 'newTokens', limit: 10 },
+ filters: ['holders.total > 50', 'holders.topHolderPct < 25', 'creator.rugCount == 0'],
+ entry: { side: 'buy', amountSol: 0.05 },
+ exit: [
+ { if: 'position.pnlPct > 75', do: { side: 'sell', percent: 100 } },
+ { if: 'position.pnlPct < -30', do: { side: 'sell', percent: 100 } },
+ { if: 'holders.topHolderPct > 40', do: { side: 'sell', percent: 100 } },
+ ],
+ caps: { sessionSpendCapSol: 0.5, perTradeSol: 0.05, maxOpenPositions: 5 },
+ },
+ snipe: {
+ scan: { kind: 'newTokens', limit: 20 },
+ filters: ['holders.total > 30', 'creator.rugCount == 0'],
+ entry: { side: 'buy', amountSol: 0.025 },
+ exit: [
+ { if: 'position.pnlPct > 100', do: { side: 'sell', percent: 100 } },
+ { if: 'position.ageSec > 600', do: { side: 'sell', percent: 100 } },
+ ],
+ caps: { sessionSpendCapSol: 0.25, perTradeSol: 0.025, maxOpenPositions: 8 },
+ },
+};
+
+describe('validateStrategySpec — no false positives on working strategies', () => {
+ it('accepts the shipped presets with zero errors', () => {
+ expect(errorsOf(PRESETS.momentum)).toEqual([]);
+ expect(errorsOf(PRESETS.snipe)).toEqual([]);
+ expect(validateStrategySpec(validBase()).issues.filter((i) => i.level === 'error')).toEqual([]);
+ });
+ it('reports filter/exit counts and a SOL denomination', () => {
+ const { meta } = validateStrategySpec(PRESETS.momentum);
+ expect(meta.filterCount).toBe(3);
+ expect(meta.exitCount).toBe(3);
+ expect(meta.denominatedQuote).toBe('SOL');
+ expect(meta.effectivePerTradeSol).toBe(0.05);
+ });
+});
+
+describe('validateStrategySpec — structural rejections', () => {
+ it('rejects a non-object strategy', () => {
+ expect(codesOf(null)).toContain('not_an_object');
+ expect(codesOf('nope')).toContain('not_an_object');
+ });
+ it('rejects a bad scan kind', () => {
+ expect(codesOf(validBase({ scan: { kind: 'wat' } }))).toContain('bad_scan_kind');
+ });
+ it('rejects an empty mintList', () => {
+ expect(codesOf(validBase({ scan: { kind: 'mintList', mints: [] } }))).toContain('empty_mint_list');
+ });
+ it('rejects a non-buy entry side and non-positive size', () => {
+ expect(codesOf(validBase({ entry: { side: 'sell', amountSol: 0.05 } }))).toContain('bad_entry_side');
+ expect(codesOf(validBase({ entry: { side: 'buy', amountSol: 0 } }))).toContain('bad_amount');
+ });
+ it('rejects malformed exit actions', () => {
+ expect(codesOf(validBase({ exit: [{ if: 'position.pnlPct > 10', do: { side: 'sell', percent: 150 } }] })))
+ .toContain('bad_exit_percent');
+ expect(codesOf(validBase({ exit: [{ if: 'position.pnlPct > 10', do: { side: 'sell', percent: 50, amountTokens: 1 } }] })))
+ .toContain('bad_exit_size');
+ expect(codesOf(validBase({ exit: [{ if: 'position.pnlPct > 10', do: { side: 'buy', percent: 50 } }] })))
+ .toContain('bad_exit_side');
+ });
+ it('rejects a zero maxOpenPositions', () => {
+ expect(codesOf(validBase({ caps: { maxOpenPositions: 0 } }))).toContain('bad_max_positions');
+ });
+});
+
+describe('validateStrategySpec — predicate path rejections', () => {
+ it('rejects an unknown metric path (typo)', () => {
+ expect(codesOf(validBase({ filters: ['holders.totl > 50'] }))).toContain('unknown_path');
+ });
+ it('rejects position.* used in a filter (never populated at entry)', () => {
+ const codes = codesOf(validBase({ filters: ['position.pnlPct > 10'] }));
+ expect(codes).toContain('path_unavailable_in_context');
+ });
+ it('rejects an unparseable predicate', () => {
+ expect(codesOf(validBase({ filters: ['garbage'] }))).toContain('unparseable_predicate');
+ });
+});
+
+describe('validateStrategySpec — impossible thresholds', () => {
+ it('rejects a percentage above 100', () => {
+ expect(codesOf(validBase({ filters: ['holders.topHolderPct > 100'] }))).toContain('impossible_threshold');
+ });
+ it('rejects a percentage below 0', () => {
+ expect(codesOf(validBase({ filters: ['holders.topHolderPct < 0'] }))).toContain('impossible_threshold');
+ });
+ it('rejects pnl below -100%', () => {
+ expect(codesOf(validBase({ exit: [{ if: 'position.pnlPct < -100', do: { side: 'sell', percent: 100 } }] })))
+ .toContain('impossible_threshold');
+ });
+ it('rejects a fractional value for an integer metric', () => {
+ expect(codesOf(validBase({ filters: ['holders.total == 50.5'] }))).toContain('impossible_threshold');
+ });
+ it('rejects a negative count equality', () => {
+ expect(codesOf(validBase({ filters: ['creator.rugCount == -1'] }))).toContain('impossible_threshold');
+ });
+});
+
+describe('validateStrategySpec — contradiction & cap sanity', () => {
+ it('rejects contradictory filters on the same path', () => {
+ const codes = codesOf(validBase({ filters: ['holders.total > 100', 'holders.total < 50'] }));
+ expect(codes).toContain('contradictory_filters');
+ });
+ it('rejects a per-trade size larger than the session cap', () => {
+ const codes = codesOf(validBase({ entry: { side: 'buy', amountSol: 0.5 }, caps: { sessionSpendCapSol: 0.1 } }));
+ expect(codes).toContain('cap_below_per_trade');
+ });
+});
+
+describe('validateStrategySpec — non-fatal warnings', () => {
+ it('warns (does not reject) on an unreachable shadowed exit rule', () => {
+ const report = validateStrategySpec(validBase({
+ exit: [
+ { if: 'position.pnlPct > 20', do: { side: 'sell', percent: 50 } },
+ { if: 'position.pnlPct > 40', do: { side: 'sell', percent: 100 } },
+ ],
+ }));
+ expect(report.issues.some((i) => i.code === 'shadowed_exit' && i.level === 'warning')).toBe(true);
+ expect(report.issues.filter((i) => i.level === 'error')).toEqual([]);
+ });
+ it('warns on an always-true (redundant) filter', () => {
+ expect(codesOf(validBase({ filters: ['holders.total >= 0'] }), 'warning')).toContain('redundant_filter');
+ });
+ it('warns that caps.perTradeSol is ignored when it differs from entry.amountSol', () => {
+ expect(codesOf(validBase({ entry: { side: 'buy', amountSol: 0.05 }, caps: { perTradeSol: 0.1, sessionSpendCapSol: 1 } }), 'warning'))
+ .toContain('per_trade_ignored');
+ });
+ it('warns on a non-base58 mint but does not reject', () => {
+ const report = validateStrategySpec(validBase({ scan: { kind: 'mintList', mints: ['M1'] } }));
+ expect(report.issues.some((i) => i.code === 'malformed_mint' && i.level === 'warning')).toBe(true);
+ expect(report.issues.filter((i) => i.level === 'error')).toEqual([]);
+ });
+});
+
+describe('validateStrategy handler — live mint & quote checks', () => {
+ const mintListSpec = validBase({ scan: { kind: 'mintList', mints: [SYNTH_MINT] } });
+
+ it('rejects a SOL strategy targeting a USDC-paired agent coin', async () => {
+ const r = await validateStrategy({
+ strategy: mintListSpec,
+ mintInfo: { [SYNTH_MINT]: { isAgentCoin: true, quoteIsUsdc: true, quoteSymbol: 'USDC' } },
+ });
+ expect(r.ok).toBe(false);
+ expect(r.data.issues.some((i) => i.code === 'quote_asset_mismatch')).toBe(true);
+ });
+
+ it('accepts a SOL strategy targeting a SOL-paired agent coin', async () => {
+ const r = await validateStrategy({
+ strategy: mintListSpec,
+ mintInfo: { [SYNTH_MINT]: { isAgentCoin: true, quoteIsUsdc: false, quoteSymbol: 'SOL' } },
+ });
+ expect(r.ok).toBe(true);
+ expect(r.data.issues.some((i) => i.level === 'error')).toBe(false);
+ });
+
+ it('rejects a mint that definitively does not exist on-chain', async () => {
+ const ctx = { skills: { invoke: async () => ({ ok: false, error: 'mint account not found' }) } };
+ const r = await validateStrategy({ strategy: mintListSpec, mintInfo: null }, ctx);
+ expect(r.ok).toBe(false);
+ expect(r.data.issues.some((i) => i.code === 'mint_not_found')).toBe(true);
+ });
+
+ it('downgrades a transient probe failure to a warning (no false rejection)', async () => {
+ const ctx = { skills: { invoke: async () => ({ ok: false, error: 'RPC 429 rate limited' }) } };
+ const r = await validateStrategy({ strategy: mintListSpec, mintInfo: null }, ctx);
+ expect(r.ok).toBe(true);
+ expect(r.data.issues.some((i) => i.code === 'mint_unverified' && i.level === 'warning')).toBe(true);
+ });
+
+ it('flags a real-but-non-agent coin as info, not an error', async () => {
+ const ctx = { skills: { invoke: async () => ({ ok: true, data: { mint: SYNTH_MINT, decimals: 6 } }) } };
+ const r = await validateStrategy({ strategy: mintListSpec, mintInfo: null }, ctx);
+ expect(r.ok).toBe(true);
+ expect(r.data.issues.some((i) => i.code === 'not_agent_coin' && i.level === 'info')).toBe(true);
+ });
+
+ it('stays backward-compatible: valid spec returns parsed metadata', async () => {
+ const r = await validateStrategy({
+ strategy: {
+ scan: { kind: 'newTokens' },
+ filters: ['holders.total > 10'],
+ entry: { side: 'buy', amountSol: 0.05 },
+ exit: [{ if: 'position.pnlPct > 100', do: { side: 'sell', percent: 100 } }],
+ },
+ });
+ expect(r.ok).toBe(true);
+ expect(r.data.filterCount).toBe(1);
+ expect(r.data.exitCount).toBe(1);
+ });
+});
+
+describe('run/backtest pre-flight gate agrees with validate', () => {
+ const broken = validBase({ filters: ['position.pnlPct > 10'] }); // position.* in filter
+
+ it('strategyErrors flags the broken spec', () => {
+ expect(strategyErrors(broken).length).toBeGreaterThan(0);
+ });
+
+ it('backtestStrategy refuses a semantically-broken spec before replay', async () => {
+ const ctx = { skills: { invoke: async () => ({ ok: true, data: {} }) } };
+ const r = await backtestStrategy({ strategy: broken, mints: [SYNTH_MINT] }, ctx);
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/position/i);
+ });
+
+ it('runStrategy throws on a semantically-broken spec', async () => {
+ await expect(
+ runStrategy({ strategy: broken, durationSec: 5, simulate: true }, { skills: { invoke: async () => ({ ok: true, data: {} }) } }),
+ ).rejects.toThrow(/invalid strategy/i);
+ });
+});
diff --git a/tests/e2e/launch-token-flow.spec.js b/tests/e2e/launch-token-flow.spec.js
new file mode 100644
index 000000000..3e12c0c92
--- /dev/null
+++ b/tests/e2e/launch-token-flow.spec.js
@@ -0,0 +1,311 @@
+/**
+ * Launch Token Modal — Playwright e2e spec.
+ *
+ * Covers the platform's most important conversion path end to end: the four
+ * steps of src/pump/launch-token-modal.js — details form → quote + bonding
+ * curve → connect wallet → sign / broadcast / confirm → success share card.
+ *
+ * Fidelity rules (mirrors tests/e2e/galaxy.spec.js):
+ * • The REAL modal module is imported and driven — nothing about the flow is
+ * re-implemented in the test.
+ * • The launch-quote / launch-prep / launch-confirm endpoints and the Solana
+ * RPC proxy are fulfilled at the Playwright route layer with realistic
+ * payloads (Vite dev proxies /api/* to production, so we must intercept to
+ * stay deterministic and never touch a real chain). The client makes the
+ * real fetches; we assert prep + confirm actually fire with the right body.
+ * • The ONLY stubbed product-external surface is window.solana — an injected
+ * browser extension. Its signTransaction returns a serialized tx exactly
+ * like a real wallet would, so the broadcast path runs for real against the
+ * fulfilled RPC.
+ *
+ * The launch-prep transaction is a genuine, parseable @solana/web3.js legacy
+ * Transaction built in Node — Transaction.from() in the modal deserializes it
+ * for real.
+ */
+
+import { test, expect } from '@playwright/test';
+import { fileURLToPath } from 'url';
+import { dirname, resolve } from 'path';
+import { Transaction, SystemProgram, Keypair } from '@solana/web3.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(__dirname, '..', '..');
+const LTM_CSS = resolve(repoRoot, 'src/pump/launch-token-modal.css');
+
+// Deterministic synthetic identities — never a real wallet or a real mint.
+const WALLET_ADDR = Keypair.generate().publicKey.toBase58();
+const MINT_ADDR = '3wsLaunchE2eSyntheticMint1111111111111111111';
+const TX_SIGNATURE = '5e2eLaunchSyntheticSig1111111111111111111111111111111111111111111111111111111111111111';
+
+// A real legacy transaction the modal can deserialize with Transaction.from().
+function buildPrepTxBase64() {
+ const payer = Keypair.generate();
+ const tx = new Transaction();
+ tx.feePayer = payer.publicKey;
+ tx.recentBlockhash = Keypair.generate().publicKey.toBase58();
+ tx.add(
+ SystemProgram.transfer({
+ fromPubkey: payer.publicKey,
+ toPubkey: payer.publicKey,
+ lamports: 1,
+ }),
+ );
+ return tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64');
+}
+
+const QUOTE_PAYLOAD = {
+ fixed_total_sol: 0.0231,
+ initial_buy: { sol: 0.5, protocol_fee_sol: 0.005, tokens_out: 12_500_000 },
+ total_sol: 0.5281,
+ cluster: 'mainnet',
+};
+
+// Install all route fixtures + the wallet stub. Returns a `calls` object the
+// tests assert against so we can prove the real prep/confirm fetches fired.
+async function installHarness(page, { quote = QUOTE_PAYLOAD } = {}) {
+ const calls = { prep: null, confirm: null, broadcast: 0 };
+ const txBase64 = buildPrepTxBase64();
+
+ // Wallet extension stub — the one acceptable mock (external browser code).
+ await page.addInitScript((addr) => {
+ const pk = { toString: () => addr, toBase58: () => addr };
+ window.solana = {
+ isPhantom: true,
+ isConnected: false,
+ publicKey: null,
+ async connect() {
+ this.isConnected = true;
+ this.publicKey = pk;
+ return { publicKey: pk };
+ },
+ async disconnect() {
+ this.isConnected = false;
+ this.publicKey = null;
+ },
+ // Real wallets return a signed tx; the modal calls signed.serialize().
+ async signTransaction(tx) {
+ return { serialize: () => tx.serialize({ requireAllSignatures: false, verifySignatures: false }) };
+ },
+ on() {},
+ removeListener() {},
+ };
+ }, WALLET_ADDR);
+
+ // SOL price — keep it off the network so the modal's price hints are stable.
+ await page.route('**/api.coingecko.com/**', (route) =>
+ route.fulfill({ json: { solana: { usd: 150 } } }),
+ );
+
+ await page.route('**/api/agents/tokens/launch-quote**', (route) =>
+ route.fulfill({ json: quote }),
+ );
+
+ await page.route('**/api/agents/tokens/launch-prep', async (route) => {
+ calls.prep = JSON.parse(route.request().postData() || '{}');
+ await route.fulfill({
+ json: { prep_id: 'prep_e2e_1', mint: MINT_ADDR, cluster: 'mainnet', tx_base64: txBase64 },
+ });
+ });
+
+ await page.route('**/api/agents/tokens/launch-confirm', async (route) => {
+ calls.confirm = JSON.parse(route.request().postData() || '{}');
+ await route.fulfill({ json: { agent: { token: { mint: MINT_ADDR } } } });
+ });
+
+ // Solana RPC proxy — answer JSON-RPC like a node. sendRawTransaction →
+ // "sendTransaction" returns a signature; getLatestBlockhash for safety.
+ await page.route('**/api/solana-rpc**', async (route) => {
+ const body = JSON.parse(route.request().postData() || '{}');
+ const reply = (result) =>
+ route.fulfill({ json: { jsonrpc: '2.0', id: body.id, result } });
+ if (body.method === 'sendTransaction') {
+ calls.broadcast += 1;
+ return reply(TX_SIGNATURE);
+ }
+ if (body.method === 'getLatestBlockhash') {
+ return reply({
+ context: { slot: 1 },
+ value: { blockhash: Keypair.generate().publicKey.toBase58(), lastValidBlockHeight: 1000 },
+ });
+ }
+ return reply(null);
+ });
+
+ // Minimal same-origin host page so the dev server still resolves /src/* module
+ // imports and the relative /api/* fetches, without booting the heavy homepage.
+ await page.route('**/__e2e/launch-harness', (route) =>
+ route.fulfill({
+ contentType: 'text/html',
+ body: '<!doctype html><html><head><meta charset="utf-8"><title>launch harness</title></head><body></body></html>',
+ }),
+ );
+
+ return calls;
+}
+
+// Open the real modal on the harness page and return once step 1 is painted.
+async function openModal(page) {
+ await page.goto('http://localhost:3000/__e2e/launch-harness');
+ await page.addStyleTag({ path: LTM_CSS });
+ await page.evaluate(async () => {
+ const mod = await import('/src/pump/launch-token-modal.js');
+ window.__ltm = mod.openLaunchTokenModal({
+ agentId: 'agent-e2e-1',
+ agentName: 'E2E Launch Agent',
+ imageUrl: '',
+ });
+ });
+ await expect(page.locator('#ltm-name')).toBeVisible({ timeout: 30_000 });
+}
+
+// Step 1 → fill valid details → Preview.
+async function fillStep1(page, { name = 'E2E Launch Agent', symbol = 'E2EAG', buy = '0.5' } = {}) {
+ await page.fill('#ltm-name', name);
+ await page.fill('#ltm-sym', symbol);
+ await page.fill('#ltm-buy', buy);
+ await page.click('#ltm-s1-next');
+}
+
+// Step 2 → wait for the quote breakdown → Continue.
+async function passStep2(page) {
+ await expect(page.locator('#ltm-chart svg')).toBeVisible({ timeout: 30_000 });
+ await expect(page.locator('.ltm-quote-row').first()).toBeVisible({ timeout: 30_000 });
+ const next = page.locator('#ltm-s2-next');
+ await expect(next).toBeEnabled();
+ await next.click();
+}
+
+// Step 3 → connect the stubbed wallet → enable Sign & Launch.
+async function connectWallet(page) {
+ await expect(page.locator('#ltm-connect')).toBeVisible();
+ await page.click('#ltm-connect');
+ await expect(page.locator('#ltm-ws')).toHaveText('Connected');
+ await expect(page.locator('#ltm-launch')).toBeEnabled();
+}
+
+test.describe('Launch Token Modal — full flow', () => {
+ test.beforeEach(async ({ page }) => {
+ page.on('pageerror', (err) => {
+ // Vite HMR socket noise on the forwarded Codespace port is not a product bug.
+ if (/websocket|hmr|wss:|failed to connect/i.test(err.message)) return;
+ throw new Error(`Page error: ${err.message}`);
+ });
+ });
+
+ test('step 1 rejects a malformed symbol and stays on the form', async ({ page }) => {
+ test.setTimeout(120_000);
+ await installHarness(page);
+ await openModal(page);
+
+ // A non-alphanumeric symbol must be rejected inline; the flow does not advance.
+ await page.fill('#ltm-name', 'E2E Launch Agent');
+ await page.fill('#ltm-sym', 'A!');
+ await page.click('#ltm-s1-next');
+
+ await expect(page.locator('#ltm-sym-err')).toContainText('alphanumeric');
+ await expect(page.locator('#ltm-sym')).toHaveClass(/ltm-err/);
+ // Still on step 1 — the quote chart never mounted.
+ await expect(page.locator('#ltm-chart')).toHaveCount(0);
+ });
+
+ test('step 2 renders the cost breakdown and bonding curve chart', async ({ page }) => {
+ test.setTimeout(120_000);
+ await installHarness(page);
+ await openModal(page);
+ await fillStep1(page);
+
+ // Bonding curve SVG mounts.
+ await expect(page.locator('#ltm-chart svg')).toBeVisible({ timeout: 30_000 });
+ // Cost breakdown rows render with a final total.
+ const rows = page.locator('.ltm-quote-row');
+ await expect(rows.first()).toBeVisible();
+ await expect(page.locator('.ltm-q-val.ltm-total')).toBeVisible();
+ await expect(page.locator('#ltm-quote')).toContainText('Total SOL needed');
+ // Dev-buy line from the quote payload is shown.
+ await expect(page.locator('#ltm-quote')).toContainText('Dev buy');
+ });
+
+ test('step 3 connects the wallet and arms the launch button', async ({ page }) => {
+ test.setTimeout(120_000);
+ await installHarness(page);
+ await openModal(page);
+ await fillStep1(page);
+ await passStep2(page);
+ await connectWallet(page);
+
+ // Connected address is shown truncated.
+ await expect(page.locator('#ltm-wa')).toContainText('…');
+ });
+
+ test('step 4 signs, broadcasts, confirms and shows the share card', async ({ page }) => {
+ test.setTimeout(120_000);
+ const calls = await installHarness(page);
+ await openModal(page);
+ await fillStep1(page);
+ await passStep2(page);
+ await connectWallet(page);
+
+ await page.click('#ltm-launch');
+
+ // Success step renders.
+ await expect(page.locator('.ltm-success-title')).toBeVisible({ timeout: 30_000 });
+ // Mint chip shows the real returned mint.
+ await expect(page.locator('#ltm-mint')).toHaveText(MINT_ADDR);
+ // Share affordances are wired.
+ await expect(page.locator('#ltm-copy-mint')).toBeVisible();
+ await expect(page.locator('#ltm-share-x')).toBeVisible();
+ // pump.fun link uses the mint (mainnet success card).
+ await expect(page.locator('#ltm-pumpfun')).toHaveAttribute(
+ 'href',
+ `https://pump.fun/coin/${MINT_ADDR}`,
+ );
+ // Share-card canvas drawn.
+ await expect(page.locator('#ltm-share')).toBeVisible();
+
+ // The REAL prep + confirm fetches fired with the expected body, and we
+ // broadcast exactly once.
+ expect(calls.prep).toMatchObject({
+ agent_id: 'agent-e2e-1',
+ provider: 'pumpfun',
+ wallet_address: WALLET_ADDR,
+ symbol: 'E2EAG',
+ });
+ expect(calls.broadcast).toBe(1);
+ expect(calls.confirm).toMatchObject({
+ prep_id: 'prep_e2e_1',
+ tx_signature: TX_SIGNATURE,
+ wallet_address: WALLET_ADDR,
+ });
+ });
+
+ test('a broadcast failure shows specific, actionable copy', async ({ page }) => {
+ test.setTimeout(120_000);
+ await installHarness(page);
+ // Make the RPC reject the send with an insufficient-funds program error.
+ await page.route('**/api/solana-rpc**', (route) => {
+ const body = JSON.parse(route.request().postData() || '{}');
+ if (body.method === 'sendTransaction') {
+ return route.fulfill({
+ json: {
+ jsonrpc: '2.0',
+ id: body.id,
+ error: { code: -32002, message: 'Transaction simulation failed: insufficient lamports 0, need 5281' },
+ },
+ });
+ }
+ return route.fulfill({ json: { jsonrpc: '2.0', id: body.id, result: null } });
+ });
+ await openModal(page);
+ await fillStep1(page);
+ await passStep2(page);
+ await connectWallet(page);
+ await page.click('#ltm-launch');
+
+ // No generic "Connection error" — the user is told to add SOL.
+ await expect(page.locator('#ltm-msg.ltm-err')).toContainText('Not enough SOL', {
+ timeout: 30_000,
+ });
+ // The flow recovered (button re-enabled), not stuck.
+ await expect(page.locator('#ltm-launch')).toBeEnabled();
+ });
+});
diff --git a/tests/pump-trade-args.test.js b/tests/pump-trade-args.test.js
index e8bdd263c..a9aa28295 100644
--- a/tests/pump-trade-args.test.js
+++ b/tests/pump-trade-args.test.js
@@ -15,6 +15,9 @@ import { PumpSdk } from '@pump-fun/pump-sdk';
import {
slippagePercentFromBps,
resolveTokenProgramForMintOwner,
+ resolveCustodialQuote,
+ usdcMintForNetwork,
+ WSOL_MINT,
SPL_TOKEN_PROGRAM_ID,
TOKEN_2022_PROGRAM_ID as T22_FROM_LIB,
} from '../api/_lib/pump-trade-args.js';
@@ -97,6 +100,60 @@ describe('resolveTokenProgramForMintOwner', () => {
});
});
+// ── resolveCustodialQuote ──────────────────────────────────────────────────
+//
+// The custodial (server-signed) buy/sell/swap paths read the coin's quote asset
+// from its on-chain bonding curve and feed it to the v2 builder. This resolver
+// is the pure core of that decision: SOL-paired vs USDC-paired vs other SPL.
+
+describe('resolveCustodialQuote', () => {
+ const USDC = usdcMintForNetwork('mainnet');
+ const USDC_DEVNET = usdcMintForNetwork('devnet');
+
+ it('treats null/undefined (no quote on the curve) as SOL-paired', () => {
+ for (const v of [null, undefined, '']) {
+ const q = resolveCustodialQuote(v);
+ expect(q).toEqual({ isSol: true, isUsdc: false, quoteSymbol: 'SOL', quoteMint: WSOL_MINT });
+ }
+ });
+
+ it('treats the system-default pubkey (SOL curve sentinel) as SOL-paired', () => {
+ const q = resolveCustodialQuote(PublicKey.default);
+ expect(q.isSol).toBe(true);
+ expect(q.isUsdc).toBe(false);
+ expect(q.quoteMint).toBe(WSOL_MINT);
+ });
+
+ it('treats the explicit wrapped-SOL mint as SOL-paired (string and PublicKey)', () => {
+ expect(resolveCustodialQuote(WSOL_MINT).isSol).toBe(true);
+ expect(resolveCustodialQuote(NATIVE_MINT).isSol).toBe(true);
+ expect(resolveCustodialQuote(new PublicKey(WSOL_MINT)).quoteSymbol).toBe('SOL');
+ });
+
+ it('classifies the network USDC mint as USDC-paired', () => {
+ const q = resolveCustodialQuote(USDC, 'mainnet');
+ expect(q).toEqual({ isSol: false, isUsdc: true, quoteSymbol: 'USDC', quoteMint: USDC });
+ expect(resolveCustodialQuote(new PublicKey(USDC)).isUsdc).toBe(true);
+ });
+
+ it('is network-aware: devnet USDC is USDC on devnet but OTHER on mainnet', () => {
+ expect(resolveCustodialQuote(USDC_DEVNET, 'devnet').quoteSymbol).toBe('USDC');
+ const onMainnet = resolveCustodialQuote(USDC_DEVNET, 'mainnet');
+ expect(onMainnet.isUsdc).toBe(false);
+ expect(onMainnet.quoteSymbol).toBe('OTHER');
+ expect(onMainnet.quoteMint).toBe(USDC_DEVNET);
+ });
+
+ it('classifies an arbitrary SPL quote mint as OTHER (non-SOL, non-USDC)', () => {
+ const other = Keypair.generate().publicKey;
+ const q = resolveCustodialQuote(other, 'mainnet');
+ expect(q.isSol).toBe(false);
+ expect(q.isUsdc).toBe(false);
+ expect(q.quoteSymbol).toBe('OTHER');
+ expect(q.quoteMint).toBe(other.toBase58());
+ });
+});
+
// ── v2 builder conformance vs the vendored IDL ─────────────────────────────
//
// Our handlers call buyV2Instructions / sellV2Instructions, which bottom out
diff --git a/vercel.json b/vercel.json
index 863269468..21bc00c51 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2397,6 +2397,14 @@
"src": "/api/erc8004/pin",
"dest": "/api/erc8004/[action]?action=pin"
},
+ {
+ "src": "/api/erc8004/validate",
+ "dest": "/api/erc8004/[action]?action=validate"
+ },
+ {
+ "src": "/api/erc8004/validation",
+ "dest": "/api/erc8004/[action]?action=validation"
+ },
{
"src": "/api/subscriptions/plans(/.*)?",
"dest": "/api/subscriptions/plans.js"