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.

coin-buy trade flow expansion, ThreeWSFactory + ThreeWSPayments EVM contracts, pump signals dedup + cursor, onchain smoke suite

nirholas3310379e1a1c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 61fdc6529..5ba1a98fa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,11 +7,15 @@ 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]`
+- **Agents can autonomously trade USDC-paired coins** — 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. (`/pump-dashboard`) `[feature]`
- **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 Live: real token art, live market caps, and a feed that heals itself** — The Pump Live showcase (three.ws/pump-live) — where a 3D agent reacts to brand-new pump.fun launches in real time — is now fully wired. Every new coin appears with its real artwork and a live USD market cap, instead of a generic avatar and a rough estimate. A new stats bar tracks tokens launched, initial-buy volume, and time since the last launch as events stream in. Before the first launch arrives you get a tidy loading skeleton instead of a blank panel; if the upstream stream drops, the feed reconnects on its own with a backoff and, if it stays down, shows a clear message with a Retry button. Token images are resolved and served through three.ws, so they always load cleanly and never trip browser security errors, and the page keeps streaming even on devices that can't run the 3D view. (`/pump-live`) `[improvement, fix]`
- **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]`
+- **Registered agents now carry an on-chain "Validated" badge** — When an agent is registered on-chain, three.ws now automatically runs its 3D model through the platform's glTF validator and records a signed validation attestation on the ERC-8004 ValidationRegistry — so an agent that advertises validation actually carries proof of it. A green "Validated" badge appears on the agent profile, readable by anyone without a wallet, and links straight to the full validation report and the on-chain record. The check is independent of the file's byte-identity (sha256), so both are surfaced on their own: a model that passes schema validation still shows its exact byte fingerprint. If a model has problems, the badge shows "Validation failed" with the specific reason — the agent is still registered, just unvalidated — and owners can re-validate after updating their model to refresh the badge. Validation is best-effort and never blocks or reverts a registration. (`/marketplace`) `[feature, security]`
+- **Strategy Lab now catches broken trading strategies before they run** — Validation in the Strategy Lab (three.ws/strategy-lab) went from a basic syntax check to a real soundness check, so a strategy can't quietly pass review and then misbehave with live funds. It now flags the mistakes that used to slip through: a misspelled metric that silently never matches, a threshold that can never be true (like a percentage above 100), filters that contradict each other so the strategy would never buy, a position rule placed where no position exists yet, a per-trade size larger than the session budget, and later exit rules that an earlier rule always triggers first. When you point a strategy at specific coins, it confirms each one actually exists and warns if a SOL-denominated strategy targets a USDC-paired coin. Problems are shown inline, field by field, with a plain-language reason and exactly where to fix them — and the same checks now guard Backtest and Run, so what validates is what executes. (`/strategy-lab`) `[improvement]`
- **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]`
diff --git a/agent-protocol-sdk/README.md b/agent-protocol-sdk/README.md
index b71a49014..8f695e682 100644
--- a/agent-protocol-sdk/README.md
+++ b/agent-protocol-sdk/README.md
@@ -28,12 +28,14 @@
> instruction, and submitted on-chain, where it emits a `SkillInvoked` event that
> anyone can verify. Built for three.ws agent-to-agent (A2A) coordination.
-> **Pending deployment.** The `agent_invocation` program is **not yet deployed to
-> mainnet**. The program id exported as `AGENT_INVOCATION_PROGRAM_ID`
-> (`Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS`) is the Anchor placeholder id,
-> not a live deployment. To use this SDK against a real cluster you **must deploy
-> the program yourself and pass your own `programId`** to `invokeSkill()` /
-> `deriveAgentPda()`. Until then, treat the defaults as devnet/local scaffolding.
+> **Live.** The `agent_invocation` program is deployed and the SDK targets it by
+> default. `AGENT_INVOCATION_PROGRAM_ID` is
+> [`AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo`](https://explorer.solana.com/address/AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo) —
+> the same program id on **mainnet-beta** and **devnet**. Just point `connection`
+> at the cluster you want; the `programId` param is optional and only needed to
+> target a different deployment. Deploy addresses, signatures, and the upgrade
+> authority are recorded in
+> [`contracts/agent-invocation/DEPLOYMENT.md`](https://github.com/nirholas/three.ws/blob/main/contracts/agent-invocation/DEPLOYMENT.md).
## Install
@@ -50,7 +52,8 @@ dependencies and are installed alongside the package.
import { Connection, Keypair, PublicKey } from '@solana/web3.js';
import { invokeSkill } from '@three-ws/agent-protocol-sdk';
-const connection = new Connection('https://api.devnet.solana.com', 'confirmed');
+// mainnet-beta by default; use 'https://api.devnet.solana.com' for devnet.
+const connection = new Connection('https://api.mainnet-beta.solana.com', 'confirmed');
const invokerAuthority = Keypair.fromSecretKey(/* your secret key bytes */);
const targetAuthority = new PublicKey('<authority that owns the target agent>');
@@ -60,7 +63,7 @@ const signature = await invokeSkill({
targetAuthority, // target agent PDA is derived from this
skillName: 'summarize', // 1–64 bytes
parameters: JSON.stringify({ url: 'https://example.com' }), // ≤512 bytes
- programId: new PublicKey('<your deployed program id>'), // required on a live cluster
+ // programId is optional — defaults to the live AGENT_INVOCATION_PROGRAM_ID.
});
console.log('invocation tx:', signature);
@@ -109,7 +112,7 @@ const [agentPda, bump] = deriveAgentPda(authority, programId);
| --- | --- | --- |
| `MAX_SKILL_NAME_LEN` | `number` | `64` — max `skillName` length in bytes. |
| `MAX_PARAMETERS_LEN` | `number` | `512` — max `parameters` length in bytes. |
-| `AGENT_INVOCATION_PROGRAM_ID` | `string` | Declared program id (placeholder until deployed). |
+| `AGENT_INVOCATION_PROGRAM_ID` | `string` | Live program id (`AgEnt…Zfo`), same on mainnet + devnet. |
| `IDL` | Anchor `Idl` | The `agent_invocation` IDL (Anchor 0.30+ format). |
| `AgentInvocation` | `type` | TypeScript type of `IDL` for `new Program<AgentInvocation>(...)`. |
| `InvokeSkillParams` | `interface` | Parameter shape for `invokeSkill`. |
@@ -128,9 +131,10 @@ validation above.
- **Node** `>= 18`.
- **Peers / deps:** `@solana/web3.js@^1.98`, `@coral-xyz/anchor@^0.32`.
-- **A deployed program.** On any live cluster you must deploy `agent_invocation`
- and pass its id as `programId`. The default `AGENT_INVOCATION_PROGRAM_ID` is a
- placeholder.
+- **A funded invoker.** `invokerAuthority` signs and pays the transaction fee, so
+ it needs a small SOL balance on the target cluster. The program itself is
+ already deployed — `AGENT_INVOCATION_PROGRAM_ID` points at the live program on
+ mainnet and devnet.
## Links
diff --git a/api/_lib/channel-feed-sources.js b/api/_lib/channel-feed-sources.js
index 385391a27..6a09de4a3 100644
--- a/api/_lib/channel-feed-sources.js
+++ b/api/_lib/channel-feed-sources.js
@@ -39,3 +39,73 @@ export async function getWhales(limit = 50) {
export async function getClaims(limit = 50) {
return readList('pf:claims', limit);
}
+
+// Agent-attributed pump.fun reputation signals, newest-first, sourced from the
+// pumpfun_signals rows the pumpfun-signals cron writes (not Redis). Each row is
+// joined to the agent it belongs to so the channel feed can render
+// "<agent> — graduated a token (+0.3)". Returns [] when the DB is unreachable.
+let _sqlPromise = null;
+async function getSql() {
+ if (!_sqlPromise) _sqlPromise = import('./db.js').then((m) => m.sql).catch(() => null);
+ return _sqlPromise;
+}
+
+const SIGNAL_LABELS = {
+ first_claim: 'first creator-fee claim',
+ graduation: 'graduated a token',
+ influencer: 'influencer-tier claim',
+ whale_buy: 'whale buy',
+ launch: 'launched a token',
+ new_account: 'new-account claim',
+ fake_claim: 'flagged claim',
+};
+
+function signalSummary(row) {
+ const who =
+ row.agent_name ||
+ (row.wallet ? `${row.wallet.slice(0, 4)}…${row.wallet.slice(-4)}` : 'an agent');
+ const what = SIGNAL_LABELS[row.kind] || String(row.kind || 'signal').replace(/_/g, ' ');
+ const w = Number(row.weight);
+ const sign = Number.isFinite(w) && w !== 0 ? ` (${w > 0 ? '+' : ''}${w})` : '';
+ return `${who} — ${what}${sign}`;
+}
+
+export async function getSignals(limit = 50) {
+ const sql = await getSql();
+ if (!sql) return [];
+ const cap = Math.min(Math.max(limit | 0 || 50, 1), 200);
+ try {
+ const rows = await sql`
+ select s.tx_signature, s.kind, s.weight, s.wallet, s.agent_asset,
+ s.payload, s.seen_at,
+ a.id as agent_id, a.name as agent_name
+ from pumpfun_signals s
+ left join agent_identities a
+ on a.meta->>'sol_mint_address' = s.agent_asset
+ and a.deleted_at is null
+ order by s.seen_at desc
+ limit ${cap}
+ `;
+ return rows.map((r) => ({
+ // Distinct dedup key so an agent-attributed signal is not collapsed
+ // against the raw mint/whale/claim event that shares its tx.
+ signature: `signal:${r.tx_signature}:${r.kind}`,
+ tx_signature: r.tx_signature,
+ mint: r.payload?.mint ?? null,
+ name: r.agent_name ?? null,
+ symbol: r.payload?.symbol ?? null,
+ signal_kind: r.kind,
+ weight: Number.isFinite(Number(r.weight)) ? Number(r.weight) : 0,
+ wallet: r.wallet ?? null,
+ agent_asset: r.agent_asset ?? null,
+ agent_id: r.agent_id ?? null,
+ agent_name: r.agent_name ?? null,
+ summary: signalSummary(r),
+ timestamp: r.seen_at ? Math.floor(new Date(r.seen_at).getTime() / 1000) : 0,
+ payload: r.payload ?? {},
+ }));
+ } catch (err) {
+ console.error('[channel-feed-sources] signals read failed:', err?.message || err);
+ return [];
+ }
+}
diff --git a/api/_lib/migrations/20260615000000_pumpfun_signals_dedup_and_cursor.sql b/api/_lib/migrations/20260615000000_pumpfun_signals_dedup_and_cursor.sql
new file mode 100644
index 000000000..54417379e
--- /dev/null
+++ b/api/_lib/migrations/20260615000000_pumpfun_signals_dedup_and_cursor.sql
@@ -0,0 +1,54 @@
+-- pumpfun_signals: allow multiple signal kinds per transaction + add a crawl cursor.
+--
+-- 1) The original schema declared `tx_signature text unique`, which makes it
+-- impossible to store more than ONE signal kind per pump.fun transaction —
+-- e.g. a single first-time creator-fee claim that is ALSO `influencer` tier
+-- AND from a `new_account` should produce three rows, but the second/third
+-- inserts collide on the bare tx_signature unique. The correct dedup key is
+-- (tx_signature, kind): exactly one row per (transaction, signal kind).
+-- Drop the single-column unique and replace it with the composite.
+--
+-- 2) The pumpfun-signals cron previously re-scanned the full recent-events
+-- window every run (relying on ON CONFLICT DO NOTHING to no-op the dups).
+-- pumpfun_signals_cursor lets the cron persist the newest event timestamp it
+-- has processed per source so each run only evaluates genuinely new events.
+-- The cursor lives in Postgres (NOT Redis) to keep Upstash write volume flat
+-- — see tasks/redis-burn-rate-reduction.md.
+
+begin;
+
+-- 0) A signal can be agent-attributed without a specific actor wallet — e.g. the
+-- self-sourced graduation signal pump-agent-stats emits keys off the token
+-- mint (agent_asset) and has no claimer wallet. The original `wallet not null`
+-- made that insert fail silently, so relax it.
+alter table pumpfun_signals alter column wallet drop not null;
+
+-- 1) Replace the bare tx_signature unique with a composite (tx_signature, kind).
+-- Drop the auto-named constraint/index from the inline `unique` declaration.
+alter table pumpfun_signals drop constraint if exists pumpfun_signals_tx_signature_key;
+drop index if exists pumpfun_signals_tx_signature_key;
+
+do $$
+begin
+ if not exists (
+ select 1 from pg_constraint where conname = 'pumpfun_signals_tx_kind_key'
+ ) then
+ alter table pumpfun_signals
+ add constraint pumpfun_signals_tx_kind_key unique (tx_signature, kind);
+ end if;
+end $$;
+
+-- Channel-feed reads recent signals newest-first across all kinds.
+create index if not exists pumpfun_signals_seen_at on pumpfun_signals(seen_at desc);
+
+-- 2) Per-source crawl cursor. `last_seen_ms` is the epoch-millisecond timestamp
+-- of the newest event the cron has evaluated for that source; the next run
+-- skips anything strictly older. `last_signature` is kept for observability.
+create table if not exists pumpfun_signals_cursor (
+ source text primary key, -- 'claims' | 'whales' | 'mints' | 'graduations'
+ last_seen_ms bigint not null default 0,
+ last_signature text,
+ updated_at timestamptz not null default now()
+);
+
+commit;
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index a6fd66250..780b959a0 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -992,17 +992,31 @@ create table if not exists user_prefs (
-- and surface trust signals on the agent passport.
create table if not exists pumpfun_signals (
id bigserial primary key,
- wallet text not null, -- claimer / creator base58 pubkey
+ wallet text, -- claimer / creator / buyer base58 pubkey (null for mint-attributed signals)
agent_asset text, -- linked Solana agent if known
- kind text not null, -- 'first_claim' | 'fake_claim' | 'graduation' | 'influencer' | 'new_account'
+ kind text not null, -- 'first_claim' | 'fake_claim' | 'graduation' | 'influencer' | 'new_account' | 'whale_buy' | 'launch'
weight real not null default 0,-- reputation impact, -1..1
payload jsonb not null default '{}'::jsonb,
- tx_signature text unique,
- seen_at timestamptz not null default now()
+ tx_signature text,
+ seen_at timestamptz not null default now(),
+ -- One row per (transaction, signal kind): a single tx can legitimately
+ -- carry several signal kinds (e.g. first_claim + influencer + new_account).
+ constraint pumpfun_signals_tx_kind_key unique (tx_signature, kind)
+);
+create index if not exists pumpfun_signals_wallet on pumpfun_signals(wallet, seen_at desc);
+create index if not exists pumpfun_signals_agent on pumpfun_signals(agent_asset, seen_at desc) where agent_asset is not null;
+create index if not exists pumpfun_signals_kind on pumpfun_signals(kind, seen_at desc);
+create index if not exists pumpfun_signals_seen_at on pumpfun_signals(seen_at desc);
+
+-- Per-source crawl cursor for the pumpfun-signals cron. Keeps the sweep from
+-- re-evaluating the whole recent-events window every run; lives in Postgres to
+-- avoid spending Upstash write quota (tasks/redis-burn-rate-reduction.md).
+create table if not exists pumpfun_signals_cursor (
+ source text primary key, -- 'claims' | 'whales' | 'mints' | 'graduations'
+ last_seen_ms bigint not null default 0,
+ last_signature text,
+ updated_at timestamptz not null default now()
);
-create index if not exists pumpfun_signals_wallet on pumpfun_signals(wallet, seen_at desc);
-create index if not exists pumpfun_signals_agent on pumpfun_signals(agent_asset, seen_at desc) where agent_asset is not null;
-create index if not exists pumpfun_signals_kind on pumpfun_signals(kind, seen_at desc);
-- ── marketplace_skills — community skill registry ────────────────────────────
-- Two flavors:
diff --git a/api/alerts/config.js b/api/alerts/config.js
deleted file mode 100644
index 1c88e7c51..000000000
--- a/api/alerts/config.js
+++ /dev/null
@@ -1,108 +0,0 @@
-// GET /api/alerts/config — the signed-in user's pump alert rules.
-// PUT /api/alerts/config — upsert those rules.
-//
-// Server-persisted so alerts survive across devices and so the pumpfun-monitor
-// cron can evaluate them when no dashboard tab is open. The frontend treats
-// localStorage as a render cache only; this endpoint is 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, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import { z } from 'zod';
-
-const DEFAULTS = {
- graduation: true,
- whale: false,
- fees: false,
- launch: false,
- whaleThreshold: 10,
- claimThreshold: 0.5,
- cooldown: 30,
- webhookUrl: null,
-};
-
-const putSchema = z.object({
- graduation: z.boolean(),
- whale: z.boolean(),
- fees: z.boolean(),
- launch: z.boolean(),
- whaleThreshold: z.coerce.number().min(0).max(1_000_000),
- claimThreshold: z.coerce.number().min(0).max(1_000_000),
- cooldown: z.coerce.number().int().min(5).max(86_400),
- webhookUrl: z
- .string()
- .trim()
- .max(2048)
- .url()
- .refine((u) => /^https:\/\//i.test(u), 'webhook must be https')
- .optional()
- .nullable()
- .or(z.literal('').transform(() => null)),
-});
-
-function rowToConfig(row) {
- if (!row) return { ...DEFAULTS };
- return {
- graduation: row.graduation,
- whale: row.whale,
- fees: row.fees,
- launch: row.launch,
- whaleThreshold: Number(row.whale_threshold),
- claimThreshold: Number(row.claim_threshold),
- cooldown: row.cooldown_seconds,
- webhookUrl: row.webhook_url || null,
- updated_at: row.updated_at || null,
- };
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET', 'PUT'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.prefsWrite(user.id);
- if (!rl.success) return rateLimited(res, rl);
-
- if (req.method === 'GET') {
- const [row] = await sql`
- SELECT graduation, whale, fees, launch, whale_threshold, claim_threshold,
- cooldown_seconds, webhook_url, updated_at
- FROM user_alert_configs
- WHERE user_id = ${user.id}
- `;
- return json(res, 200, { data: rowToConfig(row) });
- }
-
- // PUT — upsert
- if (!(await requireCsrf(req, res, user.id))) return;
-
- const body = parse(putSchema, await readJson(req));
- const webhook = body.webhookUrl ?? null;
-
- const [row] = await sql`
- INSERT INTO user_alert_configs
- (user_id, graduation, whale, fees, launch, whale_threshold, claim_threshold, cooldown_seconds, webhook_url, updated_at)
- VALUES
- (${user.id}, ${body.graduation}, ${body.whale}, ${body.fees}, ${body.launch},
- ${body.whaleThreshold}, ${body.claimThreshold}, ${body.cooldown}, ${webhook}, now())
- ON CONFLICT (user_id) DO UPDATE SET
- graduation = excluded.graduation,
- whale = excluded.whale,
- fees = excluded.fees,
- launch = excluded.launch,
- whale_threshold = excluded.whale_threshold,
- claim_threshold = excluded.claim_threshold,
- cooldown_seconds = excluded.cooldown_seconds,
- webhook_url = excluded.webhook_url,
- updated_at = now()
- RETURNING graduation, whale, fees, launch, whale_threshold, claim_threshold,
- cooldown_seconds, webhook_url, updated_at
- `;
-
- return json(res, 200, { data: rowToConfig(row) });
-});
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 8c677e4b6..6a3259973 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -46,6 +46,7 @@ import {
} from '../_lib/pump.js';
import { mintAttestation, deriveEventId, loadAttesterKeypair } from '../_lib/attest-event.js';
import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';
+import { getMints, getWhales, getClaims } from '../_lib/channel-feed-sources.js';
import { crawlAgentAttestations } from '../_lib/solana-attestations.js';
import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
import { chargeSubscription, failPayment } from '../_lib/subscription-billing.js';
@@ -878,7 +879,7 @@ async function handlePumpAgentStats(req, res) {
${JSON.stringify({ source: 'pump-agent-stats', network: m.network })}::jsonb,
${`graduated:${m.mint}:${Date.now()}`}
)
- on conflict (tx_signature) do nothing
+ on conflict (tx_signature, kind) do nothing
`;
} catch {
// pumpfun_signals table optional
@@ -1226,13 +1227,21 @@ export { detectEvents, WHALE_TRADE_USD_FLOOR };
const CLAIMS_PER_RUN = 200;
const GRADS_PER_RUN = 50;
+const WHALES_PER_RUN = 100;
+const MINTS_PER_RUN = 100;
+// Leave headroom under Vercel's function limit. The sources are cheap (Redis
+// lrange + one Postgres read), but the per-signal inserts are sequential, so a
+// budget keeps a large backlog from running long on a cold DB.
+const SIGNALS_TIME_BUDGET_MS = 22_000;
const SIGNAL_WEIGHT = {
first_claim: +0.2,
graduation: +0.3,
influencer: +0.2,
- fake_claim: -0.6,
+ whale_buy: +0.1,
+ launch: +0.05,
new_account: -0.2,
+ fake_claim: -0.6,
};
async function handlePumpfunSignals(req, res) {
@@ -1240,38 +1249,151 @@ async function handlePumpfunSignals(req, res) {
if (!requireCron(req, res)) return;
- // Graduations come from the live WS-fed table (pumpfunMcp.graduations falls
- // back to Postgres), so the graduation→signal path runs with or without the
- // optional upstream bot. Claims enrichment still requires the bot, so it's
- // skipped cleanly when the bot is unset.
+ // Every source below is real and bot-independent:
+ // • graduations — pumpfunMcp.graduations() reads the WS-fed
+ // pumpfun_graduations table (kept live by pumpfun-graduations-sync), or
+ // the upstream bot when PUMPFUN_BOT_URL is set.
+ // • claims — the bot's getRecentClaims (rich tier/age intel) when
+ // configured, merged with the pf:claims Redis lane the channel feed uses.
+ // • whales — pf:whales Redis lane (first whale-buy events).
+ // • mints — pf:mints Redis lane (new token launches).
+ // The cron emits whatever is live and degrades gracefully when a lane is
+ // empty; it never fabricates events.
const botEnabled = pumpfunBotEnabled();
+ const deadline = Date.now() + SIGNALS_TIME_BUDGET_MS;
- const [claims, grads] = await Promise.all([
+ const [claimsBot, grads, redisClaims, whales, mints] = await Promise.all([
botEnabled
- ? pumpfunMcp.recentClaims({ limit: CLAIMS_PER_RUN })
- : Promise.resolve({ ok: true, data: [] }),
- pumpfunMcp.graduations({ limit: GRADS_PER_RUN }),
+ ? pumpfunMcp.recentClaims({ limit: CLAIMS_PER_RUN }).catch((e) => ({ ok: false, error: e?.message }))
+ : Promise.resolve({ ok: false }),
+ pumpfunMcp.graduations({ limit: GRADS_PER_RUN }).catch((e) => ({ ok: false, error: e?.message })),
+ getClaims(CLAIMS_PER_RUN).catch(() => []),
+ getWhales(WHALES_PER_RUN).catch(() => []),
+ getMints(MINTS_PER_RUN).catch(() => []),
]);
- const report = { bot: botEnabled, claims: 0, graduations: 0, inserted: 0, skipped: 0, errors: [] };
-
- const claimItems = pumpfunArr(claims.ok ? claims.data : null);
+ // Bot claims carry richer intel (tier, github_account_age_days); the Redis
+ // lane is a bot-free fallback. Merge with bot enrichment winning on tx
+ // collisions.
+ const claimItems = pumpfunMergeBySig(
+ pumpfunArr(claimsBot.ok ? claimsBot.data : null),
+ Array.isArray(redisClaims) ? redisClaims : [],
+ );
const gradItems = pumpfunArr(grads.ok ? grads.data : null);
- report.claims = claimItems.length;
- report.graduations = gradItems.length;
+ const whaleItems = Array.isArray(whales) ? whales : [];
+ const mintItems = Array.isArray(mints) ? mints : [];
+
+ const report = {
+ bot: botEnabled,
+ sources: {
+ claims: claimItems.length,
+ graduations: gradItems.length,
+ whales: whaleItems.length,
+ mints: mintItems.length,
+ },
+ inserted: 0,
+ skipped_unlinked: 0,
+ skipped_by_cursor: 0,
+ errors: [],
+ };
+
+ // Resolve every actor wallet → linked agent asset in a single query, and load
+ // the per-source cursors so we only evaluate events newer than last run.
+ const wallets = pumpfunCollectWallets({
+ claims: claimItems,
+ grads: gradItems,
+ whales: whaleItems,
+ mints: mintItems,
+ });
+ const [linked, cursors] = await Promise.all([
+ pumpfunLinkedWalletMap(wallets),
+ pumpfunLoadCursors(),
+ ]);
+
+ // Process each source through its cursor. Graduations are the highest-signal,
+ // always-on lane, so they run first within the time budget.
+ await pumpfunProcessSource({
+ source: 'graduations', items: gradItems, cursors, linked, report, deadline,
+ walletOf: (ev) => ev.creator || ev.dev_wallet,
+ signalsOf: (ev) => [{
+ kind: 'graduation',
+ payload: { mint: ev.mint, symbol: ev.symbol, name: ev.name },
+ tx_signature: ev.tx_signature || ev.signature,
+ }],
+ });
+ await pumpfunProcessSource({
+ source: 'claims', items: claimItems, cursors, linked, report, deadline,
+ walletOf: (ev) => ev.claimer || ev.github_wallet,
+ signalsOf: (ev) => pumpfunSignalsFromClaim(ev),
+ });
+ await pumpfunProcessSource({
+ source: 'whales', items: whaleItems, cursors, linked, report, deadline,
+ walletOf: (ev) => ev.buyer || ev.trader || ev.traderPublicKey,
+ signalsOf: (ev) => [{
+ kind: 'whale_buy',
+ payload: { mint: ev.mint, amount_sol: ev.amount_sol ?? ev.sol_amount ?? null },
+ tx_signature: ev.signature || ev.tx_signature,
+ }],
+ });
+ await pumpfunProcessSource({
+ source: 'mints', items: mintItems, cursors, linked, report, deadline,
+ walletOf: (ev) => ev.creator || ev.traderPublicKey,
+ signalsOf: (ev) => [{
+ kind: 'launch',
+ payload: { mint: ev.mint, symbol: ev.symbol, name: ev.name },
+ tx_signature: ev.signature || ev.tx_signature,
+ }],
+ });
- const wallets = pumpfunCollectWallets(claimItems, gradItems);
- const linked = await pumpfunLinkedWalletMap(wallets);
+ return json(res, 200, report);
+}
- for (const ev of claimItems) {
- const wallet = ev.claimer || ev.github_wallet;
+// Normalize a feed event's timestamp to epoch milliseconds. pump.fun lanes use
+// epoch seconds; the graduations table may surface ISO strings. Falls back to
+// now() so an event without a timestamp is still treated as fresh (processed
+// once, then skipped by the cursor next run).
+function pumpfunTsMs(ev) {
+ const t = ev?.timestamp ?? ev?.created_at ?? ev?._seen_at ?? ev?.seen_at ?? null;
+ if (t == null) return Date.now();
+ if (typeof t === 'number') return t < 1e12 ? Math.round(t * 1000) : Math.round(t);
+ const parsed = Date.parse(t);
+ return Number.isFinite(parsed) ? parsed : Date.now();
+}
+
+// Walk a newest-first event list, emitting signals only for events at or after
+// the stored cursor and only for wallets linked to an agent. Advances the
+// cursor to the newest event timestamp seen (never backwards) so the next run
+// skips everything older. Events strictly older than the cursor are counted in
+// report.skipped_by_cursor and never re-inserted.
+async function pumpfunProcessSource({ source, items, cursors, linked, report, deadline, walletOf, signalsOf }) {
+ const cursorMs = cursors.get(source) ?? 0;
+ let maxMs = cursorMs;
+ let newestSig = null;
+
+ for (const ev of items) {
+ if (Date.now() > deadline) break;
+
+ const tsMs = pumpfunTsMs(ev);
+ if (tsMs < cursorMs) {
+ report.skipped_by_cursor++;
+ continue;
+ }
+ // Track the high-water mark across all events (linked or not) so we don't
+ // re-evaluate already-seen events next run.
+ if (tsMs > maxMs) {
+ maxMs = tsMs;
+ newestSig = ev.signature || ev.tx_signature || newestSig;
+ }
+
+ const wallet = walletOf(ev);
if (!wallet || !linked.has(wallet)) {
- report.skipped++;
+ report.skipped_unlinked++;
continue;
}
+
try {
- const inserts = pumpfunSignalsFromClaim(ev);
- for (const sig of inserts) {
+ for (const sig of signalsOf(ev)) {
+ if (!sig.tx_signature) continue;
const ok = await pumpfunInsertSignal({
wallet,
agent_asset: linked.get(wallet) || null,
@@ -1283,32 +1405,53 @@ async function handlePumpfunSignals(req, res) {
if (ok) report.inserted++;
}
} catch (err) {
- report.errors.push({ tx: ev.tx_signature, error: err.message });
+ report.errors.push({ source, tx: ev.signature || ev.tx_signature, error: err.message });
}
}
- for (const ev of gradItems) {
- const wallet = ev.creator || ev.dev_wallet;
- if (!wallet || !linked.has(wallet)) {
- report.skipped++;
- continue;
- }
- try {
- const ok = await pumpfunInsertSignal({
- wallet,
- agent_asset: linked.get(wallet) || null,
- kind: 'graduation',
- weight: SIGNAL_WEIGHT.graduation,
- payload: { mint: ev.mint, symbol: ev.symbol, name: ev.name },
- tx_signature: ev.tx_signature || ev.signature,
- });
- if (ok) report.inserted++;
- } catch (err) {
- report.errors.push({ tx: ev.tx_signature, error: err.message });
- }
+ if (maxMs > cursorMs) {
+ await pumpfunSaveCursor(source, maxMs, newestSig).catch((e) =>
+ report.errors.push({ source, stage: 'cursor', error: e?.message || String(e) }),
+ );
}
+}
- return json(res, 200, report);
+// Merge two event lists, deduping by signature with `primary` winning. Used to
+// fold the bot's rich claims over the bot-free Redis lane.
+function pumpfunMergeBySig(primary, secondary) {
+ const seen = new Set();
+ const out = [];
+ for (const e of [...primary, ...secondary]) {
+ const sig = e?.signature || e?.tx_signature;
+ if (!sig || seen.has(sig)) continue;
+ seen.add(sig);
+ out.push(e);
+ }
+ return out;
+}
+
+// Load every source cursor in one read. Returns source → last_seen_ms. A missing
+// cursor table (not migrated yet) degrades to "no cursor" so the cron still runs.
+async function pumpfunLoadCursors() {
+ const map = new Map();
+ try {
+ const rows = await sql`select source, last_seen_ms from pumpfun_signals_cursor`;
+ for (const r of rows) map.set(r.source, Number(r.last_seen_ms) || 0);
+ } catch {
+ // cursor table absent — process once, then it's created on first save.
+ }
+ return map;
+}
+
+async function pumpfunSaveCursor(source, lastSeenMs, lastSignature) {
+ await sql`
+ insert into pumpfun_signals_cursor (source, last_seen_ms, last_signature, updated_at)
+ values (${source}, ${Math.floor(lastSeenMs)}, ${lastSignature || null}, now())
+ on conflict (source) do update set
+ last_seen_ms = greatest(pumpfun_signals_cursor.last_seen_ms, excluded.last_seen_ms),
+ last_signature = excluded.last_signature,
+ updated_at = now()
+ `;
}
// ═══════════════════════════════════════════════════════════════════════════
@@ -1387,16 +1530,13 @@ function pumpfunArr(x) {
return Array.isArray(x) ? x : x.items || [];
}
-function pumpfunCollectWallets(claims, grads) {
+function pumpfunCollectWallets({ claims = [], grads = [], whales = [], mints = [] }) {
const out = new Set();
- for (const c of claims) {
- if (c.claimer) out.add(c.claimer);
- if (c.github_wallet) out.add(c.github_wallet);
- }
- for (const g of grads) {
- if (g.creator) out.add(g.creator);
- if (g.dev_wallet) out.add(g.dev_wallet);
- }
+ const add = (w) => { if (w) out.add(w); };
+ for (const c of claims) { add(c.claimer); add(c.github_wallet); }
+ for (const g of grads) { add(g.creator); add(g.dev_wallet); }
+ for (const w of whales) { add(w.buyer); add(w.trader); add(w.traderPublicKey); }
+ for (const m of mints) { add(m.creator); add(m.traderPublicKey); }
return [...out];
}
@@ -1434,7 +1574,7 @@ async function pumpfunInsertSignal({ wallet, agent_asset, kind, weight, payload,
const result = await sql`
insert into pumpfun_signals (wallet, agent_asset, kind, weight, payload, tx_signature)
values (${wallet}, ${agent_asset}, ${kind}, ${weight}, ${JSON.stringify(payload)}::jsonb, ${tx_signature})
- on conflict (tx_signature) do nothing
+ on conflict (tx_signature, kind) do nothing
returning id
`;
return result.length > 0;
diff --git a/api/pump/channel-feed.js b/api/pump/channel-feed.js
index 16f7248c6..2fae21b1b 100644
--- a/api/pump/channel-feed.js
+++ b/api/pump/channel-feed.js
@@ -1,6 +1,6 @@
import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { getMints, getWhales, getClaims } from '../_lib/channel-feed-sources.js';
+import { getMints, getWhales, getClaims, getSignals } from '../_lib/channel-feed-sources.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
@@ -16,10 +16,11 @@ export default wrap(async (req, res) => {
const limitRaw = limitParam ? parseInt(limitParam, 10) : 100;
const limit = Math.min(Math.max(Number.isFinite(limitRaw) ? limitRaw : 100, 1), 200);
- const [mints, whales, claims] = await Promise.all([
+ const [mints, whales, claims, signals] = await Promise.all([
(!allowed || allowed.has('mint')) ? getMints().catch(() => []) : [],
(!allowed || allowed.has('whale')) ? getWhales().catch(() => []) : [],
(!allowed || allowed.has('claim')) ? getClaims().catch(() => []) : [],
+ (!allowed || allowed.has('signal')) ? getSignals().catch(() => []) : [],
]);
const seen = new Set();
@@ -27,6 +28,7 @@ export default wrap(async (req, res) => {
...mints.map(e => ({ ...e, kind: 'mint' })),
...whales.map(e => ({ ...e, kind: 'whale' })),
...claims.map(e => ({ ...e, kind: 'claim', signature: e.signature || e.tx_signature })),
+ ...signals.map(e => ({ ...e, kind: 'signal' })),
]
.filter(e => {
const sig = e.signature || e.tx_signature;
diff --git a/contracts/DEPLOYMENTS.md b/contracts/DEPLOYMENTS.md
index fe7196bf9..727e52222 100644
--- a/contracts/DEPLOYMENTS.md
+++ b/contracts/DEPLOYMENTS.md
@@ -27,6 +27,19 @@ Avalanche Fuji (43113)
| ReputationRegistry | `0x8004B663056A597Dffe9eCcC1965A193B7388713` | TODO: fill after deployment |
| ValidationRegistry | `0x8004Cb1BF31DAf7788923b405b754f57acEB4272` | TODO: fill after deployment |
+## Platform validator (ValidationRegistry attestor)
+
+The platform validator is the EVM key that signs glTF/schema validation
+attestations (`recordValidation`) when an agent is registered. It must be
+allow-listed via `addValidator(<addr>)` by the registry owner on every chain it
+attests on, funded with gas, and stored as the `VALIDATOR_PRIVATE_KEY` secret in
+Vercel (never committed). Provision/rotate with
+[`scripts/erc8004/provision-validator-key.mjs`](../scripts/erc8004/provision-validator-key.mjs).
+
+| Address | Allow-listed chains | Notes |
+| ------- | ------------------- | ----- |
+| `0x93Bc7EfB0059B784465619FC73C2db8D01b1CD04` | TODO: run `addValidator` per chain | Provisioned 2026-06-15. Pending funding + allow-list (testnet first: Base Sepolia 84532). |
+
## CREATE2 Factory (ThreeWSFactory)
Custom vanity-prefixed CREATE2 deployer used to obtain matching addresses across chains.
@@ -76,9 +89,50 @@ from the same salt.
| ---------------- | -------------------------------------------- | -------------------------------------------- | -- |
| BSC (56) | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` | [`0x00000000381f09742a30a5a49975514AeC1B72Cc`](https://bscscan.com/address/0x00000000381f09742a30a5a49975514AeC1B72Cc) | [`0xc4f4e87f…`](https://bscscan.com/tx/0xc4f4e87f67c70044a8682ea50d59fbc04e9777f453538a6916075f5409e5b7ef) |
| Arbitrum (42161) | `0xaf88d065e77c8cC2239327C5EDb3A432268e5831` | [`0xed3696489490dbfAFD82996ADB11165A56c33c49`](https://arbiscan.io/address/0xed3696489490dbfAFD82996ADB11165A56c33c49) | [`0xca39a600…`](https://arbiscan.io/tx/0xca39a6003e8a6144662aceae43ee2b2c5107e426e16ccf58a406d66d38f34e5f) |
-| Base (8453) | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | predicted `0x31B13cDe47431EfcC8616C8495204e6E6C2Ded34` — ⚠ tx mined success but address has no code, treat as **not deployed** | [`0xb6fcf60b…`](https://basescan.org/tx/0xb6fcf60b4ca16d25e135f91046107e78518fca9aa4f180d5110a5116bcdfe4d0) |
-
-Base deploy must be re-run and the address re-checked before integrations point at it.
+| Base (8453) | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | [`0x31B13cDe47431EfcC8616C8495204e6E6C2Ded34`](https://basescan.org/address/0x31B13cDe47431EfcC8616C8495204e6E6C2Ded34) | [`0xb6fcf60b…`](https://basescan.org/tx/0xb6fcf60b4ca16d25e135f91046107e78518fca9aa4f180d5110a5116bcdfe4d0) |
+
+### Base deploy status — LIVE, bytecode confirmed (re-verified 2026-06-15)
+
+The earlier "tx mined but address has no code → treat as **not deployed**" note was
+**wrong** — a stale/unsynced RPC reading at deploy time. The deploy succeeded. Proof,
+re-checked on-chain against live Base RPC:
+
+- Deploy tx [`0xb6fcf60b…`](https://basescan.org/tx/0xb6fcf60b4ca16d25e135f91046107e78518fca9aa4f180d5110a5116bcdfe4d0)
+ emitted `Deployed(addr=0x31B13cDe…, salt=0x5ef7540f…)` from `ThreeWSFactory` — so the
+ predicted address **is** the deployed address (no CREATE2 collision, no salt mismatch).
+- `eth_getCode(0x31B13cDe…)` returns **1243 bytes** (non-empty). `owner()` →
+ `0x4022de2D36C334E73C7a108805Cea11C0564f402` (the deployer EOA, as on BSC/Arbitrum),
+ and Base USDC `0x833589fCD6…` is embedded as the `USDC` immutable (BSC USDC is not).
+- Independently re-derived: compiling the in-repo source (`contracts/ThreeWSPayments.sol`,
+ solc `0.8.35`, optimizer 200) reproduces the **exact** recorded BSC init-code hash
+ `0xb55479df…` and live BSC address — confirming source + settings are byte-for-byte
+ correct — and CREATE2(`factory`, salt, Base-USDC init code) → `0x31B13cDe…`. The Base
+ init-code hash is `0x253291817df177b537145a05d0221065be924cffa606b387221b5c6bf8f1c475`.
+ (1243 bytes runtime, vs BSC's 1278, differs only because each chain's USDC enters the
+ constructor as an immutable.)
+
+**Basescan verification: PENDING (not yet verified).** Source + exact settings are
+captured in-repo; run `scripts/verify-threews-payments-base.mjs` with a
+`BASESCAN_API_KEY` set to publish (constructor args:
+`(0x4022de2D…, 0x833589fCD6…)`). The script prints the Standard JSON Input bundle for
+manual UI verification when no key is present.
+
+### Base payment routing — EOA `payTo` is intentional (no redeploy / no redirect)
+
+`X402_PAY_TO_BASE` stays the EOA `0x4022de2D36C334E73C7a108805Cea11C0564f402`, **not**
+the contract. Base x402 settles via the `exact` scheme (EIP-3009
+`transferWithAuthorization` / Permit2) through the CDP facilitator, which performs a
+plain ERC-20 USDC transfer to `payTo` — it never calls `pay(bytes32)` on the recipient.
+An EOA receiver is correct there: funds land directly and stay liquid. Pointing `payTo`
+at the contract would route USDC in via a raw transfer with **no `Payment` event**,
+recoverable only through the contract's `withdraw()` — strictly worse.
+
+`ThreeWSPayments` is load-bearing only on **BSC** (`X402_PAY_TO_BSC` = the contract),
+where Binance-Peg USDC implements no EIP-3009 and no facilitator advertises `eip155:56`,
+so the contract-mediated `pay(bytes32)` "direct" scheme is the only option (see
+`api/_lib/x402-bsc-direct.js`). The Base instance exists for cross-chain parity and as an
+on-chain record; the Base x402 flow has no code path that calls it, and Base payments
+have been settling correctly to the EOA all along.
Deploy command (run from 3D-Agent repo where `scripts/deploy-multichain.mjs` lives):
```
diff --git a/contracts/ThreeWSFactory.sol b/contracts/ThreeWSFactory.sol
new file mode 100644
index 000000000..2c1c2c49c
--- /dev/null
+++ b/contracts/ThreeWSFactory.sol
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.24;
+
+contract ThreeWSFactory {
+ event Deployed(address indexed addr, bytes32 indexed salt);
+
+ function deploy(bytes32 salt, bytes memory initCode) external returns (address addr) {
+ assembly {
+ addr := create2(0, add(initCode, 32), mload(initCode), salt)
+ }
+ require(addr != address(0), "deploy failed");
+ emit Deployed(addr, salt);
+ }
+
+ function predict(bytes32 salt, bytes32 initCodeHash) external view returns (address) {
+ return address(uint160(uint256(keccak256(abi.encodePacked(
+ bytes1(0xff), address(this), salt, initCodeHash
+ )))));
+ }
+}
diff --git a/contracts/ThreeWSPayments.sol b/contracts/ThreeWSPayments.sol
new file mode 100644
index 000000000..4b730bcc8
--- /dev/null
+++ b/contracts/ThreeWSPayments.sol
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: MIT
+pragma solidity ^0.8.24;
+
+/**
+ * @title ThreeWSPayments
+ * @notice x402 pay-per-call receiver for three.ws MCP tools on BNB Chain.
+ * Agents call pay() with a USDC allowance; the contract logs the
+ * on-chain receipt and the three.ws server verifies it before
+ * executing the requested tool.
+ *
+ * Deployed to a CREATE2 vanity address starting with 0x333...
+ * Factory: 0x4e59b44847b379578588920cA78FbF26c0B4956C (Arachnid)
+ * Website: https://three.ws/pay
+ */
+interface IERC20 {
+ function transferFrom(address from, address to, uint256 amount) external returns (bool);
+ function transfer(address to, uint256 amount) external returns (bool);
+ function balanceOf(address account) external view returns (uint256);
+}
+
+contract ThreeWSPayments {
+ IERC20 public immutable USDC;
+
+ // $0.001 USDC per tool call (6 decimals)
+ uint256 public pricePerCall = 1_000;
+
+ address public owner;
+
+ event Payment(
+ address indexed payer,
+ uint256 amount,
+ bytes32 indexed ref // keccak256 of the JSON-RPC request body
+ );
+ event PriceUpdated(uint256 oldPrice, uint256 newPrice);
+
+ error NotOwner();
+ error ZeroAddress();
+
+ modifier onlyOwner() {
+ if (msg.sender != owner) revert NotOwner();
+ _;
+ }
+
+ constructor(address _owner, address _usdc) {
+ if (_owner == address(0)) revert ZeroAddress();
+ if (_usdc == address(0)) revert ZeroAddress();
+ owner = _owner;
+ USDC = IERC20(_usdc);
+ }
+
+ /// @notice Pay for one tool call. Caller must have approved `pricePerCall` USDC.
+ /// @param ref keccak256 of the request body — lets the server match payment to call.
+ function pay(bytes32 ref) external {
+ uint256 amount = pricePerCall;
+ USDC.transferFrom(msg.sender, address(this), amount);
+ emit Payment(msg.sender, amount, ref);
+ }
+
+ /// @notice Withdraw accumulated USDC to owner.
+ function withdraw() external onlyOwner {
+ uint256 bal = USDC.balanceOf(address(this));
+ USDC.transfer(owner, bal);
+ }
+
+ /// @notice Update per-call price.
+ function setPrice(uint256 newPrice) external onlyOwner {
+ emit PriceUpdated(pricePerCall, newPrice);
+ pricePerCall = newPrice;
+ }
+
+ /// @notice Transfer ownership.
+ function transferOwnership(address newOwner) external onlyOwner {
+ if (newOwner == address(0)) revert ZeroAddress();
+ owner = newOwner;
+ }
+}
diff --git a/contracts/idl/agent_invocation.json b/contracts/idl/agent_invocation.json
new file mode 100644
index 000000000..d96accd97
--- /dev/null
+++ b/contracts/idl/agent_invocation.json
@@ -0,0 +1,161 @@
+{
+ "address": "AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo",
+ "metadata": {
+ "name": "agent_invocation",
+ "version": "0.2.0",
+ "spec": "0.1.0",
+ "description": "Verifiable agent-to-agent skill invocation on Solana."
+ },
+ "instructions": [
+ {
+ "name": "invoke_skill",
+ "discriminator": [
+ 141,
+ 69,
+ 221,
+ 241,
+ 163,
+ 138,
+ 14,
+ 221
+ ],
+ "accounts": [
+ {
+ "name": "invoker_agent",
+ "docs": [
+ "The invoking agent PDA, derived from the invoker authority."
+ ],
+ "pda": {
+ "seeds": [
+ {
+ "kind": "const",
+ "value": [
+ 97,
+ 103,
+ 101,
+ 110,
+ 116
+ ]
+ },
+ {
+ "kind": "account",
+ "path": "invoker_authority"
+ }
+ ]
+ }
+ },
+ {
+ "name": "invoker_authority",
+ "signer": true
+ },
+ {
+ "name": "target_authority"
+ },
+ {
+ "name": "target_agent",
+ "docs": [
+ "The target agent PDA, derived from the target authority."
+ ],
+ "pda": {
+ "seeds": [
+ {
+ "kind": "const",
+ "value": [
+ 97,
+ 103,
+ 101,
+ 110,
+ 116
+ ]
+ },
+ {
+ "kind": "account",
+ "path": "target_authority"
+ }
+ ]
+ }
+ },
+ {
+ "name": "system_program",
+ "address": "11111111111111111111111111111111"
+ }
+ ],
+ "args": [
+ {
+ "name": "skill_name",
+ "type": "string"
+ },
+ {
+ "name": "parameters",
+ "type": "string"
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "SkillInvoked",
+ "discriminator": [
+ 232,
+ 117,
+ 249,
+ 195,
+ 117,
+ 36,
+ 59,
+ 8
+ ]
+ }
+ ],
+ "errors": [
+ {
+ "code": 6000,
+ "name": "EmptySkillName",
+ "msg": "skill_name must not be empty"
+ },
+ {
+ "code": 6001,
+ "name": "SkillNameTooLong",
+ "msg": "skill_name exceeds the maximum allowed length"
+ },
+ {
+ "code": 6002,
+ "name": "ParametersTooLong",
+ "msg": "parameters exceed the maximum allowed length"
+ }
+ ],
+ "types": [
+ {
+ "name": "SkillInvoked",
+ "type": {
+ "kind": "struct",
+ "fields": [
+ {
+ "name": "invoker_agent",
+ "type": "pubkey"
+ },
+ {
+ "name": "target_agent",
+ "type": "pubkey"
+ },
+ {
+ "name": "invoker_authority",
+ "type": "pubkey"
+ },
+ {
+ "name": "skill_name",
+ "type": "string"
+ },
+ {
+ "name": "parameters",
+ "type": "string"
+ },
+ {
+ "name": "timestamp",
+ "type": "i64"
+ }
+ ]
+ }
+ }
+ ]
+}
diff --git a/contracts/vanity/payments-bsc-deployed.json b/contracts/vanity/payments-bsc-deployed.json
index 20bd41335..c1fa93317 100644
--- a/contracts/vanity/payments-bsc-deployed.json
+++ b/contracts/vanity/payments-bsc-deployed.json
@@ -13,6 +13,6 @@
"chains": {
"bsc": "0x00000000381f09742a30a5a49975514AeC1B72Cc",
"arbitrum": "0xed3696489490dbfAFD82996ADB11165A56c33c49",
- "base": "0x31B13cDe47431EfcC8616C8495204e6E6C2Ded34 (tx success but bytecode missing — treat as not deployed)"
+ "base": "0x31B13cDe47431EfcC8616C8495204e6E6C2Ded34"
}
}
diff --git a/data/changelog.json b/data/changelog.json
index e34cf0cd6..93d7e6411 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,27 @@
{
"$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": "Registered agents now carry an on-chain \"Validated\" badge",
+ "summary": "When an agent is registered on-chain, three.ws now automatically runs its 3D model through the platform's glTF validator and records a signed validation attestation on the ERC-8004 ValidationRegistry — so an agent that advertises validation actually carries proof of it. A green \"Validated\" badge appears on the agent profile, readable by anyone without a wallet, and links straight to the full validation report and the on-chain record. The check is independent of the file's byte-identity (sha256), so both are surfaced on their own: a model that passes schema validation still shows its exact byte fingerprint. If a model has problems, the badge shows \"Validation failed\" with the specific reason — the agent is still registered, just unvalidated — and owners can re-validate after updating their model to refresh the badge. Validation is best-effort and never blocks or reverts a registration.",
+ "tags": ["feature", "security"],
+ "link": "/marketplace"
+ },
+ {
+ "date": "2026-06-15",
+ "title": "Strategy Lab now catches broken trading strategies before they run",
+ "summary": "Validation in the Strategy Lab (three.ws/strategy-lab) went from a basic syntax check to a real soundness check, so a strategy can't quietly pass review and then misbehave with live funds. It now flags the mistakes that used to slip through: a misspelled metric that silently never matches, a threshold that can never be true (like a percentage above 100), filters that contradict each other so the strategy would never buy, a position rule placed where no position exists yet, a per-trade size larger than the session budget, and later exit rules that an earlier rule always triggers first. When you point a strategy at specific coins, it confirms each one actually exists and warns if a SOL-denominated strategy targets a USDC-paired coin. Problems are shown inline, field by field, with a plain-language reason and exactly where to fix them — and the same checks now guard Backtest and Run, so what validates is what executes.",
+ "tags": ["improvement"],
+ "link": "/strategy-lab"
+ },
+ {
+ "date": "2026-06-15",
+ "title": "Pump Live: real token art, live market caps, and a feed that heals itself",
+ "summary": "The Pump Live showcase (three.ws/pump-live) — where a 3D agent reacts to brand-new pump.fun launches in real time — is now fully wired. Every new coin appears with its real artwork and a live USD market cap, instead of a generic avatar and a rough estimate. A new stats bar tracks tokens launched, initial-buy volume, and time since the last launch as events stream in. Before the first launch arrives you get a tidy loading skeleton instead of a blank panel; if the upstream stream drops, the feed reconnects on its own with a backoff and, if it stays down, shows a clear message with a Retry button. Token images are resolved and served through three.ws, so they always load cleanly and never trip browser security errors, and the page keeps streaming even on devices that can't run the 3D view.",
+ "tags": ["improvement", "fix"],
+ "link": "/pump-live"
+ },
{
"date": "2026-06-15",
"title": "Agents can autonomously trade USDC-paired coins",
diff --git a/package.json b/package.json
index 1f9746dd6..705c7c758 100644
--- a/package.json
+++ b/package.json
@@ -66,6 +66,8 @@
"build:pages": "node scripts/build-page-index.mjs",
"changelog:push": "node scripts/changelog-telegram.mjs",
"audit:deploy": "node scripts/audit-deploy-artifacts.mjs",
+ "smoke:onchain": "node scripts/onchain-smoke.mjs",
+ "smoke:onchain:ci": "node scripts/onchain-smoke.mjs --only=parity",
"audit:mcp": "node scripts/audit-mcp-manifests.mjs",
"smoke:mcp": "node scripts/smoke-mcp-remotes.mjs",
"test:mcp": "node scripts/test-mcp-all.mjs",
diff --git a/pages/pump-dashboard.html b/pages/pump-dashboard.html
index bf156342f..d9a651e21 100644
--- a/pages/pump-dashboard.html
+++ b/pages/pump-dashboard.html
@@ -771,137 +771,105 @@
<!-- ═══════ Alerts page ═══════ -->
<section class="pd-page" id="page-alerts" aria-label="Alerts">
- <div class="pd-config-grid">
- <div class="pd-panel">
- <div class="pd-panel-head"><h2>Alert settings</h2></div>
- <div class="pd-panel-body">
- <div class="pd-toggle-row">
- <div class="pd-toggle-label">
- Graduation alerts
- <div class="pd-toggle-sub">
- Notify when tokens graduate to AMM
- </div>
- </div>
- <input
- class="pd-toggle"
- type="checkbox"
- id="pd-alert-graduation"
- checked
- />
+ <div class="pd-alert-grid">
+ <div class="pd-panel pd-rule-form-panel">
+ <div class="pd-panel-head">
+ <h2 id="pd-rule-form-title">New alert rule</h2>
+ <div class="pd-spacer"></div>
+ <button class="pd-btn pd-btn-sm" id="pd-rule-cancel" type="button" hidden>Cancel edit</button>
+ </div>
+ <div class="pd-panel-body" id="pd-rule-form">
+ <div class="pd-form-group">
+ <label for="pd-rule-kind">Alert type</label>
+ <select class="pd-input" id="pd-rule-kind">
+ <option value="graduation">Graduation → AMM</option>
+ <option value="price_above">Market cap rises above</option>
+ <option value="price_below">Market cap falls below</option>
+ <option value="whale_buy">Whale buy</option>
+ <option value="new_mint">New launch by agent</option>
+ </select>
+ <div class="pd-field-hint" id="pd-rule-kind-hint"></div>
</div>
- <div class="pd-toggle-row">
- <div class="pd-toggle-label">
- Whale trade alerts
- <div class="pd-toggle-sub">
- Large buys/sells above threshold
- </div>
- </div>
- <input class="pd-toggle" type="checkbox" id="pd-alert-whale" />
+ <div class="pd-form-group" id="pd-rule-scope-group" hidden>
+ <label for="pd-rule-scope">Scope</label>
+ <select class="pd-input" id="pd-rule-scope">
+ <option value="global">All graduating tokens</option>
+ <option value="mint">A specific token</option>
+ <option value="agent">A specific agent’s tokens</option>
+ </select>
</div>
- <div class="pd-toggle-row">
- <div class="pd-toggle-label">
- Fee distribution alerts
- <div class="pd-toggle-sub">Creator fee claim events</div>
- </div>
- <input class="pd-toggle" type="checkbox" id="pd-alert-fees" />
+ <div class="pd-form-group" id="pd-rule-mint-group" hidden>
+ <label for="pd-rule-mint">Token mint</label>
+ <input class="pd-input" type="text" id="pd-rule-mint" placeholder="Token mint address" autocomplete="off" spellcheck="false" />
</div>
- <div class="pd-toggle-row">
- <div class="pd-toggle-label">
- New launch alerts
- <div class="pd-toggle-sub">New token creation events</div>
- </div>
- <input class="pd-toggle" type="checkbox" id="pd-alert-launch" />
+ <div class="pd-form-group" id="pd-rule-agent-group" hidden>
+ <label for="pd-rule-agent">Agent</label>
+ <select class="pd-input" id="pd-rule-agent">
+ <option value="">Select an agent…</option>
+ </select>
+ <div class="pd-field-hint" id="pd-rule-agent-hint">Fires when this agent launches a coin through three.ws.</div>
</div>
- </div>
- </div>
-
- <div class="pd-panel">
- <div class="pd-panel-head"><h2>Thresholds</h2></div>
- <div class="pd-panel-body">
- <div class="pd-form-group">
- <label>Whale threshold (SOL)</label>
- <input
- class="pd-input"
- type="number"
- id="pd-threshold-whale"
- value="10"
- min="0.1"
- step="0.1"
- />
+ <div class="pd-form-group" id="pd-rule-threshold-group" hidden>
+ <label for="pd-rule-threshold" id="pd-rule-threshold-label">Threshold</label>
+ <input class="pd-input" type="number" id="pd-rule-threshold" min="0" step="any" />
+ <div class="pd-field-hint" id="pd-rule-threshold-hint"></div>
</div>
<div class="pd-form-group">
- <label>Min claim alert (SOL)</label>
- <input
- class="pd-input"
- type="number"
- id="pd-threshold-claim"
- value="0.5"
- min="0.01"
- step="0.01"
- />
+ <label for="pd-rule-label">Label <span class="pd-muted">(optional)</span></label>
+ <input class="pd-input" type="text" id="pd-rule-label" maxlength="80" placeholder="Auto-named if left blank" />
</div>
- <div class="pd-form-group">
- <label>Trade alert cooldown (s)</label>
- <input
- class="pd-input"
- type="number"
- id="pd-threshold-cooldown"
- value="30"
- min="5"
- step="5"
- />
+ <div class="pd-rule-channels">
+ <div class="pd-rule-channels-title">Delivery channels</div>
+ <label class="pd-check"><input type="checkbox" id="pd-rule-inapp" checked /> <span>In-app notification</span></label>
+ <div class="pd-form-group">
+ <label for="pd-rule-webhook">Webhook URL <span class="pd-muted">(optional)</span></label>
+ <input class="pd-input" type="url" id="pd-rule-webhook" placeholder="https://your-server.com/pump-alerts" autocomplete="off" spellcheck="false" />
+ <div class="pd-field-hint">HTTPS only. Each POST is HMAC-signed with a per-rule secret revealed after you save.</div>
+ </div>
+ <div class="pd-form-group">
+ <label for="pd-rule-telegram">Telegram chat ID <span class="pd-muted">(optional)</span></label>
+ <input class="pd-input" type="text" id="pd-rule-telegram" placeholder="123456789 or @yourchannel" autocomplete="off" spellcheck="false" />
+ <div class="pd-field-hint">Message the platform bot first so it can reach you. Numeric chat id or @username.</div>
+ </div>
</div>
<div class="pd-form-group">
- <label>Webhook URL (optional)</label>
- <input
- class="pd-input"
- type="url"
- id="pd-alert-webhook"
- placeholder="https://your-server.com/pump-alerts"
- />
- <div
- style="
- font-size: 0.72rem;
- color: var(--ink-dim);
- margin-top: 0.3rem;
- "
- >
- Graduation alerts POST here even when no tab is open. Must
- be https.
- </div>
+ <label for="pd-rule-cooldown">Cooldown <span class="pd-muted">(seconds)</span></label>
+ <input class="pd-input" type="number" id="pd-rule-cooldown" min="5" max="86400" step="5" value="300" />
+ <div class="pd-field-hint">Minimum gap between deliveries for this rule. Prevents alert storms.</div>
+ </div>
+ <button class="pd-btn is-primary" id="pd-rule-save" type="button">Create alert rule</button>
+ <div class="pd-rule-signin-note" id="pd-rule-signin-note" hidden>
+ Sign in to create alerts that fire across devices. <a href="/login" class="pd-link">Sign in</a>
+ </div>
+ </div>
+ </div>
+ <div class="pd-panel pd-rules-list-panel">
+ <div class="pd-panel-head">
+ <h2>Your alert rules</h2>
+ <div class="pd-spacer"></div>
+ <button class="pd-btn pd-btn-sm" id="pd-rules-refresh" type="button">Refresh</button>
+ </div>
+ <div class="pd-panel-body no-pad">
+ <div id="pd-rules-list" class="pd-rules-list" aria-live="polite" aria-busy="false">
+ <div class="pd-empty">Loading your alert rules…</div>
</div>
- <button class="pd-btn is-primary" id="pd-save-alerts" type="button">
- Save settings
- </button>
</div>
</div>
</div>
-
<div class="pd-panel">
<div class="pd-panel-head">
<h2>Alert history</h2>
+ <div class="pd-feed-legend">Live this session + delivered server-side</div>
<div class="pd-spacer"></div>
- <button class="pd-btn pd-btn-sm" id="pd-clear-alert-feed" type="button">
- Clear
- </button>
+ <button class="pd-btn pd-btn-sm" id="pd-clear-alert-feed" type="button">Clear</button>
</div>
<div class="pd-panel-body no-pad">
<div class="pd-feed" id="pd-alert-feed" style="max-height: 360px">
<div class="pd-empty">
- <svg
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- stroke-width="1.5"
- aria-hidden="true"
- >
- <path
- d="M5 16c0-4.5 1.5-10 7-10s7 5.5 7 10M3 16h18M10 19h4"
- />
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
+ <path d="M5 16c0-4.5 1.5-10 7-10s7 5.5 7 10M3 16h18M10 19h4" />
</svg>
- <div>
- No alerts yet — enable rules above to populate this list.
- </div>
+ <div>No alerts yet — create a rule above and matches will appear here and on every device.</div>
</div>
</div>
</div>
@@ -2329,7 +2297,9 @@
? 'whale'
: evt.kind === 'claim'
? 'claim'
- : 'trade';
+ : evt.kind === 'signal'
+ ? 'signal'
+ : 'trade';
handleWsEvent({
type,
...evt,
@@ -2470,6 +2440,7 @@
complete: { cls: 'is-grad', label: 'GRAD' },
claim: { cls: 'is-claim', label: 'CLAIM' },
fee_claim: { cls: 'is-claim', label: 'CLAIM' },
+ signal: { cls: 'is-signal', label: 'SIGNAL' },
}[item.type] || { cls: '', label: item.type.toUpperCase() };
const d = item.data;
@@ -2490,6 +2461,12 @@
} else if (item.type === 'claim' || item.type === 'fee_claim') {
title = `${(Number(d.amountSol) || 0).toFixed(4)} SOL claimed`;
detail = `${d.claimType || 'fee'} · ${d.claimerWallet ? shortAddr(d.claimerWallet) : ''}`;
+ } else if (item.type === 'signal') {
+ // Agent-attributed pump.fun reputation signal from pumpfun_signals.
+ const w = Number(d.weight);
+ const weightStr = Number.isFinite(w) && w !== 0 ? ` ${w > 0 ? '+' : ''}${w}` : '';
+ title = d.summary || `${d.signal_kind || 'signal'}${weightStr}`;
+ detail = d.mint ? shortAddr(d.mint) : d.agent_name || '';
} else {
title = JSON.stringify(d).slice(0, 80);
}
diff --git a/pages/pump-live.html b/pages/pump-live.html
index 63fc4e307..ff4c10157 100644
--- a/pages/pump-live.html
+++ b/pages/pump-live.html
@@ -312,50 +312,16 @@
</div>
<script type="module">
- import { LoopOnce, LoopRepeat } from 'three';
- import { Viewer } from '/src/viewer.js';
-
// ════════════════════════════════════════════════════════════════════
- // 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.
+ // PumpFun Live Token Feed — the primary content.
+ //
+ // This module imports nothing heavy (no three.js), so it executes the instant
+ // it parses and the WebSocket feed connects immediately. The 3D agent viewer
+ // lives in a SEPARATE module below and only reacts to the `pumplive:token`
+ // event this module dispatches — the feed therefore never waits on (and never
+ // breaks with) WebGL, the GLB download, or a slow CDN.
// ════════════════════════════════════════════════════════════════════
- let viewer = null;
-
- async function initViewer() {
- try {
- const viewerEl = document.getElementById('viewer-container');
- const v = new Viewer(viewerEl, { kiosk: true });
-
- await v.load('/animations/robotexpressive.glb', '', new Map());
-
- 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;
- }
- }
-
- function playAnimation(animationName, { loop = false } = {}) {
- if (!viewer || !viewer.mixer) return;
- const clip = viewer.clips.find((c) => c.name === animationName);
- if (!clip) return;
- const action = viewer.mixer.clipAction(clip);
- action.reset();
- action.setLoop(loop ? LoopRepeat : LoopOnce, loop ? Infinity : 1);
- action.clampWhenFinished = !loop;
- action.play();
- }
-
// ════════════════════════════════════════════════════════════════════
// SOL price — drives real USD market caps. Sourced from the same-origin
// /api/pump/helius-stats endpoint (CoinGecko-backed, cached server-side).
@@ -615,8 +581,8 @@
$log.prepend(card);
while ($log.children.length > MAX_FEED_ITEMS) $log.removeChild($log.lastChild);
- // Agent reacts to the new launch.
- playAnimation('Wave', { loop: false });
+ // Notify the 3D viewer module (decoupled — it may not be loaded yet).
+ window.dispatchEvent(new CustomEvent('pumplive:token', { detail: { symbol: token.symbol || '' } }));
}
function setStatus(text, className) {
@@ -624,15 +590,58 @@
$status.className = `status ${className}`;
}
- // 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.
+ // Bootstrap. The feed opens first and never waits on anything else — the SOL
+ // price hydrates 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.
renderStats();
connect();
refreshSolPrice();
setInterval(refreshSolPrice, 60000);
- initViewer();
+</script>
+
+<script type="module">
+ // ════════════════════════════════════════════════════════════════════
+ // 3D Agent Viewer — loaded independently of the feed. It imports three.js
+ // (heavy), so isolating it here means its download never delays the live
+ // feed above. It listens for `pumplive:token` and waves on each new launch.
+ // If WebGL is unavailable (no-GPU / locked-down browser) the whole init
+ // fails soft: the feed keeps working, the avatar pane just stays empty.
+ // ════════════════════════════════════════════════════════════════════
+ import { LoopOnce, LoopRepeat } from 'three';
+ import { Viewer } from '/src/viewer.js';
+
+ let viewer = null;
+
+ function playAnimation(animationName, { loop = false } = {}) {
+ if (!viewer || !viewer.mixer) return;
+ const clip = viewer.clips.find((c) => c.name === animationName);
+ if (!clip) return;
+ const action = viewer.mixer.clipAction(clip);
+ action.reset();
+ action.setLoop(loop ? LoopRepeat : LoopOnce, loop ? Infinity : 1);
+ action.clampWhenFinished = !loop;
+ action.play();
+ }
+
+ // React to launches even while the GLB is still loading — once `viewer` is
+ // set the next event animates; events before that simply no-op.
+ window.addEventListener('pumplive:token', () => playAnimation('Wave', { loop: false }));
+
+ try {
+ const viewerEl = document.getElementById('viewer-container');
+ const v = new Viewer(viewerEl, { kiosk: true });
+ await v.load('/animations/robotexpressive.glb', '', new Map());
+
+ 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; // expose only once fully loaded so playAnimation() is safe
+ window.viewer = v;
+ } catch (err) {
+ console.warn('[pump-live] 3D viewer unavailable, feed continues without it:', err?.message || err);
+ viewer = null;
+ }
</script>
<div id="footer-container"></div>
diff --git a/public/.well-known/three-ws-agent.json b/public/.well-known/three-ws-agent.json
new file mode 100644
index 000000000..4f6604b1c
--- /dev/null
+++ b/public/.well-known/three-ws-agent.json
@@ -0,0 +1,75 @@
+{
+ "type": [
+ "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",
+ "https://three.ws/specs/3d-agent-card-v1"
+ ],
+ "name": "three.ws",
+ "symbol": "AGENT",
+ "description": "three.ws is the AI-agent layer for the open web: build, embed, monetize, and trade autonomous agents with real 3D avatars, on-chain identity, pay-per-call (x402), and pump.fun token launches. This is the platform's own agent identity — the discovery record other agents and indexers resolve to verify three.ws.",
+ "image": "https://three.ws/og-image.png",
+ "animation_url": "https://three.ws/avatars/xbot.glb",
+ "external_url": "https://three.ws",
+ "active": true,
+ "model": {
+ "uri": "https://three.ws/avatars/xbot.glb",
+ "format": "gltf-binary",
+ "sha256": "002f8d269de68e5dce3d25195caf390d1aa359bbfaae3fcf4c8dc78ec36c3ba5",
+ "sizeBytes": 2930032,
+ "polygonCount": 49112,
+ "boundingBox": {
+ "min": [-0.903, -0.003, -0.144],
+ "max": [0.903, 1.806, 0.177]
+ },
+ "license": "https://helpx.adobe.com/creative-cloud/faq/mixamo-faq.html"
+ },
+ "body": {
+ "uri": "https://three.ws/avatars/xbot.glb",
+ "format": "gltf-binary"
+ },
+ "services": [
+ { "name": "web", "endpoint": "https://three.ws/" },
+ { "name": "A2A", "endpoint": "https://three.ws/.well-known/agent-card.json", "version": "0.3.0" },
+ { "name": "MCP", "endpoint": "https://three.ws/.well-known/openapi.yaml", "version": "2025-06-18" }
+ ],
+ "x402Support": true,
+ "x402Endpoints": [
+ {
+ "url": "https://three.ws/api/mcp",
+ "method": "POST",
+ "description": "MCP tool call — 3D avatar viewer, glTF model validation/inspection/optimization, and Solana agent data",
+ "networks": ["solana", "base"],
+ "scheme": "exact",
+ "priceUsdc": "0.001"
+ }
+ ],
+ "registrations": [],
+ "supportedTrust": ["reputation", "validation"],
+ "attributes": [
+ { "trait_type": "Platform", "value": "three.ws" },
+ { "trait_type": "Standard", "value": "Metaplex Core" },
+ { "trait_type": "Schema", "value": "agent-manifest/0.1" },
+ { "trait_type": "$THREE", "value": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" }
+ ],
+ "properties": {
+ "category": "vr",
+ "files": [
+ { "uri": "https://three.ws/og-image.png", "type": "image/png" },
+ { "uri": "https://three.ws/avatars/xbot.glb", "type": "model/gltf-binary" }
+ ]
+ },
+ "platform": {
+ "name": "three.ws",
+ "url": "https://three.ws",
+ "tagline": "Give your AI a body.",
+ "x": "https://x.com/trythreews",
+ "github": "https://github.com/nirholas/three.ws"
+ },
+ "token": {
+ "symbol": "THREE",
+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",
+ "url": "https://pump.fun/coin/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"
+ },
+ "$schema": "https://three.ws/.well-known/3d-agent-card.schema.json",
+ "spec": "agent-manifest/0.1",
+ "tags": ["three.ws", "ai-agent", "platform"]
+}
diff --git a/public/changelog.json b/public/changelog.json
index d76ed0ba5..bf7315c05 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-15T02:58:27.553Z",
+ "generated_at": "2026-06-15T03:22:25.663Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "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.",
+ "link": "/pump-dashboard",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-15",
"type": "update",
@@ -38,6 +48,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "Pump Live: real token art, live market caps, and a feed that heals itself",
+ "summary": "The Pump Live showcase (three.ws/pump-live) — where a 3D agent reacts to brand-new pump.fun launches in real time — is now fully wired. Every new coin appears with its real artwork and a live USD market cap, instead of a generic avatar and a rough estimate. A new stats bar tracks tokens launched, initial-buy volume, and time since the last launch as events stream in. Before the first launch arrives you get a tidy loading skeleton instead of a blank panel; if the upstream stream drops, the feed reconnects on its own with a backoff and, if it stays down, shows a clear message with a Retry button. Token images are resolved and served through three.ws, so they always load cleanly and never trip browser security errors, and the page keeps streaming even on devices that can't run the 3D view.",
+ "link": "/pump-live",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-06-15",
"type": "update",
@@ -69,6 +90,27 @@
"feature"
]
},
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "Registered agents now carry an on-chain \"Validated\" badge",
+ "summary": "When an agent is registered on-chain, three.ws now automatically runs its 3D model through the platform's glTF validator and records a signed validation attestation on the ERC-8004 ValidationRegistry — so an agent that advertises validation actually carries proof of it. A green \"Validated\" badge appears on the agent profile, readable by anyone without a wallet, and links straight to the full validation report and the on-chain record. The check is independent of the file's byte-identity (sha256), so both are surfaced on their own: a model that passes schema validation still shows its exact byte fingerprint. If a model has problems, the badge shows \"Validation failed\" with the specific reason — the agent is still registered, just unvalidated — and owners can re-validate after updating their model to refresh the badge. Validation is best-effort and never blocks or reverts a registration.",
+ "link": "/marketplace",
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "Strategy Lab now catches broken trading strategies before they run",
+ "summary": "Validation in the Strategy Lab (three.ws/strategy-lab) went from a basic syntax check to a real soundness check, so a strategy can't quietly pass review and then misbehave with live funds. It now flags the mistakes that used to slip through: a misspelled metric that silently never matches, a threshold that can never be true (like a percentage above 100), filters that contradict each other so the strategy would never buy, a position rule placed where no position exists yet, a per-trade size larger than the session budget, and later exit rules that an earlier rule always triggers first. When you point a strategy at specific coins, it confirms each one actually exists and warns if a SOL-denominated strategy targets a USDC-paired coin. Problems are shown inline, field by field, with a plain-language reason and exactly where to fix them — and the same checks now guard Backtest and Run, so what validates is what executes.",
+ "link": "/strategy-lab",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-06-15",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 85af46587..1cafb8784 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<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>Agents can autonomously trade USDC-paired coins</title>
+ <link>https://three.ws/pump-dashboard</link>
+ <guid isPermaLink="false">2026-06-15:Agents can autonomously trade USDC-paired coins</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>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.</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,14 @@
<category>feature</category>
<description>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.</description>
</item>
+ <item>
+ <title>Pump Live: real token art, live market caps, and a feed that heals itself</title>
+ <link>https://three.ws/pump-live</link>
+ <guid isPermaLink="false">2026-06-15:Pump Live: real token art, live market caps, and a feed that heals itself</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>The Pump Live showcase (three.ws/pump-live) — where a 3D agent reacts to brand-new pump.fun launches in real time — is now fully wired. Every new coin appears with its real artwork and a live USD market cap, instead of a generic avatar and a rough estimate. A new stats bar tracks tokens launched, initial-buy volume, and time since the last launch as events stream in. Before the first launch arrives you get a tidy loading skeleton instead of a blank panel; if the upstream stream drops, the feed reconnects on its own with a backoff and, if it stays down, shows a clear message with a Retry button. Token images are resolved and served through three.ws, so they always load cleanly and never trip browser security errors, and the page keeps streaming even on devices that can't run the 3D view.</description>
+ </item>
<item>
<title>Pump Visualizer’s Trending view fixed — spheres now sized by real market cap</title>
<link>https://three.ws/pump-visualizer</link>
@@ -54,6 +70,22 @@
<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>Registered agents now carry an on-chain &quot;Validated&quot; badge</title>
+ <link>https://three.ws/marketplace</link>
+ <guid isPermaLink="false">2026-06-15:Registered agents now carry an on-chain &quot;Validated&quot; badge</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>When an agent is registered on-chain, three.ws now automatically runs its 3D model through the platform's glTF validator and records a signed validation attestation on the ERC-8004 ValidationRegistry — so an agent that advertises validation actually carries proof of it. A green &quot;Validated&quot; badge appears on the agent profile, readable by anyone without a wallet, and links straight to the full validation report and the on-chain record. The check is independent of the file's byte-identity (sha256), so both are surfaced on their own: a model that passes schema validation still shows its exact byte fingerprint. If a model has problems, the badge shows &quot;Validation failed&quot; with the specific reason — the agent is still registered, just unvalidated — and owners can re-validate after updating their model to refresh the badge. Validation is best-effort and never blocks or reverts a registration.</description>
+ </item>
+ <item>
+ <title>Strategy Lab now catches broken trading strategies before they run</title>
+ <link>https://three.ws/strategy-lab</link>
+ <guid isPermaLink="false">2026-06-15:Strategy Lab now catches broken trading strategies before they run</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Validation in the Strategy Lab (three.ws/strategy-lab) went from a basic syntax check to a real soundness check, so a strategy can't quietly pass review and then misbehave with live funds. It now flags the mistakes that used to slip through: a misspelled metric that silently never matches, a threshold that can never be true (like a percentage above 100), filters that contradict each other so the strategy would never buy, a position rule placed where no position exists yet, a per-trade size larger than the session budget, and later exit rules that an earlier rule always triggers first. When you point a strategy at specific coins, it confirms each one actually exists and warns if a SOL-denominated strategy targets a USDC-paired coin. Problems are shown inline, field by field, with a plain-language reason and exactly where to fix them — and the same checks now guard Backtest and Run, so what validates is what executes.</description>
+ </item>
<item>
<title>The pump.fun graduations feed stays fresh around the clock</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 2bb049070..84709f3f5 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-15T02:58:27.488Z",
+ "generated_at": "2026-06-15T03:22:25.455Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/pump-dashboard.css b/public/pump-dashboard.css
index f981a213c..be917f7cc 100644
--- a/public/pump-dashboard.css
+++ b/public/pump-dashboard.css
@@ -496,6 +496,7 @@ html.pump-dashboard-page body {
.pd-tag.is-whale { background: rgba(251, 191, 36, 0.14); border-color: rgba(251, 191, 36, 0.3); color: var(--warn); }
.pd-tag.is-grad { background: var(--accent-soft); border-color: var(--stroke-strong); color: var(--accent); }
.pd-tag.is-claim { background: rgba(74, 222, 128, 0.14); border-color: rgba(74, 222, 128, 0.3); color: var(--success); }
+.pd-tag.is-signal { background: rgba(129, 140, 248, 0.14); border-color: rgba(129, 140, 248, 0.32); color: #a5b4fc; }
/* ── Live feed ───────────────────────────────────────────── */
diff --git a/public/style.css b/public/style.css
index 85b5e12d3..c77c2de8f 100644
--- a/public/style.css
+++ b/public/style.css
@@ -8684,37 +8684,16 @@ textarea.erc8004-code {
margin: 0;
line-height: 1.4;
}
-.pumpfun-stats {
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 10px;
-}
-.pumpfun-stat {
+/* Live market readout — host for the shared coin-status `chip` widget. The
+ widget renders symbol · price · market cap · graduation % from a single
+ /api/pump/coin fetch, replacing the card's former bespoke stat tiles. */
+.pumpfun-coin-status-mount {
display: flex;
- flex-direction: column;
- gap: 2px;
}
-.pumpfun-stat-label {
- font-size: 10.5px;
- text-transform: uppercase;
- letter-spacing: 0.08em;
- opacity: 0.55;
-}
-.pumpfun-stat-value {
- font-size: 15px;
- font-weight: 600;
- font-variant-numeric: tabular-nums;
-}
-.pumpfun-progress {
- height: 4px;
- background: rgba(255, 255, 255, 0.08);
- border-radius: var(--radius-pill);
- overflow: hidden;
-}
-.pumpfun-progress-bar {
- height: 100%;
- background: linear-gradient(90deg, #b27dff, #6ce0c8);
- transition: width .6s ease;
+.pumpfun-coin-status-mount .csc-chip {
+ flex-wrap: wrap;
+ gap: 8px 10px;
+ font-size: 13px;
}
.pumpfun-card-mint {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
@@ -8762,7 +8741,6 @@ textarea.erc8004-code {
}
.pumpfun-card-foot:hover { opacity: 0.85; }
@media (prefers-reduced-motion: reduce) {
- .pumpfun-progress-bar { transition: none; }
.pumpfun-card--skeleton { animation: none; }
}
@@ -8923,7 +8901,6 @@ textarea.erc8004-code {
.pumpfun-card-actions { flex-wrap: wrap; }
.pumpfun-card-actions .pumpfun-btn { flex: 1 0 calc(50% - 3px); }
.pumpfun-card-actions .pumpfun-btn--ghost { flex: 1 0 100%; }
- .pumpfun-stats { grid-template-columns: 1fr; gap: 6px; }
.pumpfun-trade-label { grid-template-columns: 1fr; }
.pumpfun-toasts {
left: 14px;
diff --git a/scripts/.pumplive-smoke.mjs b/scripts/.pumplive-smoke.mjs
new file mode 100644
index 000000000..83b5e75f4
--- /dev/null
+++ b/scripts/.pumplive-smoke.mjs
@@ -0,0 +1,84 @@
+import { chromium } from 'playwright';
+
+const BASE = 'http://localhost:3939';
+const results = [];
+const ok = (n, c, d='') => { results.push({ n, c, d }); console.log(`${c ? 'PASS' : 'FAIL'} ${n}${d ? ' — ' + d : ''}`); };
+
+const browser = await chromium.launch();
+const ctx = await browser.newContext();
+const page = await ctx.newPage();
+
+const consoleErrors = [];
+const pageErrors = [];
+page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()); });
+page.on('pageerror', (e) => pageErrors.push(e.message));
+
+// 'commit' (not 'domcontentloaded'): DCL waits on the viewer module's three.js
+// download, but the feed module has no heavy imports and runs before then — so
+// the feed must be queryable well before DCL. This is the decoupling under test.
+await page.goto(`${BASE}/pump-live`, { waitUntil: 'commit', timeout: 30000 });
+await page.waitForSelector('#status', { timeout: 15000 });
+
+// 1. Empty/skeleton state present quickly (feed must NOT wait on the 3D viewer)
+await page.waitForSelector('.skeleton-card', { timeout: 8000 }).catch(() => {});
+const skeletonCount = await page.locator('.skeleton-card').count();
+const hint = await page.locator('#feed-empty-hint').textContent().catch(() => '');
+ok('Empty state: skeleton renders immediately (feed not gated on viewer)', skeletonCount >= 1, `${skeletonCount} skeletons, hint="${(hint||'').trim()}"`);
+
+// 2. WS connects → status becomes Live
+await page.waitForFunction(() => document.getElementById('status')?.classList.contains('connected'), { timeout: 25000 }).catch(() => {});
+const statusText = await page.locator('#status').textContent();
+ok('WebSocket connects (status = Live)', /live/i.test(statusText), `status="${statusText.trim()}"`);
+
+// 3. At least one real token card within 60s
+await page.waitForSelector('.token-card', { timeout: 60000 }).catch(() => {});
+const cardCount = await page.locator('.token-card').count();
+ok('Token card(s) render from live feed', cardCount >= 1, `${cardCount} cards`);
+
+// 4. Card data integrity — no undefined/null/[object Object]
+const first = page.locator('.token-card').first();
+const name = (await first.locator('.token-name').textContent().catch(() => '') || '').trim();
+const mcap = (await first.locator('.token-mcap').textContent().catch(() => '') || '').trim();
+const feedText = await page.locator('#feed').textContent();
+const dirty = /undefined|\bnull\b|\[object Object\]/.test(feedText);
+ok('No undefined/null/[object Object] in feed', !dirty, dirty ? 'FOUND dirty text' : `e.g. name="${name}", "${mcap}"`);
+ok('Card has a real name', name.length > 0 && name !== 'undefined');
+
+// 5. Stats increment from real events
+const launched = parseInt((await page.locator('#stat-launched').textContent()).replace(/\D/g, '') || '0', 10);
+const volume = (await page.locator('#stat-volume').textContent()).trim();
+const age = (await page.locator('#stat-age').textContent()).trim();
+ok('Stat: tokens launched > 0', launched > 0, `launched=${launched}`);
+ok('Stat: volume populated', volume.length > 0 && volume !== '$0', `volume=${volume}`);
+ok('Stat: last-launch populated', age !== '—', `age=${age}`);
+
+// 6. Mobile layout stacks vertically at 375px
+await page.setViewportSize({ width: 375, height: 800 });
+await page.waitForTimeout(400);
+const vb = await page.locator('#viewer-container').boundingBox();
+const fb = await page.locator('#feed-container').boundingBox();
+const stacked = vb && fb && (fb.y >= vb.y + vb.height - 5 || vb.y >= fb.y + fb.height - 5);
+const sameRow = vb && fb && Math.abs(vb.y - fb.y) < 20 && vb.x !== fb.x;
+ok('Mobile (375px): panels stack vertically', !!stacked && !sameRow, `viewer y=${vb?.y?.toFixed(0)} h=${vb?.height?.toFixed(0)}, feed y=${fb?.y?.toFixed(0)}`);
+await page.setViewportSize({ width: 1280, height: 800 });
+
+// 7. Reconnect via real network drop → backoff → recovery
+await ctx.setOffline(true);
+const reconnecting = await page.waitForFunction(() => /reconnect|disconnect|offline/i.test(document.getElementById('status')?.textContent || ''), { timeout: 15000 }).then(() => true).catch(() => false);
+const reconnStatus = (await page.locator('#status').textContent()).trim();
+ok('Reconnect: status enters backoff after drop', reconnecting, `status="${reconnStatus}"`);
+await ctx.setOffline(false);
+const recovered = await page.waitForFunction(() => document.getElementById('status')?.classList.contains('connected'), { timeout: 30000 }).then(() => true).catch(() => false);
+ok('Reconnect: recovers to Live after network returns', recovered, `status="${(await page.locator('#status').textContent()).trim()}"`);
+
+// 8. Console cleanliness (ignore dev-only noise: vite HMR socket, vercel insights, network-abort from the offline test)
+const realConsoleErrors = consoleErrors.filter((e) =>
+ !/websocket|pumpportal|failed to fetch|net::|ERR_INTERNET_DISCONNECTED|_vercel\/insights|\[vite\]|status of 4\d\d|status of 5\d\d/i.test(e));
+const realPageErrors = pageErrors.filter((e) => !/WebSocket closed without opened/i.test(e));
+ok('No unexpected console errors', realConsoleErrors.length === 0, realConsoleErrors.slice(0, 3).join(' | '));
+ok('No uncaught page errors', realPageErrors.length === 0, realPageErrors.slice(0, 3).join(' | '));
+
+await browser.close();
+const failed = results.filter((r) => !r.c);
+console.log(`\n=== ${results.length - failed.length}/${results.length} checks passed ===`);
+process.exit(failed.length ? 1 : 0);
diff --git a/scripts/onchain-smoke.mjs b/scripts/onchain-smoke.mjs
new file mode 100644
index 000000000..ad10bc5ce
--- /dev/null
+++ b/scripts/onchain-smoke.mjs
@@ -0,0 +1,907 @@
+#!/usr/bin/env node
+/**
+ * On-chain end-to-end smoke harness — the standing verification net for the
+ * three.ws on-chain stack (EVM ERC-8004 identity/validation/reputation + x402,
+ * Solana pump.fun launch/trade + agent_invocation).
+ *
+ * Each subsystem is unit-tested in isolation; nothing else exercises the whole
+ * agent lifecycle in one pass. A regression in the seam between two systems
+ * (a registry address drift, a stale ABI, a broken pin endpoint, an unfunded
+ * relayer, an undeployed program) only shows up in production. This script runs
+ * the full path against testnet/devnet and exits non-zero on any break.
+ *
+ * Design principles:
+ * - Read-only steps run everywhere (CI included) with no secrets and stay green.
+ * - Value steps (anything that broadcasts a transaction) SKIP — not FAIL — with
+ * a precise reason when their funded signer / deployment / credential is
+ * absent. Provide the credentials and the same step turns PASS/FAIL.
+ * - Testnet/devnet only by default. `--mainnet-readonly` adds read-only mainnet
+ * checks (parity, bytecode) and NEVER broadcasts value.
+ * - Synthetic signers/mints only. The only coin this platform references is
+ * $THREE; this harness never touches a real third-party token or wallet.
+ * - Real endpoints/SDKs are reused; nothing here is mocked.
+ *
+ * Usage:
+ * node scripts/onchain-smoke.mjs # all 8 steps (read-only subset runs, value steps SKIP)
+ * node scripts/onchain-smoke.mjs --only=parity # one step by key
+ * node scripts/onchain-smoke.mjs --only=1,2,3 # several by number
+ * node scripts/onchain-smoke.mjs --list # list step keys
+ * node scripts/onchain-smoke.mjs --mainnet-readonly
+ * node scripts/onchain-smoke.mjs --json # machine-readable summary on stdout
+ * node --env-file=.env scripts/onchain-smoke.mjs # load credentials from .env (Node 20+)
+ *
+ * Credentials (all optional — absence ⇒ the dependent step SKIPs):
+ * SMOKE_EVM_PRIVATE_KEY funded Base-Sepolia signer (steps 2,3,4 — must be an allow-listed validator for step 3)
+ * SMOKE_EVM_PRIVATE_KEY_2 second funded signer for the reputation feedback (step 4)
+ * SMOKE_EVM_CHAIN_ID EVM testnet chainId (default 84532 / Base Sepolia)
+ * SMOKE_AGENT_ID reuse an existing agentId for steps 3/4 without re-registering
+ * SMOKE_PIN_BASE_URL deployed API origin for /api/erc8004/pin (else GLB+card use self-contained data: URIs)
+ * SMOKE_AUTH_COOKIE session cookie for pin + pump endpoints (these require a logged-in session)
+ * SMOKE_BASE_URL deployed API origin for the Solana + x402 HTTP steps
+ * SMOKE_SOLANA_PRIVATE_KEY funded devnet signer (bs58) for pump launch/trade + agent_invocation
+ * SMOKE_X402_NAME a resolvable @handle / .sol name for the x402 pay-by-name prep (step 7)
+ * SOLANA_RPC_URL_DEVNET devnet RPC (default https://api.devnet.solana.com)
+ *
+ * Exit code: 0 when no step FAILED (SKIP is not a failure), 1 otherwise.
+ */
+
+import { createHash } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+import { existsSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+
+import { Wallet, Contract } from 'ethers';
+import Ajv2020 from 'ajv/dist/2020.js';
+import addFormats from 'ajv-formats';
+
+import {
+ IDENTITY_REGISTRY_ABI,
+ REPUTATION_REGISTRY_ABI,
+ VALIDATION_REGISTRY_ABI,
+ REGISTRY_DEPLOYMENTS as SDK_DEPLOYMENTS,
+ agentRegistryId,
+} from '../sdk/src/erc8004/abi.js';
+import { REGISTRY_DEPLOYMENTS as SRC_DEPLOYMENTS } from '../src/erc8004/abi.js';
+import { CHAIN_BY_ID } from '../api/_lib/erc8004-chains.js';
+import { evmFallbackProvider } from '../api/_lib/evm/rpc.js';
+import { buildRegistrationJSON } from '../src/erc8004/registration-json.js';
+import { normalizeGatewayURL } from '../src/ipfs.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, '..');
+
+// Anchor's default placeholder — the agent_invocation program is "deployed" only
+// once this is replaced with a real on-chain id (task 03).
+const AGENT_INVOCATION_PLACEHOLDER = 'Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS';
+
+const ERC8004_TYPE = 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1';
+const THREEWS_CARD_TYPE = 'https://three.ws/.well-known/3d-agent-card.schema.json';
+const VALIDATION_KIND = 'glb-schema';
+
+// Live-bytecode probe targets for the parity step (Base mainnet + Base Sepolia).
+const BYTECODE_PROBE_CHAINS = [8453, 84532];
+
+// ---------------------------------------------------------------------------
+// Output formatting
+// ---------------------------------------------------------------------------
+
+const COLOR = process.stdout.isTTY && !process.env.NO_COLOR;
+const c = (code, s) => (COLOR ? `\x1b[${code}m${s}\x1b[0m` : s);
+const dim = (s) => c('2', s);
+const bold = (s) => c('1', s);
+const green = (s) => c('32', s);
+const red = (s) => c('31', s);
+const yellow = (s) => c('33', s);
+
+const STATUS = {
+ PASS: { label: 'PASS', icon: '✓', paint: green },
+ FAIL: { label: 'FAIL', icon: '✗', paint: red },
+ SKIP: { label: 'SKIP', icon: '○', paint: yellow },
+};
+
+const pass = (detail, extra) => ({ status: 'PASS', detail, extra });
+const fail = (detail, extra) => ({ status: 'FAIL', detail, extra });
+const skip = (detail, extra) => ({ status: 'SKIP', detail, extra });
+
+function fmtMs(ms) {
+ if (ms < 1000) return `${ms}ms`;
+ return `${(ms / 1000).toFixed(1)}s`;
+}
+
+// ---------------------------------------------------------------------------
+// Synthetic fixtures (real, valid bytes — never mocked)
+// ---------------------------------------------------------------------------
+
+/** A real, minimal, structurally-valid binary glTF (GLB) container. */
+function buildSyntheticGlb() {
+ const gltf = {
+ asset: { version: '2.0', generator: 'three.ws onchain-smoke synthetic' },
+ scene: 0,
+ scenes: [{ name: 'smoke' }],
+ nodes: [],
+ };
+ const jsonBuf = Buffer.from(JSON.stringify(gltf), 'utf8');
+ const pad = (4 - (jsonBuf.length % 4)) % 4;
+ const jsonChunk = Buffer.concat([jsonBuf, Buffer.alloc(pad, 0x20)]);
+
+ const header = Buffer.alloc(12);
+ header.writeUInt32LE(0x46546c67, 0); // magic 'glTF'
+ header.writeUInt32LE(2, 4); // version
+ header.writeUInt32LE(12 + 8 + jsonChunk.length, 8); // total length
+
+ const chunkHeader = Buffer.alloc(8);
+ chunkHeader.writeUInt32LE(jsonChunk.length, 0);
+ chunkHeader.writeUInt32LE(0x4e4f534a, 4); // chunk type 'JSON'
+
+ return Buffer.concat([header, chunkHeader, jsonChunk]);
+}
+
+const sha256hex = (buf) => createHash('sha256').update(buf).digest('hex');
+
+/** Reject after `ms` so a hung RPC/HTTP call degrades instead of blocking the run. */
+function withTimeout(promise, ms, label) {
+ let timer;
+ const guard = new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
+ });
+ return Promise.race([promise, guard]).finally(() => clearTimeout(timer));
+}
+
+// ---------------------------------------------------------------------------
+// URI fetch (data: / ipfs:// / http(s))
+// ---------------------------------------------------------------------------
+
+async function fetchUriBytes(uri) {
+ if (uri.startsWith('data:')) {
+ const comma = uri.indexOf(',');
+ const header = uri.slice(5, comma);
+ const payload = uri.slice(comma + 1);
+ if (/;base64/i.test(header)) return Buffer.from(payload, 'base64');
+ return Buffer.from(decodeURIComponent(payload), 'utf8');
+ }
+ const url = uri.startsWith('ipfs://') ? normalizeGatewayURL(uri, 0) : uri;
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`fetch ${url} -> ${res.status}`);
+ return Buffer.from(await res.arrayBuffer());
+}
+
+const fetchUriJson = async (uri) => JSON.parse((await fetchUriBytes(uri)).toString('utf8'));
+
+/**
+ * Pin bytes to permanent storage. Uses the real /api/erc8004/pin endpoint when a
+ * session is configured; otherwise falls back to a self-contained data: URI built
+ * from the real bytes (content-addressable by the same sha256 we assert on-chain).
+ */
+async function pinBytes(buf, contentType, cfg) {
+ if (cfg.pinBaseUrl && cfg.authCookie) {
+ const res = await fetch(`${cfg.pinBaseUrl}/api/erc8004/pin`, {
+ method: 'POST',
+ headers: { 'content-type': contentType, cookie: cfg.authCookie },
+ body: buf,
+ });
+ if (!res.ok) throw new Error(`pin ${res.status}: ${(await res.text()).slice(0, 200)}`);
+ const data = await res.json();
+ const url = data.url || data.uri;
+ if (!url) throw new Error('pin endpoint returned no url');
+ return url;
+ }
+ return `data:${contentType};base64,${buf.toString('base64')}`;
+}
+
+async function httpJson(method, url, { cookie, body } = {}) {
+ const headers = {};
+ if (cookie) headers.cookie = cookie;
+ if (body !== undefined) headers['content-type'] = 'application/json';
+ const res = await fetch(url, {
+ method,
+ headers,
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ });
+ const text = await res.text();
+ let json = null;
+ try {
+ json = text ? JSON.parse(text) : null;
+ } catch {
+ /* non-JSON body surfaced verbatim below */
+ }
+ return { ok: res.ok, status: res.status, json, text };
+}
+
+// ---------------------------------------------------------------------------
+// Card schema validation
+// ---------------------------------------------------------------------------
+
+let _validateCard = null;
+async function getCardValidator() {
+ if (_validateCard) return _validateCard;
+ const schema = JSON.parse(
+ await readFile(resolve(ROOT, 'public/.well-known/3d-agent-card.schema.json'), 'utf8'),
+ );
+ const ajv = new Ajv2020({ strict: false, allErrors: true });
+ addFormats(ajv);
+ _validateCard = ajv.compile(schema);
+ return _validateCard;
+}
+
+// ---------------------------------------------------------------------------
+// Step 1 — Address parity
+// ---------------------------------------------------------------------------
+
+const normAddr = (a) => (a && String(a).trim() ? String(a).trim().toLowerCase() : null);
+
+/** Compare the three hand-maintained address sources; return a list of problems. */
+function inlineParityProblems() {
+ const problems = [];
+ const ids = new Set(
+ [...Object.keys(SRC_DEPLOYMENTS), ...Object.keys(SDK_DEPLOYMENTS)].map(Number),
+ );
+ for (const id of ids) {
+ const src = SRC_DEPLOYMENTS[id];
+ const sdk = SDK_DEPLOYMENTS[id];
+ if (!src || !sdk) {
+ problems.push(`chain ${id}: present only in ${src ? 'src/erc8004/abi.js' : 'sdk/src/erc8004/abi.js'}`);
+ continue;
+ }
+ for (const slot of ['identityRegistry', 'reputationRegistry', 'validationRegistry']) {
+ const a = normAddr(src[slot]);
+ const b = normAddr(sdk[slot]);
+ if (a !== b) problems.push(`chain ${id} ${slot}: src=${a} sdk=${b}`);
+ }
+ // The api server mirror carries identity (`registry`) + validation only.
+ const api = CHAIN_BY_ID[id];
+ if (api) {
+ if (normAddr(api.registry) !== normAddr(src.identityRegistry)) {
+ problems.push(
+ `chain ${id} identityRegistry: api=${normAddr(api.registry)} src=${normAddr(src.identityRegistry)}`,
+ );
+ }
+ if (normAddr(api.validationRegistry) !== normAddr(src.validationRegistry)) {
+ problems.push(
+ `chain ${id} validationRegistry: api=${normAddr(api.validationRegistry)} src=${normAddr(src.validationRegistry)}`,
+ );
+ }
+ }
+ }
+ return problems;
+}
+
+async function stepParity(cfg) {
+ // Prefer the dedicated task-05 guard when present (it also owns the canonical
+ // DEPLOYMENTS.md provenance check); fall back to the inline comparison so this
+ // step is meaningful before task 05 lands.
+ const parityScript = resolve(ROOT, 'scripts/verify-onchain-parity.mjs');
+ let source = 'inline';
+ if (existsSync(parityScript)) {
+ const r = spawnSync(process.execPath, [parityScript], { encoding: 'utf8' });
+ if (r.status !== 0) {
+ return fail(
+ `verify-onchain-parity.mjs exited ${r.status}: ${(r.stderr || r.stdout || '').trim().split('\n').slice(-3).join(' | ')}`,
+ );
+ }
+ source = 'verify-onchain-parity.mjs';
+ } else {
+ const problems = inlineParityProblems();
+ if (problems.length) {
+ return fail(`${problems.length} address mismatch(es): ${problems.slice(0, 4).join('; ')}`);
+ }
+ }
+
+ // Live bytecode probe (read-only) on Base mainnet + Base Sepolia. A null
+ // address is skipped; an empty-code result at a configured address is a real
+ // FAIL; a network error degrades to a warning so CI without RPC stays green.
+ const probes = [];
+ for (const id of BYTECODE_PROBE_CHAINS) {
+ const dep = SDK_DEPLOYMENTS[id];
+ const addr = dep && dep.identityRegistry;
+ if (!addr) continue;
+ try {
+ const provider = await evmFallbackProvider(id);
+ const code = await withTimeout(provider.getCode(addr), 8000, `getCode chain ${id}`);
+ if (!code || code === '0x') {
+ return fail(`chain ${id}: identityRegistry ${addr} has no bytecode`);
+ }
+ probes.push(`${id}:code✓`);
+ } catch (err) {
+ probes.push(`${id}:rpc-skip(${(err.message || 'network').slice(0, 24)})`);
+ }
+ }
+ const probeNote = probes.length ? ` · bytecode ${probes.join(' ')}` : '';
+ return pass(`address parity OK via ${source}${probeNote}`);
+}
+
+// ---------------------------------------------------------------------------
+// Step 2 — EVM register (Base Sepolia)
+// ---------------------------------------------------------------------------
+
+async function stepEvmRegister(cfg, ctx) {
+ const chainId = cfg.evmChainId;
+ const dep = SDK_DEPLOYMENTS[chainId];
+ if (!dep || !dep.identityRegistry) {
+ return skip(`no Identity Registry configured for chain ${chainId}`);
+ }
+ if (!cfg.evmKey) {
+ return skip('no funded EVM signer — set SMOKE_EVM_PRIVATE_KEY (Base-Sepolia)');
+ }
+
+ const provider = await evmFallbackProvider(chainId);
+ const signer = new Wallet(cfg.evmKey, provider);
+ const balance = await provider.getBalance(signer.address);
+ if (balance === 0n) {
+ return skip(`signer ${signer.address} has 0 balance on chain ${chainId} — fund it from a faucet`);
+ }
+
+ const registry = new Contract(dep.identityRegistry, IDENTITY_REGISTRY_ABI, signer);
+
+ // 1. Synthetic GLB + its sha256 (the independent byte-identity proof).
+ const glb = buildSyntheticGlb();
+ const glbSha = sha256hex(glb);
+ const glbUrl = await pinBytes(glb, 'model/gltf-binary', cfg);
+
+ // 2. register(seedURI) → Registered event → agentId.
+ const tx = await registry['register(string)'](glbUrl);
+ const receipt = await tx.wait();
+ const registered = receipt.logs
+ .map((l) => {
+ try {
+ return registry.interface.parseLog(l);
+ } catch {
+ return null;
+ }
+ })
+ .find((e) => e && e.name === 'Registered');
+ if (!registered) return fail('register() mined but no Registered event found');
+ const agentId = Number(registered.args.agentId);
+
+ // 3. Build the 3D Agent Card (ERC-8004 base + the v1 `model` superset) and pin.
+ const base = buildRegistrationJSON({
+ name: 'three.ws smoke agent',
+ description: 'Synthetic agent minted by scripts/onchain-smoke.mjs against testnet. Not a product launch.',
+ glbUrl,
+ imageUrl: '',
+ agentId,
+ chainId,
+ registryAddr: dep.identityRegistry,
+ services: [],
+ x402Support: true,
+ });
+ const card = {
+ ...base,
+ type: [ERC8004_TYPE, THREEWS_CARD_TYPE],
+ model: {
+ uri: glbUrl,
+ format: 'gltf-binary',
+ sha256: glbSha,
+ sizeBytes: glb.length,
+ },
+ };
+ const cardUri = await pinBytes(Buffer.from(JSON.stringify(card), 'utf8'), 'application/json', cfg);
+
+ // 4. setAgentURI → point the on-chain pointer at the final card.
+ await (await registry.setAgentURI(agentId, cardUri)).wait();
+
+ // 5. tokenURI round-trip + schema validation + sha256 byte-identity.
+ const onchainUri = await registry.tokenURI(agentId);
+ if (onchainUri !== cardUri) return fail('tokenURI did not round-trip to the pinned card URI');
+
+ const fetched = await fetchUriJson(onchainUri);
+ const validate = await getCardValidator();
+ if (!validate(fetched)) {
+ const msg = (validate.errors || [])
+ .slice(0, 3)
+ .map((e) => `${e.instancePath || '/'} ${e.message}`)
+ .join('; ');
+ return fail(`card failed 3d-agent-card.schema.json: ${msg}`);
+ }
+ if (fetched.model.sha256 !== glbSha) {
+ return fail(`card model.sha256 ${fetched.model.sha256} != GLB sha256 ${glbSha}`);
+ }
+ const modelBytes = await fetchUriBytes(fetched.model.uri);
+ if (sha256hex(modelBytes) !== glbSha) {
+ return fail('re-fetched model bytes do not hash to model.sha256');
+ }
+
+ // Hand the registered identity to steps 3 + 4.
+ ctx.evm = { chainId, agentId, registryAddr: dep.identityRegistry, signer, provider, glbSha };
+ return pass(`agentId=${agentId} · tokenURI round-trips · card valid · model.sha256 matches`, {
+ agentId,
+ registerTx: tx.hash,
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Step 3 — EVM validation attestation
+// ---------------------------------------------------------------------------
+
+function buildValidationReport(glbSha) {
+ // The canonical glb-schema report shape (see src/erc8004/validation-report.js):
+ // zero errors ⇒ passing. Deterministic key order keeps hashReport reproducible.
+ return {
+ kind: VALIDATION_KIND,
+ spec: 'erc-8004/validation/glb-schema@1',
+ validatedAt: new Date().toISOString(),
+ uri: 'synthetic://onchain-smoke.glb',
+ validator: { name: 'three.ws onchain-smoke', tool: 'scripts/onchain-smoke.mjs' },
+ byteCheck: { sha256: glbSha, byteLength: null },
+ issues: { numErrors: 0, numWarnings: 0, numInfos: 0, numHints: 0, messages: [] },
+ };
+}
+
+async function stepEvmValidation(cfg, ctx) {
+ const chainId = ctx.evm?.chainId ?? cfg.evmChainId;
+ const dep = SDK_DEPLOYMENTS[chainId];
+ if (!dep || !dep.validationRegistry) {
+ return skip(`no Validation Registry deployed on chain ${chainId}`);
+ }
+ const agentId = ctx.evm?.agentId ?? cfg.agentId;
+ if (agentId == null) {
+ return skip('no agentId — run step 2 in the same invocation or set SMOKE_AGENT_ID');
+ }
+ if (!cfg.evmKey) {
+ return skip('no funded validator signer — set SMOKE_EVM_PRIVATE_KEY (must be allow-listed on the registry)');
+ }
+
+ const provider = ctx.evm?.provider ?? (await evmFallbackProvider(chainId));
+ const signer = ctx.evm?.signer ?? new Wallet(cfg.evmKey, provider);
+ const registry = new Contract(dep.validationRegistry, VALIDATION_REGISTRY_ABI, signer);
+
+ const glbSha = ctx.evm?.glbSha ?? sha256hex(buildSyntheticGlb());
+ const report = buildValidationReport(glbSha);
+ const { keccak256, toUtf8Bytes } = await import('ethers');
+ const proofHash = keccak256(toUtf8Bytes(JSON.stringify(report)));
+ const passed = true;
+
+ // Guard: recordValidation reverts for non-allow-listed senders (NotValidator).
+ let countBefore;
+ try {
+ countBefore = await registry.getValidationCount(agentId);
+ } catch (err) {
+ return fail(`getValidationCount read failed: ${err.shortMessage || err.message}`);
+ }
+
+ let tx;
+ try {
+ tx = await registry.recordValidation(agentId, passed, proofHash, '', VALIDATION_KIND);
+ await tx.wait();
+ } catch (err) {
+ const reason = err.shortMessage || err.reason || err.message || 'revert';
+ if (/NotValidator|not a validator|0x[0-9a-f]*/i.test(reason)) {
+ return skip(`signer ${signer.address} is not an allow-listed validator (${reason})`);
+ }
+ return fail(`recordValidation failed: ${reason}`);
+ }
+
+ // Read it back via getLatestByKind (the canonical query), with a count-delta
+ // fallback if an older deployment lacks that view.
+ let readback;
+ try {
+ const latest = await registry.getLatestByKind(agentId, VALIDATION_KIND);
+ if (latest.proofHash !== proofHash) {
+ return fail(`getLatestByKind proofHash ${latest.proofHash} != recorded ${proofHash}`);
+ }
+ if (latest.passed !== passed) return fail('getLatestByKind passed flag mismatch');
+ readback = 'getLatestByKind';
+ } catch {
+ const countAfter = await registry.getValidationCount(agentId);
+ if (countAfter <= countBefore) {
+ return fail(`validation count did not increment (${countBefore} -> ${countAfter})`);
+ }
+ readback = 'getValidationCount';
+ }
+
+ return pass(`attestation recorded for agentId=${agentId} · read back via ${readback}`, {
+ validationTx: tx.hash,
+ proofHash,
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Step 4 — EVM reputation feedback
+// ---------------------------------------------------------------------------
+
+async function stepEvmReputation(cfg, ctx) {
+ const chainId = ctx.evm?.chainId ?? cfg.evmChainId;
+ const dep = SDK_DEPLOYMENTS[chainId];
+ if (!dep || !dep.reputationRegistry) {
+ return skip(`no Reputation Registry deployed on chain ${chainId}`);
+ }
+ const agentId = ctx.evm?.agentId ?? cfg.agentId;
+ if (agentId == null) {
+ return skip('no agentId — run step 2 in the same invocation or set SMOKE_AGENT_ID');
+ }
+ // Feedback must come from a DIFFERENT signer than the agent owner (a registry
+ // typically rejects self-review), so step 4 needs a dedicated second signer.
+ if (!cfg.evmKey2) {
+ return skip('no second funded signer — set SMOKE_EVM_PRIVATE_KEY_2 to submit feedback');
+ }
+
+ const provider = ctx.evm?.provider ?? (await evmFallbackProvider(chainId));
+ const reviewer = new Wallet(cfg.evmKey2, provider);
+ if ((await provider.getBalance(reviewer.address)) === 0n) {
+ return skip(`reviewer ${reviewer.address} has 0 balance on chain ${chainId} — fund it`);
+ }
+
+ const reader = new Contract(dep.reputationRegistry, REPUTATION_REGISTRY_ABI, provider);
+ let countBefore;
+ try {
+ [, countBefore] = await reader.getReputation(agentId);
+ } catch (err) {
+ return fail(`getReputation read failed: ${err.shortMessage || err.message}`);
+ }
+
+ const writer = new Contract(dep.reputationRegistry, REPUTATION_REGISTRY_ABI, reviewer);
+ let tx;
+ try {
+ tx = await writer.submitFeedback(agentId, 5, 'onchain-smoke synthetic feedback');
+ await tx.wait();
+ } catch (err) {
+ const reason = err.shortMessage || err.reason || err.message || 'revert';
+ if (/self|already|reviewed/i.test(reason)) {
+ return skip(`feedback rejected (${reason}) — use a fresh reviewer signer`);
+ }
+ return fail(`submitFeedback failed: ${reason}`);
+ }
+
+ const [, countAfter] = await reader.getReputation(agentId);
+ if (countAfter <= countBefore) {
+ return fail(`reputation count did not increment (${countBefore} -> ${countAfter})`);
+ }
+ return pass(`feedback from ${reviewer.address.slice(0, 10)}… · count ${countBefore} -> ${countAfter}`, {
+ reputationTx: tx.hash,
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Solana helpers (lazy-loaded so the EVM/read-only path needs no Solana deps)
+// ---------------------------------------------------------------------------
+
+async function loadSolana() {
+ const web3 = await import('@solana/web3.js');
+ const bs58 = (await import('bs58')).default;
+ return { ...web3, bs58 };
+}
+
+function solanaKeypairFrom(sol, bs58Secret) {
+ const { Keypair, bs58 } = sol;
+ const bytes = bs58.decode(bs58Secret);
+ return Keypair.fromSecretKey(bytes);
+}
+
+// ---------------------------------------------------------------------------
+// Step 5 — Solana launch (devnet)
+// ---------------------------------------------------------------------------
+
+async function stepSolanaLaunch(cfg, ctx) {
+ const missing = [];
+ if (!cfg.baseUrl) missing.push('SMOKE_BASE_URL');
+ if (!cfg.authCookie) missing.push('SMOKE_AUTH_COOKIE');
+ if (!cfg.solanaKey) missing.push('SMOKE_SOLANA_PRIVATE_KEY');
+ if (cfg.agentId == null) missing.push('SMOKE_AGENT_ID');
+ if (missing.length) {
+ return skip(`devnet value step — set ${missing.join(', ')} (funded devnet wallet linked to the account)`);
+ }
+
+ const sol = await loadSolana();
+ const { Connection, VersionedTransaction } = sol;
+ const wallet = solanaKeypairFrom(sol, cfg.solanaKey);
+ const conn = new Connection(cfg.solanaRpcDevnet, 'confirmed');
+
+ // 1. launch-prep — server builds the unsigned tx + (server-ground) mint key.
+ const prep = await httpJson('POST', `${cfg.baseUrl}/api/pump/launch-prep`, {
+ cookie: cfg.authCookie,
+ body: {
+ agent_id: cfg.agentId,
+ wallet_address: wallet.publicKey.toBase58(),
+ name: 'three.ws smoke',
+ symbol: 'SMOKE',
+ uri: `${cfg.baseUrl}/.well-known/3d-agent-card.schema.json`,
+ network: 'devnet',
+ coin_type: 'regular',
+ sol_buy_in: 0,
+ },
+ });
+ if (!prep.ok) return fail(`launch-prep ${prep.status}: ${prep.json?.message || prep.text?.slice(0, 160)}`);
+
+ const { prep_id, mint, mint_secret_key_b64, tx_base64 } = prep.json;
+ const txn = VersionedTransaction.deserialize(Buffer.from(tx_base64, 'base64'));
+
+ // 2. Co-sign with the server-supplied mint keypair + the user wallet, broadcast.
+ const signers = [wallet];
+ if (mint_secret_key_b64) {
+ signers.push(sol.Keypair.fromSecretKey(Buffer.from(mint_secret_key_b64, 'base64')));
+ }
+ txn.sign(signers);
+ const sig = await conn.sendRawTransaction(txn.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction(sig, 'confirmed');
+
+ // 3. launch-confirm — server records the pump_agent_mints row.
+ const confirm = await httpJson('POST', `${cfg.baseUrl}/api/pump/launch-confirm`, {
+ cookie: cfg.authCookie,
+ body: { prep_id, tx_signature: sig },
+ });
+ if (!confirm.ok) return fail(`launch-confirm ${confirm.status}: ${confirm.json?.message || confirm.text?.slice(0, 160)}`);
+
+ ctx.solana = { mint, wallet };
+ return pass(`launched mint ${mint.slice(0, 8)}… on devnet · pump_agent_mints row recorded`, {
+ mint,
+ launchSig: sig,
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Step 6 — Solana trade (devnet)
+// ---------------------------------------------------------------------------
+
+async function stepSolanaTrade(cfg, ctx) {
+ const mint = ctx.solana?.mint || cfg.solanaMint;
+ const missing = [];
+ if (!cfg.baseUrl) missing.push('SMOKE_BASE_URL');
+ if (!cfg.authCookie) missing.push('SMOKE_AUTH_COOKIE');
+ if (!cfg.solanaKey) missing.push('SMOKE_SOLANA_PRIVATE_KEY');
+ if (!mint) missing.push('a mint (run step 5 first or set SMOKE_SOLANA_MINT)');
+ if (missing.length) return skip(`devnet value step — needs ${missing.join(', ')}`);
+
+ const sol = await loadSolana();
+ const { Connection, VersionedTransaction } = sol;
+ const wallet = ctx.solana?.wallet || solanaKeypairFrom(sol, cfg.solanaKey);
+ const conn = new Connection(cfg.solanaRpcDevnet, 'confirmed');
+
+ const prep = await httpJson('POST', `${cfg.baseUrl}/api/pump/buy-prep`, {
+ cookie: cfg.authCookie,
+ body: {
+ mint,
+ wallet_address: wallet.publicKey.toBase58(),
+ sol_amount: 0.001,
+ network: 'devnet',
+ },
+ });
+ if (!prep.ok) return fail(`buy-prep ${prep.status}: ${prep.json?.message || prep.text?.slice(0, 160)}`);
+
+ const txn = VersionedTransaction.deserialize(Buffer.from(prep.json.tx_base64, 'base64'));
+ txn.sign([wallet]);
+ const sig = await conn.sendRawTransaction(txn.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction(sig, 'confirmed');
+
+ const confirm = await httpJson('POST', `${cfg.baseUrl}/api/pump/buy-confirm`, {
+ cookie: cfg.authCookie,
+ body: { prep_id: prep.json.prep_id, mint, tx_signature: sig, network: 'devnet' },
+ });
+ if (!confirm.ok) return fail(`buy-confirm ${confirm.status}: ${confirm.json?.message || confirm.text?.slice(0, 160)}`);
+
+ return pass(`bought ${mint.slice(0, 8)}… on devnet · confirmed sig ${sig.slice(0, 10)}…`, { tradeSig: sig });
+}
+
+// ---------------------------------------------------------------------------
+// Step 7 — x402 pay-by-name (resolve + prep build, never broadcasts)
+// ---------------------------------------------------------------------------
+
+async function stepX402PayByName(cfg) {
+ if (!cfg.baseUrl) return skip('no SMOKE_BASE_URL — x402 pay-by-name runs against the deployed API');
+ if (!cfg.x402Name) {
+ return skip('no SMOKE_X402_NAME — set a resolvable @handle or .sol name to exercise the prep build');
+ }
+
+ // 1. Resolve the name (read-only).
+ const resolved = await httpJson(
+ 'GET',
+ `${cfg.baseUrl}/api/x402/pay-by-name?name=${encodeURIComponent(cfg.x402Name)}`,
+ );
+ if (!resolved.ok) {
+ return fail(`resolve "${cfg.x402Name}" -> ${resolved.status}: ${resolved.json?.message || resolved.text?.slice(0, 120)}`);
+ }
+ const recipient = resolved.json?.data?.address;
+ if (!recipient) return fail(`resolve returned no address for "${cfg.x402Name}"`);
+
+ // 2. Build a payment with a fresh synthetic payer — mode=prep only, NO broadcast.
+ const sol = await loadSolana();
+ const payer = cfg.x402Payer || sol.Keypair.generate().publicKey.toBase58();
+ const prep = await httpJson('POST', `${cfg.baseUrl}/api/x402/pay-by-name`, {
+ body: { name: cfg.x402Name, amount_usdc: 0.01, mode: 'prep', payer_wallet: payer },
+ });
+ if (!prep.ok) {
+ return fail(`prep build -> ${prep.status}: ${prep.json?.message || prep.text?.slice(0, 120)}`);
+ }
+ const txB64 = prep.json?.data?.tx_base64 || prep.json?.tx_base64;
+ if (!txB64) return fail('prep build returned no tx_base64');
+
+ return pass(`resolved "${cfg.x402Name}" -> ${recipient.slice(0, 8)}… · prep tx built (not broadcast)`);
+}
+
+// ---------------------------------------------------------------------------
+// Step 8 — Solana agent_invocation (devnet)
+// ---------------------------------------------------------------------------
+
+async function stepSolanaInvoke(cfg) {
+ let sdk;
+ try {
+ sdk = await import('../agent-protocol-sdk/dist/index.js');
+ } catch (err) {
+ return fail(`agent-protocol-sdk not built (run its build): ${err.message}`);
+ }
+ const programId = sdk.AGENT_INVOCATION_PROGRAM_ID;
+ if (!programId || programId === AGENT_INVOCATION_PLACEHOLDER) {
+ return skip('agent_invocation program not deployed — id is the Anchor placeholder (task 03 pending)');
+ }
+ if (!cfg.solanaKey) {
+ return skip('no funded devnet invoker — set SMOKE_SOLANA_PRIVATE_KEY');
+ }
+
+ const sol = await loadSolana();
+ const { Connection } = sol;
+ const invoker = solanaKeypairFrom(sol, cfg.solanaKey);
+ const target = sol.Keypair.generate(); // synthetic target authority
+ const conn = new Connection(cfg.solanaRpcDevnet, 'confirmed');
+
+ const sig = await sdk.invokeSkill({
+ connection: conn,
+ invokerAuthority: invoker,
+ targetAuthority: target.publicKey,
+ skillName: 'onchain-smoke',
+ parameters: JSON.stringify({ harness: 'scripts/onchain-smoke.mjs' }),
+ programId: new sol.PublicKey(programId),
+ });
+
+ // Assert the SkillInvoked event is in the confirmed tx's program logs.
+ const txInfo = await conn.getTransaction(sig, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 });
+ if (!txInfo || txInfo.meta?.err) {
+ return fail(`invoke_skill tx ${sig} not confirmed cleanly`);
+ }
+ const logs = txInfo.meta?.logMessages || [];
+ const sawEvent = logs.some((l) => /SkillInvoked|Program data:/.test(l));
+ if (!sawEvent) return fail('invoke_skill confirmed but no SkillInvoked event in logs');
+
+ return pass(`invoke_skill confirmed on devnet · SkillInvoked emitted · sig ${sig.slice(0, 10)}…`, { invokeSig: sig });
+}
+
+// ---------------------------------------------------------------------------
+// Step registry + runner
+// ---------------------------------------------------------------------------
+
+const STEPS = [
+ { key: 'parity', num: 1, title: 'Address parity', run: stepParity },
+ { key: 'evm-register', num: 2, title: 'EVM register (Base Sepolia)', run: stepEvmRegister },
+ { key: 'evm-validation', num: 3, title: 'EVM validation attestation', run: stepEvmValidation },
+ { key: 'evm-reputation', num: 4, title: 'EVM reputation feedback', run: stepEvmReputation },
+ { key: 'solana-launch', num: 5, title: 'Solana launch (devnet)', run: stepSolanaLaunch },
+ { key: 'solana-trade', num: 6, title: 'Solana trade (devnet)', run: stepSolanaTrade },
+ { key: 'x402-payname', num: 7, title: 'x402 pay-by-name (prep)', run: stepX402PayByName },
+ { key: 'solana-invoke', num: 8, title: 'Solana agent_invocation (devnet)', run: stepSolanaInvoke },
+];
+
+function parseArgs(argv) {
+ const args = { only: null, mainnetReadonly: false, json: false, list: false, help: false };
+ for (const a of argv) {
+ if (a === '--list') args.list = true;
+ else if (a === '--json') args.json = true;
+ else if (a === '--mainnet-readonly') args.mainnetReadonly = true;
+ else if (a === '--help' || a === '-h') args.help = true;
+ else if (a.startsWith('--only=')) args.only = a.slice('--only='.length).split(',').map((s) => s.trim()).filter(Boolean);
+ }
+ return args;
+}
+
+function buildConfig(args) {
+ return {
+ mainnetReadonly: args.mainnetReadonly,
+ evmChainId: Number(process.env.SMOKE_EVM_CHAIN_ID || 84532),
+ evmKey: process.env.SMOKE_EVM_PRIVATE_KEY || null,
+ evmKey2: process.env.SMOKE_EVM_PRIVATE_KEY_2 || null,
+ agentId: process.env.SMOKE_AGENT_ID != null ? Number(process.env.SMOKE_AGENT_ID) : null,
+ pinBaseUrl: (process.env.SMOKE_PIN_BASE_URL || '').replace(/\/$/, '') || null,
+ authCookie: process.env.SMOKE_AUTH_COOKIE || null,
+ baseUrl: (process.env.SMOKE_BASE_URL || '').replace(/\/$/, '') || null,
+ solanaKey: process.env.SMOKE_SOLANA_PRIVATE_KEY || null,
+ solanaMint: process.env.SMOKE_SOLANA_MINT || null,
+ solanaRpcDevnet: process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com',
+ x402Name: process.env.SMOKE_X402_NAME || null,
+ x402Payer: process.env.SMOKE_X402_PAYER || null,
+ };
+}
+
+function selectSteps(only) {
+ if (!only) return STEPS;
+ const picked = STEPS.filter((s) => only.includes(s.key) || only.includes(String(s.num)));
+ const unknown = only.filter((o) => !STEPS.some((s) => s.key === o || String(s.num) === o));
+ if (unknown.length) {
+ console.error(red(`Unknown step(s): ${unknown.join(', ')}`));
+ console.error(dim(`Valid keys: ${STEPS.map((s) => `${s.num}:${s.key}`).join(', ')}`));
+ process.exit(2);
+ }
+ return picked;
+}
+
+function printTable(results) {
+ const w = { num: 3, step: 34, status: 6, time: 7 };
+ const line = (n, step, status, time, detail) =>
+ `${String(n).padEnd(w.num)} ${step.padEnd(w.step)} ${status.padEnd(w.status)} ${time.padEnd(w.time)} ${detail}`;
+
+ console.log('');
+ console.log(bold(line('#', 'Step', 'Status', 'Time', 'Detail')));
+ console.log(dim('─'.repeat(96)));
+ for (const r of results) {
+ const s = STATUS[r.status];
+ console.log(
+ line(
+ r.num,
+ r.title,
+ s.paint(`${s.icon} ${s.label}`),
+ fmtMs(r.ms),
+ dim(r.detail || ''),
+ ),
+ );
+ }
+ console.log(dim('─'.repeat(96)));
+}
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+
+ if (args.help) {
+ console.log(
+ 'On-chain end-to-end smoke harness. See the file header for credentials and flags.',
+ );
+ console.log(`Steps: ${STEPS.map((s) => `${s.num}:${s.key}`).join(', ')}`);
+ return 0;
+ }
+ if (args.list) {
+ for (const s of STEPS) console.log(`${s.num} ${s.key.padEnd(16)} ${s.title}`);
+ return 0;
+ }
+
+ const cfg = buildConfig(args);
+ const steps = selectSteps(args.only);
+ const ctx = {};
+
+ console.log(bold('On-chain end-to-end smoke harness'));
+ console.log(
+ dim(
+ `mode=${cfg.mainnetReadonly ? 'mainnet-readonly' : 'testnet/devnet'} · evmChain=${cfg.evmChainId} · steps=${steps.map((s) => s.num).join(',')}`,
+ ),
+ );
+ console.log('');
+
+ const results = [];
+ for (const step of steps) {
+ process.stdout.write(dim(`→ [${step.num}] ${step.title} … `));
+ const t0 = Date.now();
+ let res;
+ try {
+ res = await step.run(cfg, ctx);
+ } catch (err) {
+ res = fail(err.shortMessage || err.message || String(err));
+ }
+ const ms = Date.now() - t0;
+ const s = STATUS[res.status];
+ console.log(s.paint(`${s.icon} ${res.status}`) + dim(` (${fmtMs(ms)})`));
+ results.push({ num: step.num, key: step.key, title: step.title, ms, ...res });
+ }
+
+ printTable(results);
+
+ const counts = results.reduce((a, r) => ((a[r.status] = (a[r.status] || 0) + 1), a), {});
+ const summary = `${counts.PASS || 0} pass · ${counts.SKIP || 0} skip · ${counts.FAIL || 0} fail`;
+ console.log(
+ (counts.FAIL ? red : green)(bold(summary)) +
+ (counts.SKIP ? dim(' (skips need funded signers / deployed deps / credentials — see headers)') : ''),
+ );
+
+ if (args.json) {
+ console.log(
+ JSON.stringify(
+ { summary: counts, results: results.map(({ extra, ...r }) => ({ ...r, ...(extra || {}) })) },
+ null,
+ 2,
+ ),
+ );
+ }
+
+ return counts.FAIL ? 1 : 0;
+}
+
+main()
+ .then((code) => process.exit(code))
+ .catch((err) => {
+ console.error(red(`\nharness crashed: ${err.stack || err.message}`));
+ process.exit(1);
+ });
diff --git a/scripts/verify-solana-parity.mjs b/scripts/verify-solana-parity.mjs
index 9ec7a0379..9e0ff9a86 100644
--- a/scripts/verify-solana-parity.mjs
+++ b/scripts/verify-solana-parity.mjs
@@ -118,7 +118,11 @@ 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\/)/;
+// Minified/vendored third-party blobs (draco, codemirror, ktx2, *.bundle.js) and
+// test/fixture/IDL files. The catch-all is the minified-line guard in scanFile().
+const SCAN_SKIP_FILE = /(\.test\.|\.spec\.|\/fixtures\/|_demo-fixtures|\/idl\/|\.min\.js$|\.bundle\.js$|\/(libs|draco|ktx2|vendor|wasm)\/)/;
+// Authored source never has 20k-char lines; a file that does is a minified bundle.
+const MINIFIED_LINE = 20_000;
export function listSourceFiles({ root = ROOT } = {}) {
let files;
@@ -187,6 +191,9 @@ export function scanForDrift(registry, { root = ROOT, files = listSourceFiles({
continue;
}
const lines = text.split('\n');
+ // Defensive: skip any minified blob that slipped past the path filter —
+ // a single 1 MB line turns the per-line regexes into a CPU sink.
+ if (lines.some((l) => l.length > MINIFIED_LINE)) continue;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
diff --git a/scripts/verify-threews-payments-base.mjs b/scripts/verify-threews-payments-base.mjs
new file mode 100644
index 000000000..3dbe913f4
--- /dev/null
+++ b/scripts/verify-threews-payments-base.mjs
@@ -0,0 +1,116 @@
+#!/usr/bin/env node
+// Verify the live ThreeWSPayments contract on Base (chain 8453) on Basescan.
+//
+// The contract is already deployed and bytecode-confirmed at
+// 0x31B13cDe47431EfcC8616C8495204e6E6C2Ded34
+// (see contracts/DEPLOYMENTS.md). This script submits the source for
+// public verification via the Etherscan v2 multichain API and polls the GUID
+// until Basescan reports success.
+//
+// Inputs are pinned to exactly what produced the on-chain bytecode — confirmed
+// by reproducing the live BSC deploy's init-code hash byte-for-byte from the
+// same source + settings:
+// - solc 0.8.35, optimizer enabled, runs 200
+// - constructor(address _owner, address _usdc)
+// - _owner = 0x4022de2D36C334E73C7a108805Cea11C0564f402 (deployer EOA)
+// - _usdc = 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 (Base USDC)
+//
+// Usage:
+// BASESCAN_API_KEY=<key> node scripts/verify-threews-payments-base.mjs
+// (ETHERSCAN_API_KEY also accepted — the v2 endpoint is multichain.)
+//
+// Without a key the script prints the full verification bundle (Standard JSON
+// Input + ABI-encoded constructor args) so it can be pasted into the Basescan
+// "Verify & Publish" UI manually.
+
+import { readFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { encodeAbiParameters } from 'viem';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+const ADDRESS = '0x31B13cDe47431EfcC8616C8495204e6E6C2Ded34';
+const CHAIN_ID = 8453;
+const OWNER = '0x4022de2D36C334E73C7a108805Cea11C0564f402';
+const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+const COMPILER = 'v0.8.35+commit.47b9dedd';
+const CONTRACT_NAME = 'contracts/ThreeWSPayments.sol:ThreeWSPayments';
+
+const constructorArgs = encodeAbiParameters(
+ [{ type: 'address' }, { type: 'address' }],
+ [OWNER, BASE_USDC],
+).slice(2);
+
+// Standard JSON Input — the same settings that produced the deployed bytecode.
+const standardJson = {
+ language: 'Solidity',
+ sources: {
+ 'contracts/ThreeWSPayments.sol': {
+ content: readFileSync(resolve(root, 'contracts/ThreeWSPayments.sol'), 'utf8'),
+ },
+ },
+ settings: {
+ optimizer: { enabled: true, runs: 200 },
+ outputSelection: { '*': { '*': ['abi', 'evm.bytecode', 'evm.deployedBytecode'] } },
+ },
+};
+
+const apiKey = process.env.BASESCAN_API_KEY || process.env.ETHERSCAN_API_KEY || '';
+const API = 'https://api.etherscan.io/v2/api';
+
+async function submit() {
+ const body = new URLSearchParams({
+ chainid: String(CHAIN_ID),
+ apikey: apiKey,
+ module: 'contract',
+ action: 'verifysourcecode',
+ codeformat: 'solidity-standard-json-input',
+ contractaddress: ADDRESS,
+ contractname: CONTRACT_NAME,
+ compilerversion: COMPILER,
+ sourceCode: JSON.stringify(standardJson),
+ constructorArguements: constructorArgs,
+ });
+ const res = await fetch(API, { method: 'POST', body });
+ const json = await res.json();
+ if (json.status !== '1') throw new Error(`verify submit failed: ${json.result || json.message}`);
+ return json.result; // GUID
+}
+
+async function poll(guid) {
+ const url = `${API}?chainid=${CHAIN_ID}&module=contract&action=checkverifystatus&guid=${guid}&apikey=${apiKey}`;
+ for (let i = 0; i < 20; i++) {
+ await new Promise((r) => setTimeout(r, 5000));
+ const json = await (await fetch(url)).json();
+ const r = String(json.result || '');
+ if (r.includes('Pending')) {
+ process.stdout.write('.');
+ continue;
+ }
+ return json;
+ }
+ throw new Error('verification still pending after 100s — check Basescan manually');
+}
+
+if (!apiKey) {
+ console.log('No BASESCAN_API_KEY / ETHERSCAN_API_KEY set — printing the bundle for manual verification.\n');
+ console.log('Address :', ADDRESS, `(chain ${CHAIN_ID})`);
+ console.log('Contract :', CONTRACT_NAME);
+ console.log('Compiler :', COMPILER, '| optimizer: enabled, 200 runs');
+ console.log('Constructor args :', constructorArgs);
+ console.log('\n--- Standard JSON Input ---');
+ console.log(JSON.stringify(standardJson));
+ process.exit(0);
+}
+
+console.log(`Submitting ThreeWSPayments @ ${ADDRESS} for verification on Base (chain ${CHAIN_ID})…`);
+const guid = await submit();
+console.log('GUID:', guid, '\nPolling status');
+const result = await poll(guid);
+if (String(result.result).toLowerCase().includes('verified') || result.status === '1') {
+ console.log(`\n✅ Verified: https://basescan.org/address/${ADDRESS}#code`);
+} else {
+ console.error('\n❌', result.result || JSON.stringify(result));
+ process.exit(1);
+}
diff --git a/src/agent-onchain-card.js b/src/agent-onchain-card.js
index aa8e65085..bd8002eb2 100644
--- a/src/agent-onchain-card.js
+++ b/src/agent-onchain-card.js
@@ -106,7 +106,7 @@ export function mountAgentOnchainCard({ panel, identity }) {
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}` : '—');
+ const agentIdLabel = onchain.onchain_id ? `#${onchain.onchain_id}` : status.registry || '—';
return `
<div class="aoc-head">
<span class="aoc-title">On-chain identity</span>
diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.js
index 059ffa0b4..969fa735c 100644
--- a/src/agent-skills-pumpfun.js
+++ b/src/agent-skills-pumpfun.js
@@ -898,7 +898,7 @@ export function registerPumpFunSkills(skills) {
// ── pumpfun.channelFeed ───────────────────────────────────────────────────
skills.register({
name: 'pumpfun.channelFeed',
- description: 'Fetch recent pump.fun signals (new mints, whale buys, creator claims) as a digest the LLM can summarize.',
+ description: 'Fetch recent pump.fun activity (new mints, whale buys, creator claims) plus agent-attributed reputation signals as a digest the LLM can summarize.',
instruction: 'Read-only. No wallet required. Returns latest channel-feed items.',
animationHint: 'inspect',
voicePattern: 'Fetching pump.fun signal feed…',
@@ -909,7 +909,7 @@ export function registerPumpFunSkills(skills) {
limit: { type: 'integer', minimum: 1, maximum: 200, default: 20 },
kinds: {
type: 'string',
- description: 'Comma-separated filter: mint, whale, claim (default: all)',
+ description: 'Comma-separated filter: mint, whale, claim, signal (default: all)',
},
},
},
diff --git a/src/erc8004/abi.js b/src/erc8004/abi.js
index 4b4d0d42c..0079b6564 100644
--- a/src/erc8004/abi.js
+++ b/src/erc8004/abi.js
@@ -65,12 +65,20 @@ export const REPUTATION_REGISTRY_ABI = [
];
/**
- * Validation Registry ABI — best-effort; may need updating once the canonical
- * interface is published. Mainnet has no Validation Registry deployed yet.
+ * Validation Registry ABI — mirrors contracts/src/ValidationRegistry.sol and the
+ * canonical SDK ABI (sdk/src/erc8004/abi.js). The `getValidation*` read fragments
+ * are required by getLatestValidation() in validation-recorder.js; without them
+ * ethers cannot encode the call. Mainnet has no Validation Registry deployed yet.
*/
+const VALIDATION_RECORD_TUPLE =
+ 'tuple(address validator, bool passed, bytes32 proofHash, string proofURI, uint64 timestamp, string kind)';
+
export const VALIDATION_REGISTRY_ABI = [
'function recordValidation(uint256 agentId, bool passed, bytes32 proofHash, string proofURI, string kind) external',
'function getValidationCount(uint256 agentId) external view returns (uint256)',
+ `function getValidation(uint256 agentId, uint256 index) external view returns (${VALIDATION_RECORD_TUPLE})`,
+ `function getLatestByKind(uint256 agentId, string kind) external view returns (${VALIDATION_RECORD_TUPLE})`,
+ `function getValidationRange(uint256 agentId, uint256 offset, uint256 limit) external view returns (${VALIDATION_RECORD_TUPLE}[])`,
'event ValidationRecorded(uint256 indexed agentId, address indexed validator, bool passed, bytes32 proofHash, string kind)',
];
diff --git a/src/erc8004/agent-registry.js b/src/erc8004/agent-registry.js
index 31bf1e723..ae16407d0 100644
--- a/src/erc8004/agent-registry.js
+++ b/src/erc8004/agent-registry.js
@@ -534,6 +534,8 @@ export async function bindExistingAgentOnchain(agentId, chainId, { onStatus } =
if (!agent) throw new Error('Agent not found.');
// ── 2. Idempotency — never mint twice on a chain the agent is already on.
+ // Covers both the canonical meta.onchain block and the legacy EVM columns
+ // (erc8004_agent_id + chain_id) written by the original mint flow.
const existingOnchain = agent.onchain || agent.meta?.onchain || null;
if (existingOnchain && existingOnchain.chain === `eip155:${chainId}`) {
log('Agent is already registered on this chain.');
@@ -545,6 +547,15 @@ export async function bindExistingAgentOnchain(agentId, chainId, { onStatus } =
registrationUrl: existingOnchain.metadata_uri || undefined,
};
}
+ if (agent.erc8004_agent_id && Number(agent.chain_id) === chainId) {
+ log('Agent is already registered on this chain.');
+ return {
+ alreadyBound: true,
+ agentId: String(agent.erc8004_agent_id),
+ chainId,
+ onchain: existingOnchain || undefined,
+ };
+ }
// ── 3. Resolve stored assets — reuse, never re-enter or re-pin the GLB.
const glbUrl = agent.avatar_model_url || null;
diff --git a/src/erc8004/validation-report.test.js b/src/erc8004/validation-report.test.js
new file mode 100644
index 000000000..bde117345
--- /dev/null
+++ b/src/erc8004/validation-report.test.js
@@ -0,0 +1,101 @@
+import { describe, it, expect } from 'vitest';
+import {
+ KIND_GLB_SCHEMA,
+ SEVERITY,
+ reportPassed,
+ hashReport,
+ buildGlbReport,
+ failureReason,
+} from './validation-report.js';
+
+const VALIDATED_AT = '2026-06-15T00:00:00.000Z';
+
+const okInspect = {
+ fileSize: 1024,
+ container: 'glb',
+ counts: { totalVertices: 100, totalTriangles: 40 },
+};
+
+describe('reportPassed', () => {
+ it('passes when there are zero errors', () => {
+ const report = buildGlbReport({ url: 'x', inspect: okInspect, suggestions: [], validatedAt: VALIDATED_AT });
+ expect(reportPassed(report)).toBe(true);
+ expect(report.issues.numErrors).toBe(0);
+ });
+
+ it('fails when the model could not be parsed', () => {
+ const report = buildGlbReport({ url: 'x', error: 'not a GLB', validatedAt: VALIDATED_AT });
+ expect(reportPassed(report)).toBe(false);
+ expect(report.issues.numErrors).toBe(1);
+ expect(report.issues.messages[0].code).toBe('GLB_PARSE_FAILED');
+ });
+
+ it('treats warnings and infos as passing', () => {
+ const report = buildGlbReport({
+ url: 'x',
+ inspect: okInspect,
+ suggestions: [
+ { id: 'tri_budget', severity: 'warn', message: 'too many tris' },
+ { id: 'draco', severity: 'info', message: 'compress', estimate: '12 KB' },
+ ],
+ validatedAt: VALIDATED_AT,
+ });
+ expect(reportPassed(report)).toBe(true);
+ expect(report.issues.numWarnings).toBe(1);
+ expect(report.issues.numInfos).toBe(1);
+ // estimate is folded into the message.
+ expect(report.issues.messages.find((m) => m.code === 'DRACO').message).toContain('(12 KB)');
+ });
+
+ it('maps critical suggestions to hard errors (fails)', () => {
+ const report = buildGlbReport({
+ url: 'x',
+ inspect: okInspect,
+ suggestions: [{ id: 'corrupt', severity: 'critical', message: 'broken buffer' }],
+ validatedAt: VALIDATED_AT,
+ });
+ expect(report.issues.messages[0].severity).toBe(SEVERITY.ERROR);
+ expect(reportPassed(report)).toBe(false);
+ });
+});
+
+describe('hashReport', () => {
+ it('is deterministic for identical reports', () => {
+ const a = buildGlbReport({ url: 'x', sha256: 'abc', inspect: okInspect, validatedAt: VALIDATED_AT });
+ const b = buildGlbReport({ url: 'x', sha256: 'abc', inspect: okInspect, validatedAt: VALIDATED_AT });
+ expect(hashReport(a)).toBe(hashReport(b));
+ expect(hashReport(a)).toMatch(/^0x[0-9a-f]{64}$/);
+ });
+
+ it('changes when the bytes (sha256) change — byte-check is part of the proof', () => {
+ const a = buildGlbReport({ url: 'x', sha256: 'aaa', inspect: okInspect, validatedAt: VALIDATED_AT });
+ const b = buildGlbReport({ url: 'x', sha256: 'bbb', inspect: okInspect, validatedAt: VALIDATED_AT });
+ expect(hashReport(a)).not.toBe(hashReport(b));
+ });
+});
+
+describe('byteCheck', () => {
+ it('surfaces the sha256 + byteLength independently of pass/fail', () => {
+ const report = buildGlbReport({
+ url: 'x',
+ sha256: 'deadbeef',
+ byteLength: 2048,
+ inspect: okInspect,
+ validatedAt: VALIDATED_AT,
+ });
+ expect(report.byteCheck).toEqual({ sha256: 'deadbeef', byteLength: 2048 });
+ expect(report.kind).toBe(KIND_GLB_SCHEMA);
+ });
+});
+
+describe('failureReason', () => {
+ it('is empty for a passing report', () => {
+ const report = buildGlbReport({ url: 'x', inspect: okInspect, validatedAt: VALIDATED_AT });
+ expect(failureReason(report)).toBe('');
+ });
+
+ it('returns the single error message', () => {
+ const report = buildGlbReport({ url: 'x', error: 'not a GLB', validatedAt: VALIDATED_AT });
+ expect(failureReason(report)).toBe('not a GLB');
+ });
+});
diff --git a/src/game/coin-buy.js b/src/game/coin-buy.js
index 667956f58..39c33e503 100644
--- a/src/game/coin-buy.js
+++ b/src/game/coin-buy.js
@@ -1,10 +1,17 @@
-// Native pump.fun buy — the in-world "ape this coin" flow for /play.
+// Native pump.fun trade widget — the in-world "ape this coin" flow for /play.
//
// Every /play world IS a pump.fun coin, so the most natural action in that
-// world is buying it. This is a REAL on-chain buy, not a redirect: the
-// three.ws server builds the unsigned transaction (handling both the bonding
-// curve and the post-graduation AMM via @pump-fun/pump-sdk), the player's
-// Solana wallet signs it, and we broadcast through our same-origin RPC proxy.
+// world is trading it. This is a REAL on-chain buy/sell, not a redirect: the
+// three.ws server builds the unsigned transaction (handling the bonding curve
+// and the post-graduation AMM, SOL- and USDC-paired, via @pump-fun/pump-sdk),
+// the player's Solana wallet signs it, and we broadcast through our same-origin
+// RPC proxy.
+//
+// Denomination-aware: a coin's quote asset (SOL or USDC) is detected on mount
+// from the on-chain bonding curve, and every label, input suffix, balance, and
+// quote is driven off it. SOL-paired coins behave exactly as the original
+// SOL-only widget; USDC-paired coins denominate the buy input in USDC, show the
+// wallet's USDC balance, and price/settle against the USDC curve.
//
// Loaded as its own lazy chunk (dynamic import on first Buy click) so the heavy
// Solana/pump SDKs never weigh down the main /play bundle. The read-only quote
@@ -14,12 +21,26 @@
import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';
const WSOL = 'So11111111111111111111111111111111111111112';
+const USDC_MINT = {
+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',
+};
const NETWORK = 'mainnet';
-const SOL_PRESETS = [0.1, 0.5, 1];
const SLIPPAGE_PRESETS = [100, 300, 500]; // bps — 1% / 3% / 5%
const DEFAULT_SLIPPAGE_BPS = 300;
const PUMP_DECIMALS = 6; // pump.fun mints are always 6 decimals
+// Per-quote-asset denomination descriptors. SOL is the default until the coin's
+// pairing is detected, so a SOL coin never flickers and renders exactly as the
+// original widget; a USDC coin upgrades in place once detection resolves.
+const SOL_DENOM = { kind: 'sol', label: 'SOL', mint: WSOL, decimals: 9, presets: [0.1, 0.5, 1], step: 0.05 };
+function usdcDenom(network = NETWORK) {
+ return { kind: 'usdc', label: 'USDC', mint: USDC_MINT[network] || USDC_MINT.mainnet, decimals: 6, presets: [5, 25, 100], step: 1 };
+}
+
+// Sell uses fractions of the wallet's holdings instead of fixed amounts.
+const SELL_PRESETS = [['25%', 0.25], ['50%', 0.5], ['Max', 1]];
+
let _open = null; // the live modal controller, so a second click reuses it
function el(tag, props = {}, kids = []) {
@@ -35,83 +56,120 @@ function el(tag, props = {}, kids = []) {
return n;
}
+// Base-units (raw, decimals applied) → compact human token count.
const fmtTokens = (raw) => {
const n = Number(raw) / 10 ** PUMP_DECIMALS;
if (!isFinite(n) || n <= 0) return null;
+ return compactCount(n);
+};
+
+// A UI token count (already divided) → compact human string.
+function compactCount(n) {
+ if (!isFinite(n) || n <= 0) return '0';
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.toLocaleString(undefined, { maximumFractionDigits: 2 });
-};
+}
+
+// A decimal quote amount → string with asset-appropriate precision.
+function fmtQuote(n, denom) {
+ const v = Number(n);
+ if (!isFinite(v)) return '0';
+ const frac = denom.kind === 'usdc' ? (v >= 1 ? 2 : 4) : v >= 1 ? 3 : 5;
+ return v.toLocaleString(undefined, { maximumFractionDigits: frac });
+}
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."
+ * Map a trade failure to copy the player can act on. A bare "Trade 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
+ * @param {'buy'|'sell'} [mode]
*/
-function friendlyTradeError(err) {
+function friendlyTradeError(err, mode = 'buy') {
const raw = (err && (err.message || String(err))) || '';
const m = raw.toLowerCase();
+ const noun = mode === 'sell' ? 'this sale' : 'this buy';
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.';
+ return `Not enough SOL to cover ${noun} + 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.';
+ return raw.replace(/\s+/g, ' ').trim().slice(0, 140) || `${mode === 'sell' ? 'Sale' : 'Purchase'} failed. Try again.`;
}
/**
- * Open the buy modal for a coin. Idempotent — a second call refocuses the
- * existing modal instead of stacking.
+ * Open the trade modal for a coin. Idempotent — a second call refocuses the
+ * existing modal instead of stacking. Opens in Buy mode; the user can switch to
+ * Sell inside the modal.
* @param {{mint:string, name?:string, symbol?:string, image?:string}} coin
+ * @param {{mode?: 'buy'|'sell'}} [opts]
*/
-export function openBuyModal(coin) {
+export function openBuyModal(coin, opts = {}) {
if (!coin?.mint) return;
if (_open) { _open.focus(); return; }
- _open = new BuyModal(coin);
+ _open = new TradeModal(coin, opts.mode === 'sell' ? 'sell' : 'buy');
}
-class BuyModal {
- constructor(coin) {
+export { openBuyModal as openTradeModal };
+
+class TradeModal {
+ constructor(coin, mode = 'buy') {
this.coin = coin;
+ this.symPlain = coin.symbol ? '$' + coin.symbol.toUpperCase() : '';
this.sym = coin.symbol ? '$' + coin.symbol.toUpperCase() : 'this coin';
- this.amount = SOL_PRESETS[0];
+ this.symTokens = coin.symbol ? '$' + coin.symbol.toUpperCase() : 'tokens';
+ this.mode = mode;
+ // Optimistic SOL until detection confirms/upgrades the pairing, so a SOL
+ // coin renders identically to the original widget with no flicker.
+ this.denom = SOL_DENOM;
+ this.amount = mode === 'buy' ? SOL_DENOM.presets[0] : 0;
+ this._sellMax = false;
this.slippageBps = DEFAULT_SLIPPAGE_BPS;
this.busy = false;
this._quoteSeq = 0;
+ this._balSeq = 0;
+ this.quoteBalance = null; // wallet's USDC balance (USDC buys only)
+ this.holdings = null; // wallet's holding of this coin (for sells)
// 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._detectP = this._detectDenom();
this._refreshWallet();
+ this._refreshBalances();
this._quote();
}
// --------------------------------------------------------------- view
_build() {
+ this.tabs = el('div', { class: 'cc-buy-tabs', role: 'tablist', 'aria-label': 'Trade direction' }, [
+ el('button', { class: 'cc-buy-tab' + (this.mode === 'buy' ? ' cc-on' : ''), type: 'button', role: 'tab', 'aria-selected': this.mode === 'buy', text: 'Buy', onclick: () => this._setMode('buy') }),
+ el('button', { class: 'cc-buy-tab' + (this.mode === 'sell' ? ' cc-on' : ''), type: 'button', role: 'tab', 'aria-selected': this.mode === 'sell', text: 'Sell', onclick: () => this._setMode('sell') }),
+ ]);
+
+ this.fieldLabel = el('span', { class: 'cc-buy-field-label', text: this.mode === 'buy' ? 'You pay' : 'You sell' });
+ this.unitEl = el('span', { class: 'cc-buy-unit', text: this.denom.label });
this.amountInput = el('input', {
- type: 'number', min: '0', step: '0.05', inputmode: 'decimal',
- class: 'cc-buy-amount', value: String(this.amount), 'aria-label': 'Amount in SOL',
- oninput: () => { this.amount = Math.max(0, Number(this.amountInput.value) || 0); this._syncPresets(); this._quote(); this._syncCta(); },
+ type: 'number', min: '0', step: String(this.denom.step), inputmode: 'decimal',
+ class: 'cc-buy-amount', value: this.mode === 'buy' ? String(this.amount) : '',
+ 'aria-label': this._amountAria(),
+ oninput: () => { this._onAmountInput(); },
});
- this.presetRow = el('div', { class: 'cc-buy-presets' },
- SOL_PRESETS.map((v) => el('button', {
- class: 'cc-buy-preset' + (v === this.amount ? ' cc-on' : ''), text: v + ' SOL', type: 'button',
- onclick: () => { this.amount = v; this.amountInput.value = String(v); this._syncPresets(); this._quote(); this._syncCta(); },
- })));
-
+ this.presetRow = el('div', { class: 'cc-buy-presets' });
+ this.balLine = el('div', { class: 'cc-buy-bal', role: 'status', 'aria-live': 'polite', hidden: true });
this.quoteLine = el('div', { class: 'cc-buy-quote', role: 'status', 'aria-live': 'polite' }, 'Fetching price…');
this.slipRow = el('div', { class: 'cc-buy-slip' }, [
@@ -141,22 +199,24 @@ class BuyModal {
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-name', text: this.coin.name || 'Trade coin' }),
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) + '…' }),
+ el('span', { class: 'cc-buy-sym', text: this.symPlain || this.coin.mint.slice(0, 8) + '…' }),
this.stagePill,
]),
]),
el('button', { class: 'cc-buy-x', type: 'button', 'aria-label': 'Close', text: '✕', onclick: () => this.close() }),
]);
- this.card = el('div', { class: 'cc-buy-card', role: 'dialog', 'aria-modal': 'true', 'aria-label': `Buy ${this.coin.name || 'coin'}` }, [
+ this.card = el('div', { class: 'cc-buy-card', role: 'dialog', 'aria-modal': 'true', 'aria-label': `Trade ${this.coin.name || 'coin'}` }, [
head,
+ this.tabs,
el('label', { class: 'cc-buy-field' }, [
- el('span', { class: 'cc-buy-field-label', text: 'You pay' }),
- el('div', { class: 'cc-buy-amount-wrap' }, [this.amountInput, el('span', { class: 'cc-buy-unit', text: 'SOL' })]),
+ this.fieldLabel,
+ el('div', { class: 'cc-buy-amount-wrap' }, [this.amountInput, this.unitEl]),
]),
this.presetRow,
+ this.balLine,
this.quoteLine,
this.slipRow,
this.walletLine,
@@ -173,7 +233,7 @@ class BuyModal {
});
document.body.appendChild(this.overlay);
requestAnimationFrame(() => this.overlay.classList.add('cc-on'));
- this._syncCta();
+ this._syncMode();
setTimeout(() => this.amountInput.focus(), 30);
}
@@ -185,8 +245,95 @@ class BuyModal {
if (_open === this) _open = null;
}
+ _amountAria() {
+ return this.mode === 'buy' ? `Amount in ${this.denom.label}` : `Amount of ${this.symTokens} to sell`;
+ }
+
+ _onAmountInput() {
+ this._sellMax = false;
+ this.amount = Math.max(0, Number(this.amountInput.value) || 0);
+ this._syncPresets();
+ this._renderBalance();
+ this._quote();
+ this._syncCta();
+ }
+
+ // Rebuild presets + labels + balance for the current (mode, denom). Called on
+ // mount, on mode switch, and when detection upgrades the pairing to USDC.
+ _syncMode() {
+ this.fieldLabel.textContent = this.mode === 'buy' ? 'You pay' : 'You sell';
+ this.unitEl.textContent = this.mode === 'buy' ? this.denom.label : this.symTokens;
+ this.amountInput.setAttribute('aria-label', this._amountAria());
+ this.amountInput.step = String(this.mode === 'buy' ? this.denom.step : 1);
+ for (const t of this.tabs.children) {
+ const on = t.textContent.toLowerCase() === this.mode;
+ t.classList.toggle('cc-on', on);
+ t.setAttribute('aria-selected', String(on));
+ }
+
+ this.presetRow.textContent = '';
+ if (this.mode === 'buy') {
+ for (const v of this.denom.presets) {
+ this.presetRow.appendChild(el('button', {
+ class: 'cc-buy-preset' + (v === this.amount ? ' cc-on' : ''), type: 'button',
+ text: v + ' ' + this.denom.label,
+ onclick: () => { this._sellMax = false; this.amount = v; this.amountInput.value = String(v); this._syncPresets(); this._renderBalance(); this._quote(); this._syncCta(); },
+ }));
+ }
+ } else {
+ for (const [label, frac] of SELL_PRESETS) {
+ this.presetRow.appendChild(el('button', {
+ class: 'cc-buy-preset', type: 'button', text: label,
+ onclick: () => this._applySellFraction(label, frac),
+ }));
+ }
+ }
+ this._renderBalance();
+ this._syncPresets();
+ }
+
+ _applySellFraction(label, frac) {
+ const hold = this.holdings;
+ if (!hold || !(hold.ui > 0)) return;
+ this._sellMax = frac >= 1;
+ this.amount = this._sellMax ? hold.ui : Math.max(0, hold.ui * frac);
+ this.amountInput.value = this._sellMax ? String(hold.ui) : trimNum(this.amount);
+ for (const b of this.presetRow.children) b.classList.toggle('cc-on', b.textContent === label);
+ this._quote();
+ this._syncCta();
+ }
+
_syncPresets() {
- for (const b of this.presetRow.children) b.classList.toggle('cc-on', b.textContent === this.amount + ' SOL');
+ if (this.mode === 'buy') {
+ for (const b of this.presetRow.children) b.classList.toggle('cc-on', b.textContent === this.amount + ' ' + this.denom.label);
+ } else if (!this._sellMax) {
+ for (const b of this.presetRow.children) b.classList.remove('cc-on');
+ }
+ }
+
+ // --------------------------------------------------------------- detection
+ // Read the coin's quote asset (and graduation status) from the on-chain
+ // curve. The buy/sell-prep endpoints auto-detect server-side too — this is
+ // purely so the UI denominates correctly before the user enters an amount.
+ async _detectDenom() {
+ try {
+ const r = await fetch(`/api/pump/quote?mint=${encodeURIComponent(this.coin.mint)}&network=${NETWORK}`);
+ const data = await r.json().catch(() => ({}));
+ if (!r.ok || !data?.quote_mint) return;
+ this.graduated = !!data.graduated;
+ this._renderStage();
+ if (data.quote_mint !== WSOL && this.denom.kind !== 'usdc') {
+ this.denom = usdcDenom(NETWORK);
+ if (this.mode === 'buy') {
+ this.amount = this.denom.presets[0];
+ this.amountInput.value = String(this.amount);
+ }
+ this._syncMode();
+ this._refreshBalances();
+ this._quote();
+ this._syncCta();
+ }
+ } catch { /* keep optimistic SOL — prep still auto-detects server-side */ }
}
// --------------------------------------------------------------- wallet
@@ -212,14 +359,103 @@ class BuyModal {
this._syncCta();
}
+ // Fetch the wallet's USDC balance (USDC buys) and coin holdings (sells). A
+ // SOL buy needs neither, so it makes no extra RPC call — keeping that path
+ // identical to the original SOL-only widget.
+ async _refreshBalances() {
+ const needsQuoteBal = this.mode === 'buy' && this.denom.kind === 'usdc';
+ const needsHoldings = this.mode === 'sell';
+ if (!needsQuoteBal && !needsHoldings) { this.quoteBalance = null; this.holdings = null; this._renderBalance(); return; }
+ const w = detectSolanaWallet();
+ const owner = w?.publicKey?.toString?.();
+ if (!owner) { this.quoteBalance = null; this.holdings = null; this._renderBalance(); this._syncCta(); return; }
+ const seq = ++this._balSeq;
+ try {
+ const { Connection, PublicKey } = await import('@solana/web3.js');
+ const conn = new Connection(SOLANA_RPC[NETWORK], 'confirmed');
+ const ownerPk = new PublicKey(owner);
+ const [coinRes, quoteRes] = await Promise.all([
+ needsHoldings ? conn.getParsedTokenAccountsByOwner(ownerPk, { mint: new PublicKey(this.coin.mint) }).catch(() => null) : Promise.resolve(null),
+ needsQuoteBal ? conn.getParsedTokenAccountsByOwner(ownerPk, { mint: new PublicKey(this.denom.mint) }).catch(() => null) : Promise.resolve(null),
+ ]);
+ if (seq !== this._balSeq) return;
+ this.holdings = needsHoldings ? parseTokenAmount(coinRes) : null;
+ this.quoteBalance = needsQuoteBal ? parseTokenAmount(quoteRes) : null;
+ this._renderBalance();
+ this._syncCta();
+ } catch { /* leave balances null; states fall back to neutral */ }
+ }
+
+ _renderBalance() {
+ this.balLine.textContent = '';
+ this.balLine.classList.remove('cc-buy-bal-warn');
+ if (this.mode === 'buy' && this.denom.kind === 'usdc') {
+ this.balLine.hidden = false;
+ if (this.quoteBalance) {
+ const low = this.amount > 0 && this.amount > this.quoteBalance.ui + 1e-9;
+ this.balLine.classList.toggle('cc-buy-bal-warn', low);
+ this.balLine.append(el('span', { text: `Balance ${fmtQuote(this.quoteBalance.ui, this.denom)} USDC` }));
+ if (low) this.balLine.append(el('span', { class: 'cc-buy-bal-sep', text: ' · ' }), el('button', { class: 'cc-buy-link', type: 'button', text: 'Add USDC', onclick: () => this._openFund() }));
+ } else {
+ this.balLine.append(el('span', { text: 'Balance —' }));
+ }
+ } else if (this.mode === 'sell') {
+ this.balLine.hidden = false;
+ if (this.holdings) {
+ if (this.holdings.ui > 0) {
+ this.balLine.append(el('span', { text: `You hold ${compactCount(this.holdings.ui)} ${this.symTokens}` }));
+ } else {
+ this.balLine.append(el('span', { class: 'cc-buy-wallet-off', text: `You don't hold any ${this.symTokens} yet` }));
+ }
+ } else {
+ this.balLine.append(el('span', { text: 'Holdings —' }));
+ }
+ } else {
+ this.balLine.hidden = true;
+ }
+ }
+
+ _setMode(mode) {
+ if (this.mode === mode) return;
+ this.mode = mode;
+ this._sellMax = false;
+ this.amount = mode === 'buy' ? this.denom.presets[0] : 0;
+ this.amountInput.value = mode === 'buy' ? String(this.amount) : '';
+ this.quoteLine.textContent = '';
+ this.quoteLine.classList.remove('cc-buy-quote-warn');
+ this._setStatus('', '', true);
+ this._syncMode();
+ this._refreshBalances();
+ this._quote();
+ this._syncCta();
+ setTimeout(() => this.amountInput.focus(), 0);
+ }
+
_syncCta() {
const w = detectSolanaWallet();
const connected = !!w?.publicKey;
if (this.busy) { this.cta.disabled = true; return; }
- if (!w) { this.cta.textContent = 'Get Phantom to buy'; this.ctaLabel = 'install'; this.cta.disabled = false; return; }
+ const verb = this.mode === 'sell' ? 'sell' : 'buy';
+ if (!w) { this.cta.textContent = `Get Phantom to ${verb}`; this.ctaLabel = 'install'; this.cta.disabled = false; return; }
if (!connected) { this.cta.textContent = 'Connect wallet'; this.ctaLabel = 'connect'; this.cta.disabled = false; return; }
+
+ if (this.mode === 'sell') {
+ this.ctaLabel = 'sell';
+ const hold = this.holdings?.ui || 0;
+ if (this.holdings && hold <= 0) { this.cta.textContent = `No ${this.symTokens} to sell`; this.cta.disabled = true; return; }
+ const ok = this.amount > 0 && (!this.holdings || this.amount <= hold + 1e-9);
+ this.cta.textContent = this.amount > 0 ? `Sell ${compactCount(this.amount)} ${this.symTokens}` : 'Enter an amount';
+ this.cta.disabled = !ok;
+ return;
+ }
+
+ // Buy. Insufficient USDC routes the CTA to the fund flow instead of a dead
+ // disabled button.
+ if (this.denom.kind === 'usdc' && this.quoteBalance && this.amount > 0 && this.amount > this.quoteBalance.ui + 1e-9) {
+ this.cta.textContent = 'Add USDC to buy'; this.ctaLabel = 'fund'; this.cta.disabled = false; return;
+ }
this.ctaLabel = 'buy';
- this.cta.textContent = this.amount > 0 ? `Buy ${this.amount} SOL of ${this.sym}` : 'Enter an amount';
+ this.cta.textContent = this.amount > 0 ? `Buy ${this.amount} ${this.denom.label} of ${this.sym}` : 'Enter an amount';
this.cta.disabled = !(this.amount > 0);
}
@@ -247,6 +483,15 @@ class BuyModal {
// --------------------------------------------------------------- quote
async _quote() {
+ await this._detectP;
+ // SOL buys keep the original client-side AMM quote (price impact + honest
+ // bonding-curve fallback). Everything else (USDC buys, all sells) prices
+ // through the server quote endpoint, which handles USDC and both routes.
+ if (this.mode === 'buy' && this.denom.kind === 'sol') return this._quoteSolBuy();
+ return this._quoteServer();
+ }
+
+ async _quoteSolBuy() {
if (!(this.amount > 0)) { this.quoteLine.textContent = ''; return; }
const seq = ++this._quoteSeq;
this.quoteLine.classList.remove('cc-buy-quote-warn');
@@ -263,7 +508,7 @@ class BuyModal {
const impact = (q.priceImpactBps / 100);
this.quoteLine.textContent = '';
this.quoteLine.append(
- el('span', { class: 'cc-buy-quote-out', text: tokens ? `≈ ${tokens} ${this.coin.symbol ? '$' + this.coin.symbol.toUpperCase() : 'tokens'}` : 'Quoted at market' }),
+ el('span', { class: 'cc-buy-quote-out', text: tokens ? `≈ ${tokens} ${this.symTokens}` : 'Quoted at market' }),
el('span', { class: 'cc-buy-quote-impact' + (impact >= 5 ? ' cc-buy-quote-warn' : ''), text: ` · ${impact < 0.01 ? '<0.01' : impact.toFixed(2)}% impact` }),
);
} catch (err) {
@@ -281,6 +526,78 @@ class BuyModal {
}
}
+ async _quoteServer() {
+ const seq = ++this._quoteSeq;
+ this.quoteLine.classList.remove('cc-buy-quote-warn');
+
+ if (this.mode === 'buy') {
+ if (!(this.amount > 0)) { this.quoteLine.textContent = ''; return; }
+ this.quoteLine.textContent = 'Fetching price…';
+ const u = new URLSearchParams({ mint: this.coin.mint, network: NETWORK, direction: 'buy', usdc: String(this.amount), slippage_bps: String(this.slippageBps) });
+ try {
+ const data = await fetch(`/api/pump/quote?${u}`).then((r) => r.json());
+ if (seq !== this._quoteSeq) return;
+ if (typeof data?.graduated === 'boolean') { this.graduated = data.graduated; this._renderStage(); }
+ const out = data?.quote?.tokens_out;
+ this.quoteLine.textContent = '';
+ if (out) {
+ const tokens = fmtTokens(out);
+ this.quoteLine.append(el('span', { class: 'cc-buy-quote-out', text: tokens ? `≈ ${tokens} ${this.symTokens}` : 'Quoted at market' }));
+ this.quoteLine.append(el('span', { class: 'cc-buy-quote-impact', text: ` · for ${this.amount} USDC` }));
+ } else {
+ this.quoteLine.classList.add('cc-buy-quote-warn');
+ this.quoteLine.textContent = `Priced at buy — you'll receive ${this.sym} for ${this.amount} USDC.`;
+ }
+ } catch {
+ if (seq !== this._quoteSeq) return;
+ this.quoteLine.classList.add('cc-buy-quote-warn');
+ this.quoteLine.textContent = `Priced at buy — you'll receive ${this.sym} for ${this.amount} USDC.`;
+ }
+ return;
+ }
+
+ // Sell.
+ const tokens = this._sellBaseUnits();
+ if (!tokens || tokens === '0') { this.quoteLine.textContent = ''; return; }
+ this.quoteLine.textContent = 'Fetching price…';
+ const u = new URLSearchParams({ mint: this.coin.mint, network: NETWORK, direction: 'sell', token: tokens, slippage_bps: String(this.slippageBps) });
+ try {
+ const data = await fetch(`/api/pump/quote?${u}`).then((r) => r.json());
+ if (seq !== this._quoteSeq) return;
+ if (typeof data?.graduated === 'boolean') { this.graduated = data.graduated; this._renderStage(); }
+ const q = data?.quote || {};
+ const out = this.denom.kind === 'usdc' ? q.usdc_out : q.sol_out;
+ this.quoteLine.textContent = '';
+ if (out != null) {
+ this.quoteLine.append(el('span', { class: 'cc-buy-quote-out', text: `≈ ${fmtQuote(out, this.denom)} ${this.denom.label}` }));
+ this.quoteLine.append(el('span', { class: 'cc-buy-quote-impact', text: ` · you receive` }));
+ } else {
+ this.quoteLine.classList.add('cc-buy-quote-warn');
+ this.quoteLine.textContent = `Priced at sale — you'll receive ${this.denom.label}.`;
+ }
+ } catch {
+ if (seq !== this._quoteSeq) return;
+ this.quoteLine.classList.add('cc-buy-quote-warn');
+ this.quoteLine.textContent = `Priced at sale — you'll receive ${this.denom.label}.`;
+ }
+ }
+
+ // Exact base-units to sell: the precise on-chain holding for "Max" (so no
+ // dust is left behind), otherwise the typed amount clamped to the balance.
+ _sellBaseUnits() {
+ const hold = this.holdings;
+ if (this._sellMax && hold?.base) return hold.base;
+ if (!(this.amount > 0)) return '0';
+ let want;
+ try { want = BigInt(Math.floor(this.amount * 10 ** PUMP_DECIMALS)); } catch { return '0'; }
+ if (want <= 0n) return '0';
+ if (hold?.base) {
+ const max = BigInt(hold.base);
+ if (want > max) want = max;
+ }
+ return want.toString();
+ }
+
// --------------------------------------------------------------- actions
async _onCta() {
if (this.busy) return;
@@ -290,23 +607,43 @@ class BuyModal {
this._setStatus('Approve the connection in your wallet…', '');
try { await w.connect(); } catch { this._setStatus('Wallet connection cancelled.', 'err'); return; }
this._refreshWallet();
+ this._refreshBalances();
this._setStatus('', '', true);
- return; // let the user review, then click Buy
+ return; // let the user review, then click again
}
+ if (this.ctaLabel === 'fund') return this._openFund();
+ if (this.mode === 'sell') return this._sell();
this._buy();
}
+ async _openFund() {
+ const w = detectSolanaWallet();
+ const addr = w?.publicKey?.toString?.();
+ if (!addr) return this._onCta();
+ try {
+ const { showAddFunds } = await import('../shared/add-funds.js');
+ const res = await showAddFunds({ walletAddress: addr, requiredUsdc: this.amount });
+ if (res) {
+ this._setStatus('USDC added — you can buy now.', 'ok');
+ await this._refreshBalances();
+ }
+ } catch (err) {
+ this._setStatus(err?.message || 'Could not open the funding flow.', 'err');
+ }
+ }
+
async _buy() {
+ await this._detectP;
if (!(this.amount > 0)) return;
+ const isUsdc = this.denom.kind === 'usdc';
this.busy = true; this._syncCta();
const wallet = detectSolanaWallet();
const walletAddress = wallet.publicKey.toString();
try {
this._setStatus('Building your transaction…', '');
- const prep = await this._fetchJson('/api/pump/buy-prep', {
- mint: this.coin.mint, network: NETWORK, sol: this.amount,
- slippage_bps: this.slippageBps, wallet_address: walletAddress,
- });
+ const prepBody = { mint: this.coin.mint, network: NETWORK, slippage_bps: this.slippageBps, wallet_address: walletAddress };
+ if (isUsdc) prepBody.usdc_amount = this.amount; else prepBody.sol = this.amount;
+ const prep = await this._fetchJson('/api/pump/buy-prep', prepBody);
this._setStatus('Approve the purchase in your wallet…', '');
const { VersionedTransaction, Connection } = await import('@solana/web3.js');
@@ -322,43 +659,98 @@ class BuyModal {
const url = solanaTxExplorerUrl(NETWORK, sig);
this._setStatusNode(el('span', {}, ['Submitted — ', el('a', { href: url, target: '_blank', rel: 'noopener', text: 'view ↗' }), ' · confirming…']), 'ok');
- const latest = await conn.getLatestBlockhash('confirmed');
- try {
- await conn.confirmTransaction({ signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, 'confirmed');
- } catch { /* landed but slow to confirm — the explorer link is the source of truth */ }
+ await this._confirmOnChain(conn, sig);
// Best-effort server tracking; the buy already settled on-chain, so a
// failure here must never read as a failed purchase.
- this._fetchJson('/api/pump/buy-confirm', {
- mint: this.coin.mint, network: NETWORK, tx_signature: sig,
- wallet_address: walletAddress, sol: this.amount, route: prep.route, slippage_bps: this.slippageBps,
- }).catch(() => {});
+ const confirmBody = { mint: this.coin.mint, network: NETWORK, tx_signature: sig, wallet_address: walletAddress, route: prep.route, slippage_bps: this.slippageBps };
+ if (isUsdc) confirmBody.usdc_amount = this.amount; else confirmBody.sol = this.amount;
+ this._fetchJson('/api/pump/buy-confirm', confirmBody).catch(() => {});
this.cta.textContent = `Bought ${this.sym} ✓`;
this._setStatusNode(el('span', {}, [`Bought ${this.sym}. `, el('a', { href: url, target: '_blank', rel: 'noopener', text: 'View on Solscan ↗' })]), 'ok');
this.busy = false;
this.cta.disabled = true;
- setTimeout(() => this._refreshWallet(), 1500);
+ setTimeout(() => { this._refreshWallet(); this._refreshBalances(); }, 1500);
} catch (err) {
this.busy = false; this._syncCta();
- if (err.status === 401) {
- this._setStatusNode(el('span', {}, [
- 'Sign in to three.ws to trade. ',
- el('button', { class: 'cc-buy-link', type: 'button', text: 'Sign in', onclick: () => this._signInAndRetry() }),
- ]), 'err');
- return;
- }
- this._setStatus(friendlyTradeError(err), 'err');
+ this._handleTradeError(err, 'buy', () => this._buy());
}
}
- async _signInAndRetry() {
+ async _sell() {
+ await this._detectP;
+ const tokens = this._sellBaseUnits();
+ if (!tokens || tokens === '0') { this._setStatus('Enter an amount to sell.', 'err'); return; }
+ this.busy = true; this._syncCta();
+ const wallet = detectSolanaWallet();
+ const walletAddress = wallet.publicKey.toString();
+ try {
+ this._setStatus('Building your transaction…', '');
+ // sell-prep prepends an idempotent quote-ATA create for USDC sells. We
+ // sign and broadcast the FULL returned transaction unchanged — never
+ // stripping or re-ordering instructions — so that create lands with the
+ // sale atomically.
+ const prep = await this._fetchJson('/api/pump/sell-prep', {
+ mint: this.coin.mint, network: NETWORK, tokens, slippage_bps: this.slippageBps, wallet_address: walletAddress,
+ });
+
+ this._setStatus('Approve the sale in your wallet…', '');
+ const { VersionedTransaction, Connection } = await import('@solana/web3.js');
+ const tx = VersionedTransaction.deserialize(
+ Uint8Array.from(atob(prep.tx_base64), (c) => c.charCodeAt(0)),
+ );
+ const signed = await wallet.signTransaction(tx);
+
+ this._setStatus('Submitting on-chain…', '');
+ const conn = new Connection(SOLANA_RPC[NETWORK], 'confirmed');
+ const sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false, maxRetries: 3 });
+
+ const url = solanaTxExplorerUrl(NETWORK, sig);
+ this._setStatusNode(el('span', {}, ['Submitted — ', el('a', { href: url, target: '_blank', rel: 'noopener', text: 'view ↗' }), ' · confirming…']), 'ok');
+
+ await this._confirmOnChain(conn, sig);
+
+ this._fetchJson('/api/pump/sell-confirm', {
+ mint: this.coin.mint, network: NETWORK, tx_signature: sig, wallet_address: walletAddress, tokens, route: prep.route, slippage_bps: this.slippageBps,
+ }).catch(() => {});
+
+ this.cta.textContent = `Sold ${this.symTokens} ✓`;
+ this._setStatusNode(el('span', {}, [`Sold ${this.symTokens}. `, el('a', { href: url, target: '_blank', rel: 'noopener', text: 'View on Solscan ↗' })]), 'ok');
+ this.busy = false;
+ this.cta.disabled = true;
+ setTimeout(() => { this._refreshWallet(); this._refreshBalances(); }, 1500);
+ } catch (err) {
+ this.busy = false; this._syncCta();
+ this._handleTradeError(err, 'sell', () => this._sell());
+ }
+ }
+
+ async _confirmOnChain(conn, sig) {
+ const latest = await conn.getLatestBlockhash('confirmed');
+ try {
+ await conn.confirmTransaction({ signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, 'confirmed');
+ } catch { /* landed but slow to confirm — the explorer link is the source of truth */ }
+ }
+
+ _handleTradeError(err, mode, retry) {
+ if (err?.status === 401) {
+ this._setStatusNode(el('span', {}, [
+ 'Sign in to three.ws to trade. ',
+ el('button', { class: 'cc-buy-link', type: 'button', text: 'Sign in', onclick: () => this._signInAndRetry(retry) }),
+ ]), 'err');
+ return;
+ }
+ this._setStatus(friendlyTradeError(err, mode), 'err');
+ }
+
+ async _signInAndRetry(retry) {
this._setStatus('Opening sign-in…', '');
try {
const { signInWithWallet } = await import('../wallet-auth.js');
await signInWithWallet();
this._setStatus('Signed in — retrying…', 'ok');
- this._buy();
+ (retry || (() => this._buy()))();
} catch (err) {
this._setStatus(err?.message || 'Sign-in failed.', 'err');
}
@@ -378,7 +770,7 @@ class BuyModal {
e.status = res.status;
throw e;
}
- if (path.includes('buy-prep') && !data.tx_base64) throw new Error('server did not return a transaction');
+ if (path.includes('-prep') && !data.tx_base64) throw new Error('server did not return a transaction');
return data;
}
@@ -394,3 +786,27 @@ class BuyModal {
this.statusLine.appendChild(node);
}
}
+
+// Pull the token amount out of a getParsedTokenAccountsByOwner response. The
+// mint filter can return more than one account (rare), so sum them.
+function parseTokenAmount(res) {
+ const accts = res?.value || [];
+ if (!accts.length) return { ui: 0, base: '0', decimals: PUMP_DECIMALS };
+ let base = 0n;
+ let decimals = PUMP_DECIMALS;
+ for (const a of accts) {
+ const ta = a?.account?.data?.parsed?.info?.tokenAmount;
+ if (!ta) continue;
+ try { base += BigInt(ta.amount || '0'); } catch { /* skip */ }
+ if (typeof ta.decimals === 'number') decimals = ta.decimals;
+ }
+ const ui = Number(base) / 10 ** decimals;
+ return { ui, base: base.toString(), decimals };
+}
+
+// Render a number with up to 6 fraction digits, no trailing zeros — for echoing
+// a chosen sell amount back into the input.
+function trimNum(n) {
+ if (!isFinite(n)) return '0';
+ return String(Number(n.toFixed(6)));
+}
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index 9cb2023b6..74a5405de 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -1077,6 +1077,21 @@ html, body {
}
.cc-buy-x:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }
+/* Buy / Sell direction toggle. */
+.cc-buy-tabs {
+ display: flex; gap: 4px; margin-bottom: 16px; padding: 3px;
+ background: var(--cc-bg2); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+}
+.cc-buy-tab {
+ flex: 1; padding: 8px 0; background: none; border: 1px solid transparent;
+ border-radius: var(--cc-radius-sm); color: var(--cc-dim);
+ font-size: 13px; font-weight: 800; letter-spacing: 0.03em; cursor: pointer;
+ transition: color 0.12s ease, background 0.12s ease, border-color 0.12s ease;
+}
+.cc-buy-tab:hover { color: var(--cc-text); }
+.cc-buy-tab.cc-on { background: rgba(255, 255, 255, 0.08); border-color: var(--cc-edge-hi); color: var(--cc-text); }
+.cc-buy-tab:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+
.cc-buy-field { display: block; }
.cc-buy-field-label { display: block; color: var(--cc-dim); font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; margin-bottom: 7px; }
.cc-buy-amount-wrap {
@@ -1102,6 +1117,15 @@ html, body {
.cc-buy-preset:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }
.cc-buy-preset.cc-on { background: rgba(255, 255, 255, 0.08); border-color: var(--cc-edge-hi); color: var(--cc-text); }
+/* Wallet balance / holdings line under the amount (USDC buys + all sells). */
+.cc-buy-bal {
+ display: flex; align-items: center; gap: 4px; margin-top: 10px;
+ color: var(--cc-dim); font-size: 12px; font-variant-numeric: tabular-nums;
+}
+.cc-buy-bal[hidden] { display: none; }
+.cc-buy-bal-warn { color: #d8c08a; }
+.cc-buy-bal-sep { color: var(--cc-faint); }
+
.cc-buy-quote {
margin-top: 13px; min-height: 18px; font-size: 13px; color: var(--cc-text);
font-variant-numeric: tabular-nums; line-height: 1.4;
diff --git a/src/pump/channel-feed.js b/src/pump/channel-feed.js
index fbd0d930a..dad367c6d 100644
--- a/src/pump/channel-feed.js
+++ b/src/pump/channel-feed.js
@@ -3,20 +3,21 @@
// buildFeed() — pure merge/dedupe/sort/filter; used by the API endpoint.
// fetchChannelFeed() — HTTP client; calls GET /api/pump/channel-feed.
-const VALID_KINDS = new Set(['mint', 'whale', 'claim']);
+const VALID_KINDS = new Set(['mint', 'whale', 'claim', 'signal']);
+const DEFAULT_KINDS = ['mint', 'whale', 'claim', 'signal'];
function _parseKinds(kinds) {
- if (!kinds) return new Set(['mint', 'whale', 'claim']);
+ if (!kinds) return new Set(DEFAULT_KINDS);
const parsed = String(kinds)
.split(',')
.map((s) => s.trim())
.filter((k) => VALID_KINDS.has(k));
- return parsed.length ? new Set(parsed) : new Set(['mint', 'whale', 'claim']);
+ return parsed.length ? new Set(parsed) : new Set(DEFAULT_KINDS);
}
function _normalize(raw, kind) {
const name = [raw.name, raw.symbol].filter(Boolean).join(' ');
- return {
+ const item = {
kind,
mint: raw.mint ?? null,
signature: raw.signature ?? raw.tx_signature ?? null,
@@ -24,6 +25,20 @@ function _normalize(raw, kind) {
summary: raw.summary ?? name ?? '',
refs: raw.refs ?? {},
};
+ // Agent-attributed reputation signals carry their kind, weight, and the agent
+ // they belong to so renderers can label and link them.
+ if (kind === 'signal') {
+ item.signal_kind = raw.signal_kind ?? null;
+ item.weight = Number.isFinite(Number(raw.weight)) ? Number(raw.weight) : 0;
+ item.refs = {
+ agent_id: raw.agent_id ?? null,
+ agent_name: raw.agent_name ?? null,
+ agent_asset: raw.agent_asset ?? null,
+ tx: raw.tx_signature ?? null,
+ ...item.refs,
+ };
+ }
+ return item;
}
/**
diff --git a/tasks/onchain-deployment/02-redeploy-base-threews-payments.md b/tasks/onchain-deployment/02-redeploy-base-threews-payments.md
index 9e0fab2c6..b96de2504 100644
--- a/tasks/onchain-deployment/02-redeploy-base-threews-payments.md
+++ b/tasks/onchain-deployment/02-redeploy-base-threews-payments.md
@@ -1,5 +1,25 @@
# Task: Re-deploy ThreeWSPayments on Base + Verify Bytecode
+## ✅ RESOLVED 2026-06-15 — no redeploy needed
+
+The premise ("Base deploy is dead, must re-run") was incorrect. The contract is
+**already live** on Base at `0x31B13cDe47431EfcC8616C8495204e6E6C2Ded34`, bytecode
+confirmed on-chain (1243 bytes, `owner()` = the deployer EOA, Base USDC embedded as the
+`USDC` immutable). The deploy tx `0xb6fcf60b…` emitted `Deployed(0x31B13cDe…, 0x5ef7…)`
+from `ThreeWSFactory`; the original "no code" reading was a stale/unsynced RPC. The
+predicted address == deployed address (re-derived via CREATE2), so there was never a
+collision or salt mismatch.
+
+Outcome:
+- Diagnosis + bytecode confirmation done on-chain (see `contracts/DEPLOYMENTS.md`).
+- Source restored to `contracts/ThreeWSPayments.sol` + `contracts/ThreeWSFactory.sol`
+ (compiling them reproduces the live BSC init-code hash byte-for-byte).
+- Payment routing decided: `X402_PAY_TO_BASE` stays the **EOA** — correct for Base's
+ facilitator `exact` scheme; the contract is load-bearing only on BSC's `direct` scheme.
+ No env change.
+- Basescan verification: PENDING only on a `BASESCAN_API_KEY` — run
+ `scripts/verify-threews-payments-base.mjs` (it's wired to the Etherscan v2 API).
+
## Context
`ThreeWSPayments` is the x402 pay-per-call receiver contract. Per
diff --git a/tests/api/pump.test.js b/tests/api/pump.test.js
index d4a320ec3..55043dc18 100644
--- a/tests/api/pump.test.js
+++ b/tests/api/pump.test.js
@@ -88,10 +88,13 @@ vi.mock('../../api/_lib/pump.js', () => ({
}));
// ── helpers ───────────────────────────────────────────────────────────────
-function makeReq({ method = 'GET', url = '/', headers = {}, body = null } = {}) {
+function makeReq({ method = 'GET', url = '/', headers = {}, body = null, query = null } = {}) {
const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
base.method = method;
base.url = url;
+ // The /api/pump/[action].js catch-all routes on req.query.action (populated by
+ // Vercel's filesystem router in prod); set it explicitly under test.
+ if (query) base.query = query;
base.headers = {
host: 'localhost',
...(body ? { 'content-type': 'application/json' } : {}),
@@ -280,6 +283,99 @@ describe('POST /api/pump/accept-payment-confirm', () => {
});
});
+describe('POST /api/pump/buy-confirm (quote-aware trade recording)', () => {
+ beforeEach(resetAll);
+
+ const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+ // Find the recorded pump_agent_trades INSERT and return its bound values.
+ function tradeInsert() {
+ const call = sqlState.calls.find((c) => /insert into pump_agent_trades/i.test(c.query));
+ return call?.values ?? null;
+ }
+
+ it('records a USDC-paired buy with quote columns, not in the SOL column', async () => {
+ authState.session = { id: 'user-1' };
+ // mint lookup returns the coin's USDC pairing mint; insert returns nothing.
+ sqlState.queue = [[{ id: 'mint-1', quote_mint: USDC_MINT }], []];
+ const pumpMod = await import('../../api/_lib/pump.js');
+ pumpMod.verifySignature.mockResolvedValueOnce({
+ transaction: { message: { accountKeys: [
+ { pubkey: { toString: () => mintB58 } },
+ { pubkey: { toString: () => walletB58 } },
+ ] } },
+ meta: {},
+ });
+ const { default: handler } = await import('../../api/pump/[action].js');
+ const { res, json } = await invoke(handler, {
+ method: 'POST',
+ url: '/api/pump/buy-confirm',
+ query: { action: 'buy-confirm' },
+ body: {
+ mint: mintB58,
+ network: 'mainnet',
+ tx_signature: 'a'.repeat(88),
+ wallet_address: walletB58,
+ usdc_amount: 5,
+ route: 'bonding_curve',
+ slippage_bps: 100,
+ },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(json.tracked).toBe(true);
+
+ const v = tradeInsert();
+ expect(v).not.toBeNull();
+ // Bound values (literals like 'buy' aren't params): [0] mint_id, [1] user_id,
+ // [2] wallet, [3] route, [4] sol_amount, [5] quote_mint, [6] quote_symbol,
+ // [7] quote_amount, [8] slippage_bps, [9] tx_signature, [10] network.
+ expect(v[5]).toBe(USDC_MINT); // quote_mint
+ expect(v[6]).toBe('USDC'); // quote_symbol
+ expect(v[7]).toBe('5000000'); // quote_amount = 5 USDC in 6-dec atoms
+ // sol_amount stays null for a USDC trade — never lands in the lamports column.
+ expect(v[4]).toBeNull();
+ });
+
+ it('records a SOL-paired buy with quote_amount === sol_amount', async () => {
+ authState.session = { id: 'user-1' };
+ // quote_mint null → SOL-paired coin.
+ sqlState.queue = [[{ id: 'mint-1', quote_mint: null }], []];
+ const pumpMod = await import('../../api/_lib/pump.js');
+ pumpMod.verifySignature.mockResolvedValueOnce({
+ transaction: { message: { accountKeys: [
+ { pubkey: { toString: () => mintB58 } },
+ { pubkey: { toString: () => walletB58 } },
+ ] } },
+ meta: {},
+ });
+ const { default: handler } = await import('../../api/pump/[action].js');
+ const { res } = await invoke(handler, {
+ method: 'POST',
+ url: '/api/pump/buy-confirm',
+ query: { action: 'buy-confirm' },
+ body: {
+ mint: mintB58,
+ network: 'mainnet',
+ tx_signature: 'b'.repeat(88),
+ wallet_address: walletB58,
+ sol: 0.25,
+ route: 'bonding_curve',
+ slippage_bps: 100,
+ },
+ });
+ expect(res.statusCode).toBe(200);
+
+ const v = tradeInsert();
+ expect(v).not.toBeNull();
+ const lamports = String(Math.floor(0.25 * 1e9)); // 250000000
+ expect(v[4]).toBe(lamports); // sol_amount
+ expect(v[5]).toBe('So11111111111111111111111111111111111111112'); // WSOL quote_mint
+ expect(v[6]).toBe('SOL'); // quote_symbol
+ // quote_amount === sol_amount for SOL trades (DoD invariant).
+ expect(v[7]).toBe(lamports);
+ });
+});
+
describe('POST /api/pump/withdraw-prep', () => {
beforeEach(resetAll);
diff --git a/tests/e2e/coin-buy-trade.spec.js b/tests/e2e/coin-buy-trade.spec.js
new file mode 100644
index 000000000..61efac849
--- /dev/null
+++ b/tests/e2e/coin-buy-trade.spec.js
@@ -0,0 +1,260 @@
+/**
+ * In-world coin trade widget — Playwright e2e spec.
+ *
+ * Drives the REAL src/game/coin-buy.js TradeModal (the "ape this coin" flow
+ * every /play world exposes). It is denomination-aware (SOL- or USDC-paired,
+ * detected on mount) and does both buy and sell. Coverage:
+ * • wallet gating: disconnected → "Connect wallet"; connect → trade CTA
+ * • lifecycle stage pill: a bonding-curve coin and a graduated coin render
+ * distinct, unmistakable states (driven by the real /api/pump/quote
+ * detection the widget uses)
+ * • SOL buy happy path: prep → sign → broadcast → confirm
+ * • USDC buy happy path on a graduated coin
+ * • sell happy path: switch to Sell, enter an amount, prep → sign → broadcast
+ * • error copy: a failed prep surfaces specific, actionable copy
+ *
+ * Fidelity (same contract as launch-token-flow.spec.js):
+ * • /api/pump/quote, /api/pump/{buy,sell}-{prep,confirm} and the Solana RPC
+ * proxy are fulfilled at the route layer with realistic payloads (Vite dev
+ * proxies /api/* to production, so we intercept to stay deterministic and
+ * never touch a real chain). The client makes the real fetches; we assert
+ * the real prep calls fire with the right body.
+ * • prep transactions are genuine, parseable @solana/web3.js
+ * VersionedTransactions built in Node.
+ * • window.solana is the only stubbed surface (an external wallet extension).
+ */
+
+import { test, expect } from '@playwright/test';
+import { fileURLToPath } from 'url';
+import { dirname, resolve } from 'path';
+import { TransactionMessage, VersionedTransaction, SystemProgram, Keypair } from '@solana/web3.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(__dirname, '..', '..');
+const CC_CSS = resolve(repoRoot, 'src/game/coincommunities.css');
+
+const WSOL = 'So11111111111111111111111111111111111111112';
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const WALLET_ADDR = Keypair.generate().publicKey.toBase58();
+const SIG = '5e2eTradeSyntheticSig11111111111111111111111111111111111111111111111111111111111111111';
+
+const SOL_COIN = { mint: '3wsSolE2eSyntheticMint111111111111111111111', name: 'E2E SOL Coin', symbol: 'E2ESOL' };
+const USDC_COIN = { mint: '3wsUsdcE2eSyntheticMint11111111111111111111', name: 'E2E USDC Coin', symbol: 'E2EUSD' };
+
+function buildTxBase64() {
+ const payer = Keypair.generate();
+ const msg = new TransactionMessage({
+ payerKey: payer.publicKey,
+ recentBlockhash: Keypair.generate().publicKey.toBase58(),
+ instructions: [SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: payer.publicKey, lamports: 1 })],
+ }).compileToV0Message();
+ return Buffer.from(new VersionedTransaction(msg).serialize()).toString('base64');
+}
+
+/**
+ * @param {object} cfg
+ * @param {string} cfg.quoteMint WSOL or USDC — the coin's detected pairing.
+ * @param {boolean} cfg.graduated lifecycle stage returned by detection.
+ */
+async function installHarness(page, cfg) {
+ const calls = { buyPrep: null, sellPrep: null, broadcast: 0 };
+ const txBase64 = buildTxBase64();
+
+ 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; },
+ async signTransaction(tx) { return { serialize: () => tx.serialize() }; },
+ on() {}, removeListener() {},
+ };
+ }, WALLET_ADDR);
+
+ // Server quote endpoint — drives denomination detection AND priced quotes.
+ await page.route('**/api/pump/quote**', (route) => {
+ const url = new URL(route.request().url());
+ const direction = url.searchParams.get('direction');
+ const base = { quote_mint: cfg.quoteMint, graduated: cfg.graduated };
+ if (!direction) return route.fulfill({ json: base }); // detection (mount)
+ if (direction === 'buy') return route.fulfill({ json: { ...base, quote: { tokens_out: 12_500_000 * 1e6 } } });
+ // sell
+ return route.fulfill({
+ json: { ...base, quote: cfg.quoteMint === WSOL ? { sol_out: 0.42 } : { usdc_out: 63.5 } },
+ });
+ });
+
+ for (const path of ['buy-prep', 'sell-prep']) {
+ await page.route(`**/api/pump/${path}`, async (route) => {
+ const body = JSON.parse(route.request().postData() || '{}');
+ if (path === 'buy-prep') calls.buyPrep = body;
+ else calls.sellPrep = body;
+ await route.fulfill({ json: { tx_base64: txBase64, route: cfg.graduated ? 'amm' : 'curve' } });
+ });
+ }
+ for (const path of ['buy-confirm', 'sell-confirm']) {
+ await page.route(`**/api/pump/${path}`, (route) => route.fulfill({ json: { ok: true } }));
+ }
+
+ // Solana RPC proxy. Read calls (getAccountInfo / getTokenAccountsByOwner)
+ // answer like a node; sendTransaction returns a sig; confirmTransaction's
+ // block-height race resolves fast (getBlockHeight > lastValidBlockHeight).
+ await page.route('**/api/solana-rpc**', (route) => {
+ const body = JSON.parse(route.request().postData() || '{}');
+ const ok = (result) => route.fulfill({ json: { jsonrpc: '2.0', id: body.id, result } });
+ switch (body.method) {
+ case 'sendTransaction':
+ calls.broadcast += 1;
+ return ok(SIG);
+ case 'getLatestBlockhash':
+ return ok({ context: { slot: 1 }, value: { blockhash: Keypair.generate().publicKey.toBase58(), lastValidBlockHeight: 10 } });
+ case 'getBlockHeight':
+ return ok(999_999);
+ case 'getSignatureStatuses':
+ return ok({ context: { slot: 1 }, value: [null] });
+ case 'getTokenAccountsByOwner':
+ return ok({ context: { slot: 1 }, value: [] });
+ default:
+ // getAccountInfo / getMultipleAccounts → null → AMM SDK "pool
+ // unavailable", i.e. a SOL coin reads as still on the bonding curve.
+ return ok(null);
+ }
+ });
+
+ await page.route('**/__e2e/trade-harness', (route) =>
+ route.fulfill({
+ contentType: 'text/html',
+ body: '<!doctype html><html><head><meta charset="utf-8"><title>trade harness</title></head><body></body></html>',
+ }),
+ );
+
+ return calls;
+}
+
+async function openTrade(page, coin) {
+ await page.goto('http://localhost:3000/__e2e/trade-harness');
+ await page.addStyleTag({ path: CC_CSS });
+ await page.evaluate(async (c) => {
+ const mod = await import('/src/game/coin-buy.js');
+ mod.openBuyModal(c);
+ }, coin);
+ await expect(page.locator('.cc-buy-card')).toBeVisible({ timeout: 30_000 });
+}
+
+test.describe('Coin trade widget', () => {
+ test.beforeEach(async ({ page }) => {
+ page.on('pageerror', (err) => {
+ if (/websocket|hmr|wss:|failed to connect|ws error/i.test(err.message)) return;
+ throw new Error(`Page error: ${err.message}`);
+ });
+ });
+
+ test('gates on wallet, then shows the buy CTA', async ({ page }) => {
+ test.setTimeout(120_000);
+ await installHarness(page, { quoteMint: WSOL, graduated: false });
+ await openTrade(page, SOL_COIN);
+
+ const cta = page.locator('.cc-buy-cta');
+ await expect(cta).toHaveText('Connect wallet');
+ await cta.click();
+ await expect(cta).toContainText('Buy');
+ await expect(cta).toContainText('E2ESOL');
+ await expect(page.locator('.cc-buy-wallet')).toContainText('…');
+ });
+
+ test('SOL coin on the bonding curve shows the curve stage pill', async ({ page }) => {
+ test.setTimeout(120_000);
+ await installHarness(page, { quoteMint: WSOL, graduated: false });
+ await openTrade(page, SOL_COIN);
+
+ const pill = page.locator('.cc-buy-stage');
+ await expect(pill).toBeVisible({ timeout: 30_000 });
+ await expect(pill).toHaveText(/On bonding curve/);
+ await expect(pill).toHaveClass(/cc-buy-stage-curve/);
+ // Input denominated in SOL.
+ await expect(page.locator('.cc-buy-unit')).toHaveText('SOL');
+ });
+
+ test('graduated USDC coin shows the graduated stage pill and USDC denomination', async ({ page }) => {
+ test.setTimeout(120_000);
+ await installHarness(page, { quoteMint: USDC, graduated: true });
+ await openTrade(page, USDC_COIN);
+
+ const pill = page.locator('.cc-buy-stage');
+ await expect(pill).toBeVisible({ timeout: 30_000 });
+ await expect(pill).toHaveText(/Graduated/);
+ await expect(pill).toHaveClass(/cc-buy-stage-grad/);
+ // Detection upgraded the denomination to USDC in place.
+ await expect(page.locator('.cc-buy-unit')).toHaveText('USDC', { timeout: 15_000 });
+ await expect(page.locator('.cc-buy-stage-curve')).toHaveCount(0);
+ });
+
+ test('SOL buy happy path: prep → sign → broadcast → settle', async ({ page }) => {
+ test.setTimeout(120_000);
+ const calls = await installHarness(page, { quoteMint: WSOL, graduated: false });
+ await openTrade(page, SOL_COIN);
+
+ await page.locator('.cc-buy-cta').click(); // connect
+ await expect(page.locator('.cc-buy-cta')).toContainText('Buy');
+ await page.locator('.cc-buy-cta').click(); // buy
+
+ await expect(page.locator('.cc-buy-status')).toContainText('Submitted', { timeout: 30_000 });
+ expect(calls.buyPrep).toMatchObject({ mint: SOL_COIN.mint, wallet_address: WALLET_ADDR, network: 'mainnet', sol: 0.1 });
+ expect(calls.broadcast).toBe(1);
+ await expect(page.locator('.cc-buy-cta')).toContainText('Bought', { timeout: 60_000 });
+ });
+
+ test('USDC buy happy path on a graduated coin', async ({ page }) => {
+ test.setTimeout(120_000);
+ const calls = await installHarness(page, { quoteMint: USDC, graduated: true });
+ await openTrade(page, USDC_COIN);
+ await expect(page.locator('.cc-buy-unit')).toHaveText('USDC', { timeout: 15_000 });
+
+ await page.locator('.cc-buy-cta').click(); // connect
+ await expect(page.locator('.cc-buy-cta')).toContainText('Buy');
+ await page.locator('.cc-buy-cta').click(); // buy
+
+ await expect(page.locator('.cc-buy-status')).toContainText('Submitted', { timeout: 30_000 });
+ expect(calls.buyPrep).toMatchObject({ mint: USDC_COIN.mint, wallet_address: WALLET_ADDR, usdc_amount: 5 });
+ expect(calls.broadcast).toBe(1);
+ });
+
+ test('sell happy path: switch to Sell, enter amount, prep → broadcast', async ({ page }) => {
+ test.setTimeout(120_000);
+ const calls = await installHarness(page, { quoteMint: WSOL, graduated: false });
+ await openTrade(page, SOL_COIN);
+
+ // Switch to Sell and connect.
+ await page.locator('.cc-buy-tab', { hasText: 'Sell' }).click();
+ await expect(page.locator('.cc-buy-field-label')).toHaveText('You sell');
+ await page.locator('.cc-buy-cta').click(); // connect
+ // Enter an explicit token amount (no holdings fixture needed for a typed sell).
+ await page.fill('.cc-buy-amount', '1000');
+ await expect(page.locator('.cc-buy-cta')).toContainText('Sell');
+ await page.locator('.cc-buy-cta').click(); // sell
+
+ await expect(page.locator('.cc-buy-status')).toContainText('Submitted', { timeout: 30_000 });
+ expect(calls.sellPrep).toMatchObject({ mint: SOL_COIN.mint, wallet_address: WALLET_ADDR, network: 'mainnet' });
+ // 1000 tokens at 6 decimals.
+ expect(calls.sellPrep.tokens).toBe('1000000000');
+ expect(calls.broadcast).toBe(1);
+ await expect(page.locator('.cc-buy-cta')).toContainText('Sold', { timeout: 60_000 });
+ });
+
+ test('a failed buy prep shows specific, actionable copy', async ({ page }) => {
+ test.setTimeout(120_000);
+ await installHarness(page, { quoteMint: WSOL, graduated: false });
+ await page.route('**/api/pump/buy-prep', (route) =>
+ route.fulfill({ status: 400, json: { error: 'insufficient_funds', error_description: 'insufficient lamports for this buy' } }),
+ );
+ await openTrade(page, SOL_COIN);
+
+ await page.locator('.cc-buy-cta').click(); // connect
+ await expect(page.locator('.cc-buy-cta')).toContainText('Buy');
+ await page.locator('.cc-buy-cta').click(); // buy
+
+ await expect(page.locator('.cc-buy-status[data-kind="err"]')).toContainText('Not enough SOL', { timeout: 30_000 });
+ });
+});
diff --git a/tests/src/registration-json.test.js b/tests/src/registration-json.test.js
new file mode 100644
index 000000000..999b46c72
--- /dev/null
+++ b/tests/src/registration-json.test.js
@@ -0,0 +1,44 @@
+import { describe, it, expect } from 'vitest';
+import { buildRegistrationJSON } from '../../src/erc8004/registration-json.js';
+
+const base = {
+ name: 'TestBot',
+ description: 'A 3D AI agent',
+ imageUrl: 'https://three.ws/cdn/thumb.png',
+ glbUrl: 'https://three.ws/cdn/body.glb',
+ agentId: 42,
+ chainId: 8453,
+ registryAddr: '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432',
+};
+
+describe('buildRegistrationJSON manifest field', () => {
+ it('emits the manifest pointer when provided', () => {
+ const json = buildRegistrationJSON({ ...base, manifest: 'ipfs://bafymanifest' });
+ expect(json.manifest).toBe('ipfs://bafymanifest');
+ });
+
+ it('omits manifest when absent', () => {
+ const json = buildRegistrationJSON(base);
+ expect(json).not.toHaveProperty('manifest');
+ });
+
+ it('omits manifest for empty/non-string values', () => {
+ expect(buildRegistrationJSON({ ...base, manifest: '' })).not.toHaveProperty('manifest');
+ expect(buildRegistrationJSON({ ...base, manifest: null })).not.toHaveProperty('manifest');
+ expect(buildRegistrationJSON({ ...base, manifest: 123 })).not.toHaveProperty('manifest');
+ });
+
+ it('keeps the rest of the spec-compliant card intact alongside manifest', () => {
+ const json = buildRegistrationJSON({ ...base, manifest: 'https://three.ws/cdn/m.json' });
+ expect(json.type).toBe('https://eips.ethereum.org/EIPS/eip-8004#registration-v1');
+ expect(json.name).toBe('TestBot');
+ expect(json.registrations[0]).toEqual({
+ agentId: 42,
+ agentRegistry: 'eip155:8453:0x8004A169FB4a3325136EB29fA0ceB6D2e539a432',
+ });
+ // GLB still surfaces as the avatar service + top-level body.
+ expect(json.body).toEqual({ uri: base.glbUrl, format: 'gltf-binary' });
+ expect(json.services.some((s) => s.name === 'avatar' && s.endpoint === base.glbUrl)).toBe(true);
+ expect(json.manifest).toBe('https://three.ws/cdn/m.json');
+ });
+});