Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Solana attestation module + agent registration script, pump dashboard redesign, pump alert + parity test suites, devnet smoke runbook
nirholase3b3b12c1be7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5ba1a98fa..12e1b0ebb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,9 +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]`+- **Agent reputation now reflects a real pump.fun track record** — An agent's pump.fun behavior now feeds its reputation and shows on its passport. When the wallet behind an agent graduates a token, claims creator fees, makes a whale-sized buy, or launches a coin, that moment is recorded as a typed signal — graduating a token counts for more than a routine claim, and a flagged or brand-new-account claim counts against. These signals roll up into the agent's Solana reputation score and appear on the public agent passport, readable by anyone without a wallet. The live pump.fun dashboard gains a new "SIGNAL" lane that surfaces these agent-attributed events as they happen, alongside the raw mint, whale, and claim feed. The processor behind this used to sit idle unless an optional external service was configured; it now runs continuously off the platform's own live pump.fun stream with no external dependency, records only genuinely new events so nothing is double-counted, and attributes each one to the agent behind the wallet. (`/pump-dashboard`) `[improvement, fix]`- **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]`+- **Buy and sell USDC-paired coins straight from the trade widget** — The in-world trade widget now speaks both currencies. Open Buy on a coin and the widget reads its real pairing from the chain: a SOL coin asks for SOL exactly as before, while a USDC-paired coin denominates the amount in USDC, shows your wallet's USDC balance, and prices and settles the trade in USDC. A new Sell tab lets you sell a coin you hold back to its quote asset — pick 25%, 50%, or Max of your balance, see the live payout, and sign once; for USDC coins the payout account is opened for you automatically in the same transaction. Every state is handled: not enough USDC offers a one-tap Add-funds flow, a moved price explains your slippage, and a cancelled signature is quietly acknowledged. The whole flow is your own wallet, signed in your browser, with a Solscan link the moment it lands. (`/play`) `[feature]`+- **Clearer launch & trade errors, and a graduated badge on coins** — When a token launch or an in-world trade can't go through, the app now tells you exactly why and what to do next — "Not enough SOL to cover the launch + network fees," "Price moved beyond your slippage limit," "You cancelled the signature in your wallet," or "Couldn't reach the Solana network" — instead of a single catch-all "Connection error." Coins also show their lifecycle at a glance: the trade panel carries a badge marking whether a coin is still on its bonding curve or has graduated to the PumpSwap AMM, so a graduated coin is unmistakable. Backed by new end-to-end browser tests that drive the full four-step launch flow and the buy/sell widget so this conversion path can't silently break. (`/pump-dashboard`) `[improvement]`- **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]`+- **Live coin status — price, market cap and graduation — now unified across the platform** — The launches feed, agent profile token panels, and the in-world agent coin card now share one live coin-status display, so every place that shows a coin reads the same numbers from the same source. Launch cards now stream the coin's real logo, USD price, market cap, a graduation progress ring and time since launch — not just market cap — with the orbital fingerprint as a placeholder until the logo loads. Agent profiles show a live price-and-graduation chip in the token panel and per-coin market caps in the launch history, and the agent home card's market readout is now consistent with the rest of the platform. Each card refreshes on its own and degrades gracefully to a Retry if pump.fun is briefly unreachable. (`/launches`) `[improvement]`+- **On-chain model validation for Solana agents** — Solana agents now get the same verifiable, on-chain glTF/model validation that EVM agents get from the ValidationRegistry — no contract to deploy. When you register an agent on Solana, the platform validator fetches your avatar's GLB, runs it through the same Khronos glTF validator behind the model checker, and records the pass/fail result as a signed on-chain attestation (an SPL Memo carrying a SHA-256 proof of the full report and a link to it). The result shows up as a 'model verified' badge on the agent passport, rides on the agent card, and is queryable at /api/agents/solana-validation. Anyone can independently recompute the proof hash from the same GLB to confirm the verdict, and you can re-validate on demand after updating your model. Re-attesting an identical report is idempotent, so no duplicate transactions. `[feature, security]`+- **Pump dashboard alerts now run server-side — fire across devices even with the tab closed** — Alert rules moved from your browser to our servers, so they fire whether or not a dashboard tab is open and follow you across every device you sign in on. Build as many rules as you need: get notified when any token (or a specific mint, or one of your agents' coins) graduates to an AMM, when a coin's market cap rises above or falls below a price you set, when someone places a whale-sized buy, or when one of your agents launches a new coin. Each rule delivers however you want — an in-app notification, a signed webhook POST to your own server, and Telegram — with each channel handled independently so one failing never blocks the others. Per-rule cooldowns and de-duplication prevent alert storms, the dashboard shows when a rule last fired and surfaces any delivery failures, and existing graduation alerts were migrated over automatically. (`/pump-dashboard`) `[feature]`- **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]`@@ -17,7 +23,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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 can now register itself on-chain on Solana** — Alongside its ERC-8004 identity, three.ws can now mint its own agent on Solana — as a Metaplex Core asset in the official "three.ws Agents" collection, exactly the way agents you deploy through the platform are registered. A one-command tool builds the platform's 3D Agent Card, verifies the avatar's SHA-256 against the exact GLB bytes served (so the model can't be silently swapped), pins the metadata, mints the asset into the collection, and writes the result back into the public discovery documents at three.ws/.well-known so any wallet, explorer, or agent can resolve and verify three.ws. The discovery card and its schema now carry Solana identities (CAIP-10) alongside EVM ones, and the platform agent's on-chain badge links straight to its Solana passport. (`/.well-known/agent-registration.json`) `[feature, infra]`- **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]`+- **USDC-paired agent coins now record and display correct trade amounts** — Coins launched against USDC are now tracked in the right currency end to end. Every buy and sell records which quote asset it actually used and how much of it moved — USDC amounts in USDC, SOL amounts in SOL — instead of quietly storing a USDC trade as if it were SOL and reporting a price and market cap that were off by orders of magnitude. Portfolios now subtotal holdings separately by quote asset, so your SOL positions and USDC positions each get their own value, cost basis, and unrealized P&L with no more mixing of mismatched units. Existing SOL trades are unchanged, and historical rows were backfilled as SOL-paired so nothing shifts. `[fix, feature]`## 2026-06-14diff --git a/api/_lib/migrations/2026-06-15-pump-alert-rules.sql b/api/_lib/migrations/2026-06-15-pump-alert-rules.sqlindex 7652d3ee1..6580aee56 100644--- a/api/_lib/migrations/2026-06-15-pump-alert-rules.sql+++ b/api/_lib/migrations/2026-06-15-pump-alert-rules.sql@@ -6,8 +6,10 @@-- cron against real persisted data sources, so they fire across devices even-- with no dashboard tab open.----- NOTE: this file is applied by scripts/apply-migrations.mjs, which splits on--- ';' at line ends. Keep every statement split-safe (no DO/$$ blocks).+-- NOTE: this file is applied by scripts/apply-migrations.mjs as a single+-- multi-statement body via the websocket Pool (pool.query). Statements are kept+-- simple and split-safe (no DO/$$ blocks) so the file also survives any naive+-- split-on-';' fallback.create table if not exists pump_alert_rules (id uuid primary key default gen_random_uuid(),diff --git a/api/_lib/pump-alert-eval.js b/api/_lib/pump-alert-eval.jsindex 43241626f..cfbecac5d 100644--- a/api/_lib/pump-alert-eval.js+++ b/api/_lib/pump-alert-eval.js@@ -93,7 +93,9 @@ export function isWhaleBuy(rule, trade) {* @returns {{ fire: boolean, nextState: { side: 'over'|'under' }, reason: string }}*/export function evaluatePriceRule(rule, currentMcapUsd, lastState = {}) {- const mcap = Number(currentMcapUsd);+ // Number(null) is 0 (finite), so guard null/undefined explicitly — a missing+ // price must hit the no-price branch, not read as a $0 market cap.+ const mcap = currentMcapUsd == null ? NaN : Number(currentMcapUsd);const threshold = Number(rule.threshold);// Without a live price we can't decide — preserve prior state, don't fire.if (!Number.isFinite(mcap) || !Number.isFinite(threshold) || threshold <= 0) {diff --git a/api/_lib/pump-alert-runner.js b/api/_lib/pump-alert-runner.jsindex 9e5099853..4a050ddac 100644--- a/api/_lib/pump-alert-runner.js+++ b/api/_lib/pump-alert-runner.js@@ -79,7 +79,7 @@ export async function runPumpAlertRules(now = Date.now()) {const fireRows = await sql`SELECT rule_id, last_fired_at, last_event_id, last_stateFROM pump_alert_rule_fires- WHERE rule_id = ANY(${rules.map((r) => r.id)})+ WHERE rule_id = ANY(${rules.map((r) => r.id)}::uuid[])`;const fireState = new Map(fireRows.map((f) => [f.rule_id, f]));@@ -148,7 +148,7 @@ async function runNewMintRules(rules, fireState, report, ctx) {const mints = await sql`SELECT id, agent_id, mint, name, symbol, created_atFROM pump_agent_mints- WHERE agent_id = ANY(${agentIds})+ WHERE agent_id = ANY(${agentIds}::uuid[])AND created_at > now() - ${NEW_MINT_WINDOW}::intervalORDER BY created_at ASC`;@@ -315,7 +315,7 @@ async function loadAgentMintSets(agentIds) {const map = new Map();if (!agentIds.length) return map;const rows = await sql`- SELECT agent_id, mint FROM pump_agent_mints WHERE agent_id = ANY(${agentIds})+ SELECT agent_id, mint FROM pump_agent_mints WHERE agent_id = ANY(${agentIds}::uuid[])`;for (const r of rows) {if (!map.has(r.agent_id)) map.set(r.agent_id, new Set());diff --git a/api/_lib/solana-attestations.js b/api/_lib/solana-attestations.jsindex c83a50699..9d617d1f8 100644--- a/api/_lib/solana-attestations.js+++ b/api/_lib/solana-attestations.js@@ -22,6 +22,11 @@ export const KIND_MAP = {export const KINDS_ALL = Object.values(KIND_MAP);export const MIN_STAKE_LAMPORTS = 1_000_000n; // 0.001 SOL+// Subkind marking a glTF/GLB schema validation (the Solana analog of the EVM+// ValidationRegistry's recordValidation glb-schema attestation). It rides on the+// threews.validation.v1 kind but carries proof_hash/proof_uri instead of task_hash.+export const SUBKIND_GLB_SCHEMA = 'glb-schema';+// Validate a parsed memo payload against its schema. Returns true iff well-formed.export function validatePayload(p) {if (!p || typeof p !== 'object') return false;@@ -31,6 +36,12 @@ export function validatePayload(p) {case 'threews.feedback.v1':return Number.isInteger(p.score) && p.score >= 1 && p.score <= 5;case 'threews.validation.v1':+ // Model (glTF/GLB schema) validations carry a content proof hash + URI;+ // task validations carry a task_hash. Either form must declare passed.+ if (p.subkind === SUBKIND_GLB_SCHEMA) {+ return typeof p.proof_hash === 'string' && p.proof_hash.length > 0+ && typeof p.passed === 'boolean';+ }return typeof p.task_hash === 'string' && typeof p.passed === 'boolean';case 'threews.task.v1':return typeof p.task_id === 'string' && typeof p.scope_hash === 'string';diff --git a/api/_lib/solana-validation-attest.js b/api/_lib/solana-validation-attest.jsnew file mode 100644index 000000000..ec33bd4bc--- /dev/null+++ b/api/_lib/solana-validation-attest.js@@ -0,0 +1,206 @@+/**+ * Solana ValidationRegistry attestor (server-side).+ *+ * The Solana-native analog of api/_lib/validation-attest.js (EVM). Solana has no+ * deployed registry contract — on-chain attestations are first-class SPL Memo+ * transactions indexed into `solana_attestations` (see solana-attestations.js).+ * This turns an agent's GLB into a signed, on-chain glTF/schema validation+ * attestation:+ *+ * 1. Fetch the GLB (SSRF-guarded) and run it through the platform's one glTF+ * validator — the same inspector behind /api/x402/model-check. Parse-success+ * ⇒ structurally valid; parse-failure ⇒ a hard error in the report.+ * 2. sha256 the canonical report JSON for the on-chain proof hash, and pin the+ * full report to R2 so verifiers can fetch the detail behind the hash+ * (best-effort: an unconfigured bucket yields an empty proof_uri, never a+ * thrown attestation — the hash alone is still verifiable).+ * 3. Emit a `threews.validation.v1` memo (subkind glb-schema) signed by the+ * platform attester (ATTEST_AGENT_SECRET_KEY), with the agent asset pubkey+ * as a non-signer key, then mirror the row into solana_attestations.+ *+ * Idempotent by content: re-attesting an identical report for the same agent+ * returns the existing signature instead of broadcasting a duplicate tx.+ *+ * Best-effort by contract: callers wrap this in try/catch — a validation failure+ * (or missing key / RPC trouble) must never block the flow that triggered it.+ * Errors carry a machine-readable `.code`.+ */++import { createHash } from 'node:crypto';+import {+ PublicKey,+ Transaction,+ TransactionInstruction,+ sendAndConfirmTransaction,+} from '@solana/web3.js';++import { sql } from './db.js';+import { solanaConnection } from './solana/connection.js';+import { RPC, SUBKIND_GLB_SCHEMA } from './solana-attestations.js';+import { loadAttesterKeypair } from './attest-event.js';+import { validateGlb } from './validation-attest.js';+import { putObject, publicUrl } from './r2.js';+import { KIND_GLB_SCHEMA } from '../../src/erc8004/validation-report.js';++const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');+const VALIDATION_KIND = 'threews.validation.v1';+const TX_TIMEOUT_MS = 15_000;++class SolanaAttestError extends Error {+ constructor(code, message) {+ super(message);+ this.name = 'SolanaAttestError';+ this.code = code;+ }+}++/** sha256 of the canonicalized report JSON — the on-chain proof hash (hex). */+export function hashReportSha256(report) {+ return createHash('sha256').update(JSON.stringify(report)).digest('hex');+}++function withTimeout(promise, ms) {+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(+ () => reject(Object.assign(new Error(`rpc timeout after ${ms}ms`), { code: 'RPC_TIMEOUT' })),+ ms,+ );+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}++/** Pin the report JSON to R2, returning its public URL. Best-effort: '' on failure. */+async function pinReport(report, network, agentAsset, proofHash) {+ try {+ const body = Buffer.from(JSON.stringify(report, null, 2));+ const key = `solana/validation/${network}/${agentAsset}/${proofHash}.json`;+ await putObject({ key, body, contentType: 'application/json' });+ return publicUrl(key);+ } catch {+ return '';+ }+}++/**+ * Full Solana attestation: validate the GLB, pin the report, sign + record a+ * memo attestation, mirror to the index.+ *+ * @param {object} p+ * @param {'mainnet'|'devnet'} p.network+ * @param {string} p.agentAsset Metaplex Core asset pubkey (base58).+ * @param {string} p.glbUrl Public URL to the agent's GLB.+ * @param {string} p.validatedAt ISO timestamp (caller-supplied; deterministic hashing).+ * @returns {Promise<{+ * status: 'minted'|'deduped', passed: boolean, proofHash: string, proofUri: string,+ * signature: string, modelSha256: string, validatedAt: string, kind: string,+ * network: string, agentAsset: string, validator: string, report: object,+ * }>}+ */+export async function attestValidationSolana({ network, agentAsset, glbUrl, validatedAt }) {+ if (network !== 'mainnet' && network !== 'devnet') {+ throw new SolanaAttestError('unsupported_network', `unsupported network ${network}`);+ }+ try {+ new PublicKey(agentAsset);+ } catch {+ throw new SolanaAttestError('invalid_asset', 'agentAsset is not a valid pubkey');+ }++ let attester;+ try {+ attester = loadAttesterKeypair();+ } catch {+ throw new SolanaAttestError(+ 'attester_key_not_configured',+ 'ATTEST_AGENT_SECRET_KEY is not set — cannot sign Solana validation attestations.',+ );+ }+ const validator = attester.publicKey.toBase58();++ // 1. Validate the GLB (never throws on an invalid model — that's a failing report).+ const { report, passed, sha256: modelSha256 } = await validateGlb(glbUrl, validatedAt);+ const proofHash = hashReportSha256(report);++ // 2. Content idempotency: an identical report already on-chain for this agent+ // short-circuits before we spend a second tx.+ const [existing] = await sql`+ select signature, payload->>'proof_uri' as proof_uri+ from solana_attestations+ where agent_asset = ${agentAsset} and network = ${network}+ and kind = ${VALIDATION_KIND}+ and payload->>'subkind' = ${SUBKIND_GLB_SCHEMA}+ and payload->>'proof_hash' = ${proofHash}+ limit 1+ `;+ if (existing) {+ return {+ status: 'deduped', passed, proofHash, proofUri: existing.proof_uri || '',+ signature: existing.signature, modelSha256, validatedAt,+ kind: KIND_GLB_SCHEMA, network, agentAsset, validator, report,+ };+ }++ // 3. Pin the report, build the payload.+ const proofUri = await pinReport(report, network, agentAsset, proofHash);+ const payload = {+ v: 1,+ kind: VALIDATION_KIND,+ subkind: SUBKIND_GLB_SCHEMA,+ agent: agentAsset,+ ts: Math.floor(new Date(validatedAt).getTime() / 1000) || Math.floor(Date.now() / 1000),+ passed,+ proof_hash: proofHash,+ proof_uri: proofUri,+ model_sha256: modelSha256,+ source: 'threews.model-check',+ };++ // 4. Sign + send the memo.+ const conn = solanaConnection({ url: RPC[network] || RPC.devnet, commitment: 'confirmed' });+ const ix = new TransactionInstruction({+ programId: MEMO_PROGRAM_ID,+ keys: [+ { pubkey: attester.publicKey, isSigner: true, isWritable: false },+ { pubkey: new PublicKey(agentAsset), isSigner: false, isWritable: false },+ ],+ data: Buffer.from(JSON.stringify(payload), 'utf8'),+ });+ const tx = new Transaction().add(ix);++ let signature;+ try {+ signature = await withTimeout(+ sendAndConfirmTransaction(conn, tx, [attester], { commitment: 'confirmed' }),+ TX_TIMEOUT_MS,+ );+ } catch (err) {+ throw new SolanaAttestError('record_failed', `validation memo failed: ${err.message}`);+ }++ // 5. Mirror into the index (best-effort; the crawler would pick it up anyway).+ try {+ await sql`+ insert into solana_attestations (+ signature, network, slot, block_time, agent_asset, attester,+ kind, payload, task_id, target_signature, verified+ )+ values (+ ${signature}, ${network}, null, now(),+ ${agentAsset}, ${validator},+ ${VALIDATION_KIND}, ${JSON.stringify(payload)}::jsonb,+ null, null, true+ )+ on conflict (signature) do nothing+ `;+ } catch (err) {+ if (err?.code !== '23505') throw err;+ }++ return {+ status: 'minted', passed, proofHash, proofUri, signature, modelSha256,+ validatedAt, kind: KIND_GLB_SCHEMA, network, agentAsset, validator, report,+ };+}++export { SolanaAttestError };diff --git a/api/agents/solana/[action].js b/api/agents/solana/[action].jsindex a0d339b88..d7a1a16b7 100644--- a/api/agents/solana/[action].js+++ b/api/agents/solana/[action].js@@ -11,6 +11,8 @@ import {handleRegisterConfirm,handleReputation,handleReputationHistory,+ handleValidate,+ handleValidation,} from './_handlers.js';export {@@ -31,6 +33,8 @@ const DISPATCH = {'register-confirm': handleRegisterConfirm,reputation: handleReputation,'reputation-history': handleReputationHistory,+ validate: handleValidate,+ validation: handleValidation,};export default wrap(async (req, res) => {diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.jsindex 8e5b6b43e..6fe4d4268 100644--- a/api/agents/solana/_handlers.js+++ b/api/agents/solana/_handlers.js@@ -170,6 +170,154 @@ export const handleAttestEvent = wrap(async (req, res) => {return json(res, 202, { data: { deduped: true, status: 'in_progress' } });});+// ── solana-validate (write: glTF/schema validation attestation) ────────────────++import { attestValidationSolana, SolanaAttestError } from '../../_lib/solana-validation-attest.js';+import { SUBKIND_GLB_SCHEMA } from '../../_lib/solana-attestations.js';++const SOLANA_ATTEST_ERROR_STATUS = {+ unsupported_network: 400,+ invalid_asset: 400,+ invalid_glb_url: 400,+ glb_fetch_failed: 502,+ glb_too_large: 413,+ attester_key_not_configured: 500,+ record_failed: 502,+};++const validateSchema = z.object({+ asset_pubkey: z.string().min(32).max(44),+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),+ glb_url: z.string().url().optional(),+});++export const handleValidate = wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const body = parse(validateSchema, await readJson(req));+ const { asset_pubkey, network } = body;+ try { new PublicKey(asset_pubkey); } catch { return error(res, 400, 'validation_error', 'invalid asset pubkey'); }++ // Ownership: the agent must belong to the signed-in user (mirrors handleEdit).+ const [agent] = await sql`select id, avatar_id from agent_identities where (meta->>'sol_mint_address') = ${asset_pubkey} and user_id = ${user.id} and deleted_at is null limit 1`;+ if (!agent) return error(res, 404, 'not_found', 'agent not found for your account');++ // Resolve the GLB to validate: explicit glb_url wins; otherwise the agent's+ // avatar GLB. validateGlb SSRF-guards whatever URL we pass.+ let glbUrl = body.glb_url || null;+ if (!glbUrl && agent.avatar_id) {+ const [av] = await sql`select storage_key from avatars where id = ${agent.avatar_id} and deleted_at is null limit 1`;+ if (av?.storage_key) glbUrl = publicUrl(av.storage_key);+ }+ if (!glbUrl) return error(res, 422, 'no_model', 'agent has no GLB to validate — attach an avatar or pass glb_url');++ let result;+ try {+ result = await attestValidationSolana({+ network,+ agentAsset: asset_pubkey,+ glbUrl,+ validatedAt: new Date().toISOString(),+ });+ } catch (e) {+ if (e instanceof SolanaAttestError) {+ return error(res, SOLANA_ATTEST_ERROR_STATUS[e.code] || 500, e.code, e.message);+ }+ throw e;+ }++ const { recordEvent } = await import('../../_lib/usage.js');+ recordEvent({+ userId: user.id, agentId: agent.id, kind: 'solana_validation', tool: 'glb-schema',+ status: 'ok', meta: { network, signature: result.signature, passed: result.passed, deduped: result.status === 'deduped' },+ });++ return json(res, result.status === 'deduped' ? 200 : 201, {+ ok: true,+ passed: result.passed,+ signature: result.signature,+ proof_hash: result.proofHash,+ proof_uri: result.proofUri,+ model_sha256: result.modelSha256,+ kind: result.kind,+ subkind: SUBKIND_GLB_SCHEMA,+ validator: result.validator,+ network,+ asset_pubkey,+ deduped: result.status === 'deduped',+ explorer: `https://explorer.solana.com/tx/${result.signature}${network === 'devnet' ? '?cluster=devnet' : ''}`,+ });+});++// ── solana-validation (read: latest + history of glTF/schema validations) ──────++export const handleValidation = wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, `http://${req.headers.host}`);+ const asset = url.searchParams.get('asset');+ const network = url.searchParams.get('network') === 'mainnet' ? 'mainnet' : 'devnet';+ const limit = Math.min(Number(url.searchParams.get('limit') || 25), 200);+ const force = url.searchParams.get('refresh') === '1';++ if (!asset) return error(res, 400, 'validation_error', 'asset query param required');+ try { new PublicKey(asset); } catch { return error(res, 400, 'validation_error', 'invalid asset pubkey'); }++ // Refresh-on-demand so a just-recorded validation is visible immediately.+ let [cursor] = await sql`select last_indexed_at from solana_attestations_cursor where agent_asset = ${asset} limit 1`;+ if (!cursor || force) {+ const [a] = await sql`select wallet_address as owner from agent_identities where meta->>'sol_mint_address' = ${asset} and deleted_at is null limit 1`;+ try { await crawlAgentAttestations({ agentAsset: asset, network, ownerWallet: a?.owner || null }); } catch {}+ [cursor] = await sql`select last_indexed_at from solana_attestations_cursor where agent_asset = ${asset} limit 1`;+ }++ const rows = await sql`+ select signature, slot, block_time, attester, payload, verified, revoked, disputed+ from solana_attestations+ where agent_asset = ${asset} and network = ${network}+ and kind = 'threews.validation.v1'+ and payload->>'subkind' = ${SUBKIND_GLB_SCHEMA}+ and revoked = false+ order by slot desc nulls first, block_time desc+ limit ${limit}+ `;++ const history = rows.map((r) => ({+ signature: r.signature,+ slot: r.slot,+ block_time: r.block_time,+ validator: r.attester,+ passed: r.payload?.passed === true,+ proof_hash: r.payload?.proof_hash || null,+ proof_uri: r.payload?.proof_uri || null,+ model_sha256: r.payload?.model_sha256 || null,+ verified: r.verified,+ disputed: r.disputed,+ explorer: `https://explorer.solana.com/tx/${r.signature}${network === 'devnet' ? '?cluster=devnet' : ''}`,+ }));++ return json(res, 200, {+ agent: asset,+ network,+ kind: SUBKIND_GLB_SCHEMA,+ latest: history[0] || null,+ count: history.length,+ history,+ last_indexed_at: cursor?.last_indexed_at || null,+ }, { 'cache-control': 'public, max-age=30', 'access-control-allow-origin': '*' });+});+// ── solana-metadata ──────────────────────────────────────────────────────────export const handleMetadata = wrap(async (req, res) => {@@ -268,6 +416,12 @@ export const handleCard = wrap(async (req, res) => {if (s) token_stats = { mint: s.mint, network: s.network, graduated: s.graduated, bonding_curve: s.bonding_curve, amm: s.amm, last_signature: s.last_signature, last_signature_at: s.last_signature_at, recent_tx_count: s.recent_tx_count, refreshed_at: s.refreshed_at };} catch {}+ let validation = null;+ try {+ const [v] = await sql`select signature, attester, payload, block_time from solana_attestations where agent_asset = ${asset} and network = ${network} and kind = 'threews.validation.v1' and payload->>'subkind' = ${SUBKIND_GLB_SCHEMA} and revoked = false order by slot desc nulls first, block_time desc limit 1`;+ if (v) validation = { passed: v.payload?.passed === true, proof_hash: v.payload?.proof_hash || null, proof_uri: v.payload?.proof_uri || null, validator: v.attester, signature: v.signature, validated_at: v.block_time };+ } catch {}+return json(res, 200, {schema_version: '1.0',name: a.name,@@ -293,6 +447,7 @@ export const handleCard = wrap(async (req, res) => {a2a_paid: `${origin}/api/agents/a2a-paid`,attestations: `${origin}/api/agents/solana-attestations?asset=${asset}&network=${network}`,reputation: `${origin}/api/agents/solana-reputation?asset=${asset}&network=${network}`,+ validation: `${origin}/api/agents/solana-validation?asset=${asset}&network=${network}`,...(token_stats ? { quote: `${origin}/api/pump/quote?mint=${asset}&network=${network}`, price_history: `${origin}/api/agents/solana-price-history?asset=${asset}&network=${network}` } : {}),},attestation: {@@ -301,6 +456,7 @@ export const handleCard = wrap(async (req, res) => {memo_program: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',usage: 'Sign an SPL Memo tx with one of the published schemas as JSON, including this asset_pubkey as a non-signer key.',},+ ...(validation ? { validation } : {}),...(pumpfun ? { pumpfun } : {}),...(token_stats ? { token_stats } : {}),}, { 'cache-control': 'public, max-age=120', 'access-control-allow-origin': '*' });@@ -561,7 +717,28 @@ export const handleRegisterConfirm = wrap(async (req, res) => {await sql`delete from agent_registrations_pending where user_id=${user.id} and payload->>'asset_pubkey'=${asset_pubkey}`;- return json(res, 201, { ok: true, agent: { ...agent, home_url: `${env.APP_ORIGIN}/agent/${agent.id}` }, sol_mint_address: asset_pubkey, tx_signature, network });+ // Best-effort glTF/schema validation attestation, recorded on-chain by the+ // platform validator. Mirrors the EVM auto-validation path: a failure here+ // (missing key, RPC trouble, no avatar GLB) must never fail the registration.+ let validation = null;+ try {+ if (avatar_id) {+ const [av] = await sql`select storage_key from avatars where id = ${avatar_id} and deleted_at is null limit 1`;+ if (av?.storage_key) {+ const r = await attestValidationSolana({+ network,+ agentAsset: asset_pubkey,+ glbUrl: publicUrl(av.storage_key),+ validatedAt: new Date().toISOString(),+ });+ validation = { passed: r.passed, signature: r.signature, proof_hash: r.proofHash, deduped: r.status === 'deduped' };+ }+ }+ } catch (e) {+ validation = { error: e.code || 'validation_failed' };+ }++ return json(res, 201, { ok: true, agent: { ...agent, home_url: `${env.APP_ORIGIN}/agent/${agent.id}` }, sol_mint_address: asset_pubkey, tx_signature, network, ...(validation ? { validation } : {}) });});// ── solana-collection-metadata ─────────────────────────────────────────────────diff --git a/api/alerts/_rules.js b/api/alerts/_rules.jsindex e44c06537..a1f6baf78 100644--- a/api/alerts/_rules.js+++ b/api/alerts/_rules.js@@ -113,10 +113,14 @@ export function validateUpdate(current, patch) {enabled: 'enabled' in patch ? patch.enabled : current.enabled,label: 'label' in patch ? patch.label : current.label,};+ // Normalize first so fields incompatible with the (possibly new) kind are+ // cleared before validation — e.g. switching to new_mint drops a stale+ // target_mint instead of failing on it.+ const normalized = normalizeForKind(merged);const issues = [];- refineRule(merged, { addIssue: (i) => issues.push(i) });+ refineRule(normalized, { addIssue: (i) => issues.push(i) });if (issues.length) return { ok: false, issues };- return { ok: true, value: normalizeForKind(merged) };+ return { ok: true, value: normalized };}/** Null out fields that don't apply to the rule's kind so stale values can't leak. */@@ -145,7 +149,10 @@ export function serializeRule(row) {telegram_chat: row.telegram_chat || null,cooldown_seconds: row.cooldown_seconds,enabled: row.enabled,- label: row.label || deriveRuleLabel(row),+ // `label` is the raw user value (null when auto); `label_display` is what+ // the UI shows — a derived default when the user didn't name the rule.+ label: row.label || null,+ label_display: row.label || deriveRuleLabel(row),last_fired_at: row.last_fired_at || null,recent_failures: row.recent_failures != null ? Number(row.recent_failures) : 0,recent_deliveries: row.recent_deliveries || [],diff --git a/api/cron/[name].js b/api/cron/[name].jsindex 6a3259973..39011414a 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -1559,7 +1559,8 @@ async function pumpfunLinkedWalletMap(wallets) {function pumpfunSignalsFromClaim(ev) {const out = [];- const base = { tx_signature: ev.tx_signature, payload: ev };+ // Bot claims carry tx_signature; the pf:claims Redis lane carries signature.+ const base = { tx_signature: ev.tx_signature || ev.signature, payload: ev };if (ev.first_time_claim) out.push({ kind: 'first_claim', ...base });if (ev.fake_claim) out.push({ kind: 'fake_claim', ...base });if (ev.tier === 'mega' || ev.tier === 'influencer') out.push({ kind: 'influencer', ...base });diff --git a/api/wk.js b/api/wk.jsindex c324605d1..d6b506f73 100644--- a/api/wk.js+++ b/api/wk.js@@ -49,12 +49,21 @@ const SCHEMAS = {},},'threews.validation.v1': {- description: 'Validator attestation about an agent task result.',- required: ['v', 'kind', 'agent', 'task_hash', 'passed'],+ description:+ 'Validator attestation. Two forms: a task validation (task_hash) or a ' ++ 'glTF/GLB schema validation of the agent model (subkind "glb-schema", ' ++ 'carrying proof_hash + proof_uri) — the Solana analog of the EVM ' ++ 'ValidationRegistry recordValidation.',+ required: ['v', 'kind', 'agent', 'passed'],properties: {...COMMON,- task_hash: { type: 'string' },passed: { type: 'boolean' },+ subkind: { type: 'string', enum: ['glb-schema'], description: 'Present for model (glTF/GLB schema) validations.' },+ task_hash: { type: 'string', description: 'Task validation form: sha256 of the validated task.' },+ proof_hash: { type: 'string', description: 'Model form: sha256 of the canonical validation report JSON.' },+ proof_uri: { type: 'string', description: 'Model form: URL to the full pinned validation report.' },+ model_sha256: { type: 'string', description: 'Model form: sha256 of the GLB bytes.' },+ source: { type: 'string' },uri: { type: 'string', format: 'uri' },},},@@ -105,6 +114,7 @@ function handleAttestationSchemas(req, res) {discovery: {list_endpoint: '/api/agents/solana-attestations?asset=<pubkey>&kind=...',reputation_endpoint: '/api/agents/solana-reputation?asset=<pubkey>',+ validation_endpoint: '/api/agents/solana-validation?asset=<pubkey>',},},{ 'cache-control': 'public, max-age=300' },diff --git a/data/changelog.json b/data/changelog.jsonindex 93d7e6411..1ff79c336 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,60 @@{"$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": "Clearer launch & trade errors, and a graduated badge on coins",+ "summary": "When a token launch or an in-world trade can't go through, the app now tells you exactly why and what to do next — \"Not enough SOL to cover the launch + network fees,\" \"Price moved beyond your slippage limit,\" \"You cancelled the signature in your wallet,\" or \"Couldn't reach the Solana network\" — instead of a single catch-all \"Connection error.\" Coins also show their lifecycle at a glance: the trade panel carries a badge marking whether a coin is still on its bonding curve or has graduated to the PumpSwap AMM, so a graduated coin is unmistakable. Backed by new end-to-end browser tests that drive the full four-step launch flow and the buy/sell widget so this conversion path can't silently break.",+ "tags": ["improvement"],+ "link": "/pump-dashboard"+ },+ {+ "date": "2026-06-15",+ "title": "Pump dashboard alerts now run server-side — fire across devices even with the tab closed",+ "summary": "Alert rules moved from your browser to our servers, so they fire whether or not a dashboard tab is open and follow you across every device you sign in on. Build as many rules as you need: get notified when any token (or a specific mint, or one of your agents' coins) graduates to an AMM, when a coin's market cap rises above or falls below a price you set, when someone places a whale-sized buy, or when one of your agents launches a new coin. Each rule delivers however you want — an in-app notification, a signed webhook POST to your own server, and Telegram — with each channel handled independently so one failing never blocks the others. Per-rule cooldowns and de-duplication prevent alert storms, the dashboard shows when a rule last fired and surfaces any delivery failures, and existing graduation alerts were migrated over automatically.",+ "tags": ["feature"],+ "link": "/pump-dashboard"+ },+ {+ "date": "2026-06-15",+ "title": "On-chain model validation for Solana agents",+ "summary": "Solana agents now get the same verifiable, on-chain glTF/model validation that EVM agents get from the ValidationRegistry — no contract to deploy. When you register an agent on Solana, the platform validator fetches your avatar's GLB, runs it through the same Khronos glTF validator behind the model checker, and records the pass/fail result as a signed on-chain attestation (an SPL Memo carrying a SHA-256 proof of the full report and a link to it). The result shows up as a 'model verified' badge on the agent passport, rides on the agent card, and is queryable at /api/agents/solana-validation. Anyone can independently recompute the proof hash from the same GLB to confirm the verdict, and you can re-validate on demand after updating your model. Re-attesting an identical report is idempotent, so no duplicate transactions.",+ "tags": ["feature", "security"]+ },+ {+ "date": "2026-06-15",+ "title": "Live coin status — price, market cap and graduation — now unified across the platform",+ "summary": "The launches feed, agent profile token panels, and the in-world agent coin card now share one live coin-status display, so every place that shows a coin reads the same numbers from the same source. Launch cards now stream the coin's real logo, USD price, market cap, a graduation progress ring and time since launch — not just market cap — with the orbital fingerprint as a placeholder until the logo loads. Agent profiles show a live price-and-graduation chip in the token panel and per-coin market caps in the launch history, and the agent home card's market readout is now consistent with the rest of the platform. Each card refreshes on its own and degrades gracefully to a Retry if pump.fun is briefly unreachable.",+ "tags": ["improvement"],+ "link": "/launches"+ },+ {+ "date": "2026-06-15",+ "title": "USDC-paired agent coins now record and display correct trade amounts",+ "summary": "Coins launched against USDC are now tracked in the right currency end to end. Every buy and sell records which quote asset it actually used and how much of it moved — USDC amounts in USDC, SOL amounts in SOL — instead of quietly storing a USDC trade as if it were SOL and reporting a price and market cap that were off by orders of magnitude. Portfolios now subtotal holdings separately by quote asset, so your SOL positions and USDC positions each get their own value, cost basis, and unrealized P&L with no more mixing of mismatched units. Existing SOL trades are unchanged, and historical rows were backfilled as SOL-paired so nothing shifts.",+ "tags": ["fix", "feature"]+ },+ {+ "date": "2026-06-15",+ "title": "three.ws can now register itself on-chain on Solana",+ "summary": "Alongside its ERC-8004 identity, three.ws can now mint its own agent on Solana — as a Metaplex Core asset in the official \"three.ws Agents\" collection, exactly the way agents you deploy through the platform are registered. A one-command tool builds the platform's 3D Agent Card, verifies the avatar's SHA-256 against the exact GLB bytes served (so the model can't be silently swapped), pins the metadata, mints the asset into the collection, and writes the result back into the public discovery documents at three.ws/.well-known so any wallet, explorer, or agent can resolve and verify three.ws. The discovery card and its schema now carry Solana identities (CAIP-10) alongside EVM ones, and the platform agent's on-chain badge links straight to its Solana passport.",+ "tags": ["feature", "infra"],+ "link": "/.well-known/agent-registration.json"+ },+ {+ "date": "2026-06-15",+ "title": "Buy and sell USDC-paired coins straight from the trade widget",+ "summary": "The in-world trade widget now speaks both currencies. Open Buy on a coin and the widget reads its real pairing from the chain: a SOL coin asks for SOL exactly as before, while a USDC-paired coin denominates the amount in USDC, shows your wallet's USDC balance, and prices and settles the trade in USDC. A new Sell tab lets you sell a coin you hold back to its quote asset — pick 25%, 50%, or Max of your balance, see the live payout, and sign once; for USDC coins the payout account is opened for you automatically in the same transaction. Every state is handled: not enough USDC offers a one-tap Add-funds flow, a moved price explains your slippage, and a cancelled signature is quietly acknowledged. The whole flow is your own wallet, signed in your browser, with a Solscan link the moment it lands.",+ "tags": ["feature"],+ "link": "/play"+ },+ {+ "date": "2026-06-15",+ "title": "Agent reputation now reflects a real pump.fun track record",+ "summary": "An agent's pump.fun behavior now feeds its reputation and shows on its passport. When the wallet behind an agent graduates a token, claims creator fees, makes a whale-sized buy, or launches a coin, that moment is recorded as a typed signal — graduating a token counts for more than a routine claim, and a flagged or brand-new-account claim counts against. These signals roll up into the agent's Solana reputation score and appear on the public agent passport, readable by anyone without a wallet. The live pump.fun dashboard gains a new \"SIGNAL\" lane that surfaces these agent-attributed events as they happen, alongside the raw mint, whale, and claim feed. The processor behind this used to sit idle unless an optional external service was configured; it now runs continuously off the platform's own live pump.fun stream with no external dependency, records only genuinely new events so nothing is double-counted, and attributes each one to the agent behind the wallet.",+ "tags": ["improvement", "fix"],+ "link": "/pump-dashboard"+ },{"date": "2026-06-15","title": "Registered agents now carry an on-chain \"Validated\" badge",diff --git a/docs/erc8004/validation-attestation.md b/docs/erc8004/validation-attestation.mdnew file mode 100644index 000000000..b471e22b4--- /dev/null+++ b/docs/erc8004/validation-attestation.md@@ -0,0 +1,86 @@+# ERC-8004 Validation Attestation++When an agent is registered (or re-validated) on-chain, three.ws automatically+runs its GLB through the platform's glTF validator and records a signed+validation attestation on the ERC-8004 **ValidationRegistry**. This is what makes+`supportedTrust: ["validation"]` in the 3D Agent Card real — the agent carries an+on-chain, independently-verifiable proof that its model passed validation.++## Flow++```+register/bind ──▶ POST /api/erc8004/validate ──▶ api/_lib/validation-attest.js+ │+ 1. fetch GLB (SSRF-guarded) │ reuses the ONE glTF validator+ 2. sha256 the bytes (byte-check) │ (src/gltf-inspect.js, the same+ 3. inspectModel() → report │ code behind /api/x402/model-check)+ 4. pin report JSON → R2 │+ 5. recordValidation(...) signed ▼+ by VALIDATOR_PRIVATE_KEY ──▶ ValidationRegistry (on-chain)++profile badge ◀── GET /api/erc8004/validation ◀── resolveLatestValidation()+ (walletless) getLatestByKind(agentId,"glb-schema")+```++- **Pass/fail** = zero parse/schema errors. Optimization suggestions are recorded+ as warnings/infos and never fail a model. See+ [`src/erc8004/validation-report.js`](../../src/erc8004/validation-report.js).+- **Byte-check vs schema-check are independent.** A passing schema validation+ never overrides the sha256 byte identity — both are surfaced in the report+ (`byteCheck.sha256` and `issues`).+- **Best-effort.** A validation failure, a missing validator key, an undeployed+ registry, or a non-allow-listed validator never blocks or reverts the+ registration. The agent is registered; it's just unvalidated, and the badge+ says so.+- **Re-runnable.** Re-validating after a GLB update records a fresh attestation;+ `getLatestByKind` (and the badge) reflect the latest.++## Badge states++`src/shared/validation-badge.js` renders four designed states from the on-chain+read: **validated** (green ✓, links to the proof report + validator), **validation+failed** (red, shows the failure reason from the pinned report), **not validated**+(registry deployed, no attestation yet — owners get a Validate action), and+**pending** (while fetching / attesting). When the ValidationRegistry isn't+deployed on the agent's chain the badge renders nothing.++## Operating the platform validator++The validator is a dedicated EVM key. It is **not** in the repo.++1. **Provision** (already done — address below):+ ```+ node scripts/erc8004/provision-validator-key.mjs+ ```+ Address: `0x93Bc7EfB0059B784465619FC73C2db8D01b1CD04` (provisioned 2026-06-15).+2. **Store the secret**: set `VALIDATOR_PRIVATE_KEY` in Vercel (production ++ preview) and `.env.local` for local runs. Never commit it.+3. **Fund** the address with gas on each ValidationRegistry chain.+4. **Allow-list** it on each chain as the registry owner (coordinate with+ [task 01](../../tasks/onchain-deployment/01-deploy-mainnet-validation-registry.md)+ step 6):+ ```+ cast send <ValidationRegistry> "addValidator(address)" \+ 0x93Bc7EfB0059B784465619FC73C2db8D01b1CD04 --rpc-url <chain>+ ```++Until the key is configured **and** allow-listed on a chain whose+ValidationRegistry is deployed, `/api/erc8004/validate` returns a clear ops error+(`validator_key_not_configured`, `validation_registry_not_deployed`, or+`validator_not_allowlisted`) — never a silent skip. **Testnet** (Base Sepolia+84532) already has a deployed registry, so it's the first end-to-end target;+**mainnet** activates automatically once task 01 fills the mainnet address in+`api/_lib/erc8004-chains.js`, `src/erc8004/abi.js`, and `sdk/src/erc8004/abi.js`.++## Surfaces++| Piece | File |+| ----- | ---- |+| Pure report (hash, pass/fail, build) | `src/erc8004/validation-report.js` |+| Server attestor | `api/_lib/validation-attest.js` |+| Endpoints (`validate` POST, `validation` GET) | `api/erc8004/[action].js` |+| Walletless on-chain read | `api/_lib/onchain.js` → `resolveLatestValidation` |+| Registry address + ABI | `api/_lib/erc8004-chains.js` |+| Badge component | `src/shared/validation-badge.js` |+| Profile render | `src/agent-detail.js` |+| DB cache (list views / ops) | migration `20260615000000_erc8004_validation.sql` |diff --git a/docs/solana-pumpfun.md b/docs/solana-pumpfun.mdindex 55e304a84..43f284ecc 100644--- a/docs/solana-pumpfun.md+++ b/docs/solana-pumpfun.md@@ -67,7 +67,7 @@ SOLANA_RPC_URL= # mainnet (Helius/Triton recommended)SOLANA_RPC_URL_DEVNET=```-When `PUMPFUN_BOT_URL` is unset, the integration becomes a no-op: endpoints return `503 unavailable`, the cron returns `{ skipped: 'pumpfun bot not configured' }`, and the watch skills return a friendly error. Solana agents that don't use it pay no cost.+`PUMPFUN_BOT_URL` is an **optional enrichment layer**, not a hard dependency. When it's unset (the prod default), the `pumpfun-signals` cron still runs off the live WS-fed `pumpfun_graduations` table and the `pf:claims` / `pf:whales` / `pf:mints` Redis lanes — only the bot's richer claim intel (tier, GitHub account age) is skipped. The `op=claims` read proxy and watch skills soft-degrade to empty when the bot is absent. Solana agents that don't use it pay no cost.---@@ -97,17 +97,36 @@ These are continuous-blend stimuli, not discrete states — they decay according## Reputation signals-The cron writes typed rows to `pumpfun_signals(wallet, agent_asset, kind, weight, payload, tx_signature)`. `solana-reputation` aggregates them as `pumpfun_signals: { count, weight, by_kind }` in the response.+The cron writes typed rows to `pumpfun_signals(wallet, agent_asset, kind, weight, payload, tx_signature)`. `solana-reputation` aggregates them as `pumpfun_signals: { count, weight, by_kind }` in the response, and the agent-passport card surfaces a `pumpfun` block. The `/api/pump/channel-feed` `signal` lane renders them as live, agent-attributed feed cards.++### Sources (no upstream bot required)++The cron is **not gated on the optional `PUMPFUN_BOT_URL`** — every lane has a real, always-on source, and the cron emits whatever is live:++| Lane | Source | Actor wallet |+|---|---|---|+| graduations | `pumpfunMcp.graduations()` → the WS-fed `pumpfun_graduations` table (kept fresh by the `pumpfun-graduations-sync` cron), or the bot when configured | `creator` / `dev_wallet` |+| claims | bot `getRecentClaims` (rich tier/age intel) when configured, merged with the `pf:claims` Redis lane | `claimer` / `github_wallet` |+| whales | `pf:whales` Redis lane (first whale-buy events) | `buyer` |+| mints | `pf:mints` Redis lane (new token launches) | `creator` |++A signal is only written when the actor wallet is linked to a three.ws agent (`user_wallets` → `agent_identities`, Solana). Each lane keeps a Postgres cursor in `pumpfun_signals_cursor(source, last_seen_ms, …)` so a run only evaluates events newer than the last — no re-scanning the whole window. The cursor lives in Postgres (not Redis) to keep Upstash write volume flat; the cron makes **zero new Redis writes** — only `lrange` reads.++### Dedup key++Rows are unique on `(tx_signature, kind)`, not `tx_signature` alone — a single claim transaction can legitimately produce `first_claim` + `influencer` + `new_account` rows at once.Default weights:-| Kind | Weight |-|---|---|-| `first_claim` | +0.2 |-| `graduation` | +0.3 |-| `influencer` | +0.2 |-| `new_account` | -0.2 |-| `fake_claim` | -0.6 |+| Kind | Weight | Lane |+|---|---|---|+| `graduation` | +0.3 | graduations |+| `first_claim` | +0.2 | claims |+| `influencer` | +0.2 | claims |+| `whale_buy` | +0.1 | whales |+| `launch` | +0.05 | mints |+| `new_account` | -0.2 | claims |+| `fake_claim` | -0.6 | claims |These are **off-chain** signals — flagged as such, not on-chain attestations. `verified=false` semantically. Weighting them into a final composite score is up to consumers; the endpoint exposes the raw aggregates.diff --git a/docs/validation.md b/docs/validation.mdindex 9fdd222d8..56872724b 100644--- a/docs/validation.md+++ b/docs/validation.md@@ -185,6 +185,66 @@ The minimum check suite for a `pass` verdict includes:- `manifest-integrity` — the agent card's `model.sha256` matches the actual bytes- `card-schema` — the card validates against the three.ws Card v1 spec+### ValidationRegistry (Solana)++Solana agents (Metaplex Core assets) get the same on-chain validation guarantee+without a deployed registry contract. On Solana, attestations are first-class+**SPL Memo transactions** indexed into the `solana_attestations` table — that+index *is* the registry. A glTF/schema validation is a `threews.validation.v1`+memo with `subkind: "glb-schema"`, signed by the platform validator and carrying+the same proof fields as the EVM record.++The platform validator signs and records automatically when an agent is+registered (`/api/agents/solana-register-confirm`), and on demand:++```js+// POST /api/agents/solana-validate (owner-authenticated)+// body: { asset_pubkey, network: "mainnet"|"devnet", glb_url? }+// glb_url defaults to the agent's avatar GLB.+const res = await fetch('/api/agents/solana-validate', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ asset_pubkey, network: 'mainnet' }),+}).then((r) => r.json());++// → { passed, signature, proof_hash, proof_uri, model_sha256, validator, explorer }+```++The on-chain memo payload:++```json+{+ "v": 1,+ "kind": "threews.validation.v1",+ "subkind": "glb-schema",+ "agent": "<asset pubkey>",+ "ts": 1781483899,+ "passed": true,+ "proof_hash": "<sha256 of the canonical report JSON>",+ "proof_uri": "<URL to the full pinned report>",+ "model_sha256": "<sha256 of the GLB bytes>",+ "source": "threews.model-check"+}+```++The proof hash is `sha256(JSON.stringify(report))` (Solana convention; the EVM+side uses keccak256). Anyone can recompute it: re-run the validator on the same+GLB, `JSON.stringify` the report, sha256 it, and compare against `proof_hash` in+the memo. Read the latest and history:++```+GET /api/agents/solana-validation?asset=<pubkey>&network=mainnet+→ { latest, history[], count, last_indexed_at }+```++The validation status also rides on the agent card+(`/api/agents/solana-card`, `validation` block) and renders as a **model+verified / model failed** badge on the agent passport. Schema:+[`/.well-known/agent-attestation-schemas`](../api/wk.js). Recording is gated to+the platform validator key (`ATTEST_AGENT_SECRET_KEY`); re-attesting an identical+report is idempotent (returns the existing signature, no duplicate tx).+### Signed attestation (off-chain)For lighter-weight use cases, `src/attestations/gltf.js` provides a wallet-signed JSON attestation that does not require a blockchain transaction:diff --git a/mcp-server/src/tools/agenc-list-tasks.js b/mcp-server/src/tools/agenc-list-tasks.jsindex 8e8fc8b3d..7b54524e8 100644--- a/mcp-server/src/tools/agenc-list-tasks.js+++ b/mcp-server/src/tools/agenc-list-tasks.js@@ -41,14 +41,14 @@ export async function buildAgenCListTasksTool() {priceUsd: '$0.001',inputSchema: inputJsonSchema,example: {- creator: '5yC9BM8KUsJTPbWPLfA2N8qH1s9V8DQ3Vcw1G6Jdpump',+ creator: 'THREEsynthetic111111111111111111111111111111',cluster: 'devnet',},outputExample: {ok: true,cluster: 'devnet',programId: '6UcJzbTEemBz3aY5wK5qKHGMD7bdRsmR4smND29gB2ab',- creator: '5yC9BM8KUsJTPbWPLfA2N8qH1s9V8DQ3Vcw1G6Jdpump',+ creator: 'THREEsynthetic111111111111111111111111111111',count: 1,tasks: [{diff --git a/package.json b/package.jsonindex 705c7c758..723b1f226 100644--- a/package.json+++ b/package.json@@ -66,6 +66,7 @@"build:pages": "node scripts/build-page-index.mjs","changelog:push": "node scripts/changelog-telegram.mjs","audit:deploy": "node scripts/audit-deploy-artifacts.mjs",+ "verify:solana": "node scripts/verify-solana-parity.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",diff --git a/pages/pump-dashboard.html b/pages/pump-dashboard.htmlindex d9a651e21..2ceef7ccb 100644--- a/pages/pump-dashboard.html+++ b/pages/pump-dashboard.html@@ -1720,7 +1720,10 @@feedCount: 0,activityCount: 0,feedPaused: false,- alertConfig: safeParseJson(localStorage.getItem('pumpbot-alerts') || '{}', {}),+ alertRules: (() => {+ const v = safeParseJson(localStorage.getItem('pumpbot-alerts') || '[]', []);+ return Array.isArray(v) ? v : [];+ })(),// Deep-link target: /pump-dashboard?agent=<id> (e.g. straight from the// launch-token modal) focuses the control panel on that specific agent// instead of falling back to the account default.@@ -2528,22 +2531,78 @@</div>`;}- // ── Alerts ───────────────────────────────────────────────────+ // -- Alerts (server-persisted rules) ----------------------------------+ // Alert rules live in Postgres and are evaluated server-side by the+ // pumpfun-monitor cron, so they fire across devices even with the tab closed.+ // localStorage is a render cache only. While the tab is open we ALSO match+ // live-feed events against the loaded rules for instant feedback.++ // Same-origin fetch: alert rules + notifications are three.ws's own endpoints,+ // never the user-configurable PumpKit API URL.+ function nativeFetch(path, options = {}) {+ return fetch(location.origin + path, { credentials: 'include', ...options });+ }+ async function nativeCsrf() {+ try {+ const r = await nativeFetch('/api/csrf-token');+ if (!r.ok) return null;+ const d = await r.json();+ return d.token || (d.data && d.data.token) || null;+ } catch {+ return null;+ }+ }+ const RULE_KIND_META = {+ graduation: { icon: '\u{1F393}', label: 'Graduation' },+ price_above: { icon: '\u{1F4C8}', label: 'Mcap above' },+ price_below: { icon: '\u{1F4C9}', label: 'Mcap below' },+ whale_buy: { icon: '\u{1F40B}', label: 'Whale buy' },+ new_mint: { icon: '\u{1F195}', label: 'New launch' },+ };++ let _ruleEditingId = null;+ let _agentsLoaded = false;++ function relTime(ts) {+ const ms = Date.now() - new Date(ts).getTime();+ if (!Number.isFinite(ms)) return '';+ const s = Math.floor(ms / 1000);+ if (s < 60) return s + 's ago';+ const m = Math.floor(s / 60);+ if (m < 60) return m + 'm ago';+ const h = Math.floor(m / 60);+ if (h < 24) return h + 'h ago';+ return Math.floor(h / 24) + 'd ago';+ }+ function numOrNull(v) {+ const n = parseFloat(v);+ return Number.isFinite(n) ? n : null;+ }++ // Live-feed -> rule matching for instant, tab-open feedback. The authoritative+ // cross-session delivery is the server cron; this only mirrors it locally for+ // event kinds the raw feed actually carries (graduation, whale buys).function checkAlerts(item) {- const ac = state.alertConfig;+ const rules = state.alertRules || [];+ if (!rules.length) return;const t = item.type;- if ((t === 'graduation' || t === 'complete') && ac.graduation !== false)- addAlertItem(item, 'Token graduated');- if ((t === 'whale' || t === 'whale_trade') && ac.whale) {- const threshold = parseFloat(ac.whaleThreshold) || 10;- if ((Number(item.data.solAmount) || 0) >= threshold)- addAlertItem(item, 'Whale trade detected');+ const d = item.data || {};+ const mint = d.mint || d.tokenMint || null;+ const solAmount = Number(d.solAmount != null ? d.solAmount : d.sol_amount || 0);+ for (const r of rules) {+ if (!r.enabled) continue;+ let hit = false;+ if (r.kind === 'graduation' && (t === 'graduation' || t === 'complete')) {+ hit = !r.target_mint || r.target_mint === mint;+ } else if (r.kind === 'whale_buy' && (t === 'whale' || t === 'whale_trade' || t === 'trade' || t === 'buy')) {+ hit = r.target_mint === mint && d.is_buy !== false && solAmount >= Number(r.threshold || 0);+ }+ if (hit) {+ const meta = RULE_KIND_META[r.kind];+ addAlertItem(item, meta.icon + ' ' + (r.label_display || r.label || meta.label));+ }}- if ((t === 'claim' || t === 'fee_claim') && ac.fees)- addAlertItem(item, 'Fee claimed');- if ((t === 'launch' || t === 'create' || t === 'mint') && ac.launch)- addAlertItem(item, 'New token launched');}function addAlertItem(item, label) {@@ -2551,86 +2610,33 @@if (!feed) return;const empty = feed.querySelector('.pd-empty');if (empty) empty.remove();- const d = item.data;+ const d = item.data || {};let detail = d.tokenSymbol || d.name || d.mint || '';- if (d.solAmount) detail += ` · ${Number(d.solAmount).toFixed(4)} SOL`;+ if (d.solAmount) detail += ' · ' + Number(d.solAmount).toFixed(4) + ' SOL';const timeStr = item.time.toLocaleTimeString('en-US', { hour12: false });const div = document.createElement('div');div.className = 'pd-feed-item';- div.innerHTML = `- <div class="pd-feed-time">${timeStr}</div>- <div class="pd-feed-tag-col"></div>- <div class="pd-feed-body">- <div class="pd-feed-title" style="color:var(--warn)">${escapeHtml(label)}</div>- <div class="pd-feed-detail">${escapeHtml(detail)}</div>- </div>- `;+ div.innerHTML =+ '<div class="pd-feed-time">' + timeStr + '</div>' ++ '<div class="pd-feed-tag-col"></div>' ++ '<div class="pd-feed-body">' ++ '<div class="pd-feed-title" style="color:var(--warn)">' + escapeHtml(label) + '</div>' ++ '<div class="pd-feed-detail">' + escapeHtml(detail) + '</div>' ++ '</div>';feed.prepend(div);while (feed.children.length > 200) feed.lastElementChild.remove();}- // Task 12: alert config is server-persisted (per user, cross-device) and- // evaluated server-side by the pumpfun-monitor cron. localStorage is only- // a fast render cache.- function applyAlertConfigToForm(cfg) {- if (cfg.graduation !== undefined) $('pd-alert-graduation').checked = cfg.graduation;- if (cfg.whale !== undefined) $('pd-alert-whale').checked = cfg.whale;- if (cfg.fees !== undefined) $('pd-alert-fees').checked = cfg.fees;- if (cfg.launch !== undefined) $('pd-alert-launch').checked = cfg.launch;- if (cfg.whaleThreshold != null) $('pd-threshold-whale').value = cfg.whaleThreshold;- if (cfg.claimThreshold != null) $('pd-threshold-claim').value = cfg.claimThreshold;- if (cfg.cooldown != null) $('pd-threshold-cooldown').value = cfg.cooldown;- if (cfg.webhookUrl != null) $('pd-alert-webhook').value = cfg.webhookUrl || '';- }-- const ALERT_FORM_IDS = [- 'pd-alert-graduation',- 'pd-alert-whale',- 'pd-alert-fees',- 'pd-alert-launch',- 'pd-threshold-whale',- 'pd-threshold-claim',- 'pd-threshold-cooldown',- 'pd-alert-webhook',- 'pd-save-alerts',- ];- // Disable the form while the authoritative server config is in flight so the- // user can't edit (and Save) stale localStorage values that the GET is about- // to overwrite. aria-busy announces the pending state to assistive tech.- function setAlertFormDisabled(disabled) {- const panel = $('page-alerts');- if (panel) panel.setAttribute('aria-busy', disabled ? 'true' : 'false');- for (const id of ALERT_FORM_IDS) {- const el = $(id);- if (el) el.disabled = disabled;- }- }-- let _alertConfigLoaded = false;+ // Entry point on nav into #alerts.async function loadAlertConfig() {- // Fetch server alert history into the feed regardless of auth state.+ updateRuleFormFields();loadServerAlerts();- if (_alertConfigLoaded) return;- setAlertFormDisabled(true);- try {- const resp = await apiFetch('/api/alerts/config');- if (resp.status === 401) return; // anonymous — keep local cache- if (!resp.ok) return;- const { data } = await resp.json();- state.alertConfig = data;- localStorage.setItem('pumpbot-alerts', JSON.stringify(data));- applyAlertConfigToForm(data);- _alertConfigLoaded = true;- } catch {- /* keep local cache */- } finally {- setAlertFormDisabled(false);- }+ await loadAlertRules();}async function loadServerAlerts() {try {- const resp = await apiFetch('/api/notifications?type=pump_alert&limit=50');+ const resp = await nativeFetch('/api/notifications?type=pump_alert&limit=50');if (!resp.ok) return;const { notifications } = await resp.json();if (!Array.isArray(notifications) || !notifications.length) return;@@ -2642,79 +2648,437 @@addAlertItem({time: new Date(n.created_at),- data: {- name: p.name,- tokenSymbol: p.symbol,- mint: p.mint,- solAmount: p.amount_sol,- },+ data: { name: p.name, tokenSymbol: p.symbol, mint: p.mint, solAmount: p.amount_sol },},- `Graduated · ${p.symbol || p.name || 'token'}`,+ serverAlertLabel(p),);});} catch {/* server history is best-effort */}}+ function serverAlertLabel(p) {+ const meta = RULE_KIND_META[p.kind] || { icon: '\u{1F514}', label: 'Alert' };+ const tok = p.symbol ? '$' + p.symbol : p.name || 'token';+ return meta.icon + ' ' + meta.label + ' · ' + tok;+ }- async function saveAlertConfig() {- const webhookUrl = $('pd-alert-webhook').value.trim();- if (webhookUrl && !/^https:\/\//i.test(webhookUrl)) {- toast('Webhook URL must start with https://', 'error');- return;+ async function loadAlertRules() {+ const list = $('pd-rules-list');+ if (!list) return;+ list.setAttribute('aria-busy', 'true');+ try {+ const resp = await nativeFetch('/api/alerts/rules');+ if (resp.status === 401) {+ state.alertRules = [];+ setRuleFormSignedOut(true);+ renderRulesSignedOut();+ return;+ }+ if (!resp.ok) {+ renderRulesError(resp.status);+ return;+ }+ const { rules } = await resp.json();+ state.alertRules = Array.isArray(rules) ? rules : [];+ localStorage.setItem('pumpbot-alerts', JSON.stringify(state.alertRules));+ setRuleFormSignedOut(false);+ renderRulesList(state.alertRules);+ populateAgentOptions();+ } catch {+ // Network error: fall back to the cached render so rules still show.+ renderRulesList(state.alertRules || []);+ } finally {+ list.setAttribute('aria-busy', 'false');}- const payload = {- graduation: $('pd-alert-graduation').checked,- whale: $('pd-alert-whale').checked,- fees: $('pd-alert-fees').checked,- launch: $('pd-alert-launch').checked,- whaleThreshold: parseFloat($('pd-threshold-whale').value) || 0,- claimThreshold: parseFloat($('pd-threshold-claim').value) || 0,- cooldown: parseInt($('pd-threshold-cooldown').value, 10) || 30,- webhookUrl: webhookUrl || null,+ }++ function renderRulesList(rules) {+ const list = $('pd-rules-list');+ if (!list) return;+ list.innerHTML = rules.length ? rules.map(ruleCardHTML).join('') : rulesEmptyHTML();+ }+ function rulesEmptyHTML() {+ return (+ '<div class="pd-empty pd-rules-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>' ++ '<div><strong>No alert rules yet</strong></div>' ++ '<div class="pd-muted">Create your first rule on the left. Rules run on our servers and fire across every device — even with this tab closed.</div>' ++ '</div>'+ );+ }+ function renderRulesSignedOut() {+ const list = $('pd-rules-list');+ if (!list) return;+ list.innerHTML =+ '<div class="pd-empty">' ++ '<div><strong>Sign in to manage alerts</strong></div>' ++ '<div class="pd-muted">Server-side alerts are tied to your account so they follow you across devices.</div>' ++ '<a class="pd-btn is-primary pd-btn-sm" href="/login" style="margin-top:.6rem">Sign in</a>' ++ '</div>';+ }+ function renderRulesError(status) {+ const list = $('pd-rules-list');+ if (!list) return;+ list.innerHTML =+ '<div class="pd-empty">' ++ '<div><strong>Couldn’t load alert rules (' + status + ')</strong></div>' ++ '<div class="pd-muted">Check your connection, then use Refresh above.</div>' ++ '</div>';+ }++ function ruleSummaryHTML(r) {+ const short = (m) => (m ? escapeHtml(m.slice(0, 4) + '…' + m.slice(-4)) : '');+ const usd = (n) => '$' + Number(n).toLocaleString('en-US');+ switch (r.kind) {+ case 'graduation':+ if (r.target_mint) return 'When <span class="pd-mono">' + short(r.target_mint) + '</span> graduates to an AMM';+ if (r.target_agent) return 'When this agent’s token graduates to an AMM';+ return 'When any pump.fun token graduates to an AMM';+ case 'price_above':+ return 'When <span class="pd-mono">' + short(r.target_mint) + '</span> market cap rises above ' + usd(r.threshold);+ case 'price_below':+ return 'When <span class="pd-mono">' + short(r.target_mint) + '</span> market cap falls below ' + usd(r.threshold);+ case 'whale_buy':+ return 'When someone buys ≥ ' + escapeHtml(String(r.threshold)) + ' SOL of <span class="pd-mono">' + short(r.target_mint) + '</span>';+ case 'new_mint':+ return 'When this agent launches a new coin';+ default:+ return '';+ }+ }+ function channelChipsHTML(r) {+ const chips = [];+ if (r.deliver_in_app) chips.push('<span class="pd-chip">In-app</span>');+ if (r.webhook_url) chips.push('<span class="pd-chip">Webhook <button class="pd-chip-action" data-rule-reveal="' + escapeHtml(r.id) + '" aria-expanded="false" aria-controls="pd-secret-' + escapeHtml(r.id) + '" type="button">secret</button></span>');+ if (r.telegram_chat) chips.push('<span class="pd-chip">Telegram</span>');+ return chips.join('');+ }+ function deliveryStatusHTML(r) {+ if (!r.recent_failures) return '';+ const fail = (r.recent_deliveries || []).find((d) => d && d.ok === false);+ const detail = fail ? fail.channel + ': ' + (fail.detail || 'failed') : '';+ return (+ '<div class="pd-rule-fail">⚠ ' + r.recent_failures + ' delivery failure' + (r.recent_failures > 1 ? 's' : '') ++ ' in 24h' + (detail ? ' — ' + escapeHtml(detail) : '') + '</div>'+ );+ }+ function ruleCardHTML(r) {+ const meta = RULE_KIND_META[r.kind] || { icon: '\u{1F514}', label: 'Alert' };+ const last = r.last_fired_at ? 'Last fired ' + relTime(r.last_fired_at) : 'Not fired yet';+ return (+ '<div class="pd-rule-card' + (r.enabled ? '' : ' is-disabled') + '" data-rule-id="' + escapeHtml(r.id) + '">' ++ '<div class="pd-rule-icon" aria-hidden="true">' + meta.icon + '</div>' ++ '<div class="pd-rule-body">' ++ '<div class="pd-rule-title">' + escapeHtml(r.label_display || r.label || meta.label) + '</div>' ++ '<div class="pd-rule-summary">' + ruleSummaryHTML(r) + '</div>' ++ '<div class="pd-rule-tags">' ++ channelChipsHTML(r) ++ '<span class="pd-rule-tag">Cooldown ' + r.cooldown_seconds + 's</span>' ++ '<span class="pd-rule-tag' + (r.last_fired_at ? '' : ' pd-muted') + '">' + last + '</span>' ++ '</div>' ++ '<div class="pd-rule-secret-row" id="pd-secret-' + escapeHtml(r.id) + '" hidden data-secret-for="' + escapeHtml(r.id) + '">' ++ '<span class="pd-muted">Signing secret:</span> ' ++ '<code class="pd-rule-secret-code">' + escapeHtml(r.webhook_secret || '—') + '</code> ' ++ '<button class="pd-btn pd-btn-xs" data-rule-copy="' + escapeHtml(r.id) + '" type="button">Copy</button>' ++ '</div>' ++ deliveryStatusHTML(r) ++ '</div>' ++ '<div class="pd-rule-actions">' ++ '<label class="pd-switch" title="' + (r.enabled ? 'Enabled — click to disable' : 'Disabled — click to enable') + '">' ++ '<input type="checkbox" data-rule-toggle="' + escapeHtml(r.id) + '" ' + (r.enabled ? 'checked' : '') + ' aria-label="' + (r.enabled ? 'Disable' : 'Enable') + ' alert: ' + escapeHtml(r.label_display || r.label || meta.label) + '" />' ++ '<span class="pd-switch-track"><span class="pd-switch-thumb"></span></span>' ++ '</label>' ++ '<button class="pd-btn pd-btn-sm" data-rule-edit="' + escapeHtml(r.id) + '" type="button">Edit</button>' ++ '<button class="pd-btn pd-btn-sm is-danger" data-rule-delete="' + escapeHtml(r.id) + '" type="button">Delete</button>' ++ '</div>' ++ '</div>'+ );+ }++ async function populateAgentOptions() {+ const sel = $('pd-rule-agent');+ if (!sel || _agentsLoaded) return;+ try {+ const resp = await nativeFetch('/api/agents');+ if (!resp.ok) return;+ const j = await resp.json();+ const agents = j.agents || j.data || [];+ const cur = sel.value;+ sel.innerHTML =+ '<option value="">Select an agent…</option>' ++ agents.map((a) => '<option value="' + escapeHtml(a.id) + '">' + escapeHtml(a.name || a.id) + '</option>').join('');+ if (cur) sel.value = cur;+ _agentsLoaded = true;+ } catch {+ /* leave the placeholder option */+ }+ }++ function updateRuleFormFields() {+ const kind = $('pd-rule-kind').value;+ const scopeGroup = $('pd-rule-scope-group');+ const mintGroup = $('pd-rule-mint-group');+ const agentGroup = $('pd-rule-agent-group');+ const thrGroup = $('pd-rule-threshold-group');+ const hint = $('pd-rule-kind-hint');+ scopeGroup.hidden = true;+ mintGroup.hidden = true;+ agentGroup.hidden = true;+ thrGroup.hidden = true;+ if (kind === 'graduation') {+ scopeGroup.hidden = false;+ const scope = $('pd-rule-scope').value;+ if (scope === 'mint') mintGroup.hidden = false;+ else if (scope === 'agent') {+ agentGroup.hidden = false;+ populateAgentOptions();+ }+ hint.textContent = 'Fires when a pump.fun token migrates to an AMM.';+ } else if (kind === 'price_above' || kind === 'price_below') {+ mintGroup.hidden = false;+ thrGroup.hidden = false;+ $('pd-rule-threshold-label').textContent = 'Market cap (USD)';+ $('pd-rule-threshold').min = '1';+ $('pd-rule-threshold').step = '1';+ $('pd-rule-threshold-hint').textContent =+ kind === 'price_above'+ ? 'Alert when the token’s USD market cap rises above this value.'+ : 'Alert when the token’s USD market cap falls below this value.';+ hint.textContent = 'Tracks the token’s live USD market cap.';+ } else if (kind === 'whale_buy') {+ mintGroup.hidden = false;+ thrGroup.hidden = false;+ $('pd-rule-threshold-label').textContent = 'Minimum buy size (SOL)';+ $('pd-rule-threshold').min = '0.01';+ $('pd-rule-threshold').step = '0.01';+ $('pd-rule-threshold-hint').textContent = 'Alert on any buy at or above this many SOL.';+ hint.textContent = 'Watches buys on a specific token.';+ } else if (kind === 'new_mint') {+ agentGroup.hidden = false;+ populateAgentOptions();+ hint.textContent = 'Fires when the selected agent launches a new coin.';+ }+ }++ function buildRulePayload() {+ const kind = $('pd-rule-kind').value;+ const p = {+ kind,+ deliver_in_app: $('pd-rule-inapp').checked,+ webhook_url: $('pd-rule-webhook').value.trim() || null,+ telegram_chat: $('pd-rule-telegram').value.trim() || null,+ cooldown_seconds: parseInt($('pd-rule-cooldown').value, 10) || 300,+ label: $('pd-rule-label').value.trim() || null,};- const btn = $('pd-save-alerts');- const btnLabel = btn ? btn.textContent : '';- if (btn) {- btn.disabled = true;- btn.textContent = 'Saving…';+ if (kind === 'graduation') {+ const scope = $('pd-rule-scope').value;+ if (scope === 'mint') p.target_mint = $('pd-rule-mint').value.trim() || null;+ else if (scope === 'agent') p.target_agent = $('pd-rule-agent').value || null;+ } else if (kind === 'price_above' || kind === 'price_below' || kind === 'whale_buy') {+ p.target_mint = $('pd-rule-mint').value.trim() || null;+ p.threshold = numOrNull($('pd-rule-threshold').value);+ } else if (kind === 'new_mint') {+ p.target_agent = $('pd-rule-agent').value || null;+ }+ return p;+ }++ function validateRuleClient(p) {+ if (p.kind === 'price_above' || p.kind === 'price_below' || p.kind === 'whale_buy') {+ if (!p.target_mint) return 'Enter a token mint address.';+ if (!(p.threshold > 0)) return 'Enter a threshold greater than 0.';+ }+ if (p.kind === 'new_mint' && !p.target_agent) return 'Select an agent.';+ if (p.kind === 'graduation') {+ const scope = $('pd-rule-scope').value;+ if (scope === 'mint' && !p.target_mint) return 'Enter a token mint address.';+ if (scope === 'agent' && !p.target_agent) return 'Select an agent.';+ }+ if (p.webhook_url && !/^https:\/\//i.test(p.webhook_url)) return 'Webhook URL must start with https://';+ if (!p.deliver_in_app && !p.webhook_url && !p.telegram_chat) return 'Enable at least one delivery channel.';+ if (!(p.cooldown_seconds >= 5)) return 'Cooldown must be at least 5 seconds.';+ return null;+ }++ async function saveRule() {+ const payload = buildRulePayload();+ const err = validateRuleClient(payload);+ if (err) {+ toast(err, 'error');+ return;}+ const btn = $('pd-rule-save');+ btn.disabled = true;+ btn.textContent = _ruleEditingId ? 'Saving…' : 'Creating…';try {- const csrf = await getCsrfToken();+ const csrf = await nativeCsrf();const headers = { 'Content-Type': 'application/json' };if (csrf) headers['x-csrf-token'] = csrf;- const resp = await apiFetch('/api/alerts/config', {- method: 'PUT',- headers,- body: JSON.stringify(payload),- });+ const path = _ruleEditingId ? '/api/alerts/rules/' + _ruleEditingId : '/api/alerts/rules';+ const httpMethod = _ruleEditingId ? 'PATCH' : 'POST';+ const resp = await nativeFetch(path, { method: httpMethod, headers, body: JSON.stringify(payload) });if (resp.status === 401) {toast('Sign in to save alerts across devices', 'error');+ setRuleFormSignedOut(true);return;}if (!resp.ok) {- const err = await resp.json().catch(() => ({}));- toast(- err.error_description || err.error || `Save failed (${resp.status})`,- 'error',- );+ const e = await resp.json().catch(() => ({}));+ toast(e.error_description || e.error || 'Save failed (' + resp.status + ')', 'error');return;}- const { data } = await resp.json();- state.alertConfig = data;- localStorage.setItem('pumpbot-alerts', JSON.stringify(data));- applyAlertConfigToForm(data);- toast('Alert settings saved', 'success');+ const data = await resp.json();+ const wasEditing = !!_ruleEditingId;+ toast(wasEditing ? 'Alert rule updated' : 'Alert rule created', 'success');+ if (data.rule && data.rule.webhook_secret && payload.webhook_url) {+ toast('Webhook secret ready — open “secret” on the rule to copy it.', 'info');+ }+ resetRuleForm();+ await loadAlertRules();} catch (e) {toast('Network error: ' + (e.message || 'save failed'), 'error');} finally {- if (btn) {- btn.disabled = false;- btn.textContent = btnLabel;+ btn.disabled = false;+ btn.textContent = _ruleEditingId ? 'Update alert rule' : 'Create alert rule';+ }+ }++ function editRule(id) {+ const r = (state.alertRules || []).find((x) => x.id === id);+ if (!r) return;+ _ruleEditingId = id;+ $('pd-rule-kind').value = r.kind;+ if (r.kind === 'graduation') {+ $('pd-rule-scope').value = r.target_mint ? 'mint' : r.target_agent ? 'agent' : 'global';+ }+ $('pd-rule-mint').value = r.target_mint || '';+ $('pd-rule-threshold').value = r.threshold != null ? r.threshold : '';+ $('pd-rule-label').value = r.label || '';+ $('pd-rule-inapp').checked = !!r.deliver_in_app;+ $('pd-rule-webhook').value = r.webhook_url || '';+ $('pd-rule-telegram').value = r.telegram_chat || '';+ $('pd-rule-cooldown').value = r.cooldown_seconds || 300;+ updateRuleFormFields();+ // Agent options may load async; set the value once they're present.+ const applyAgent = () => {+ if (r.target_agent) $('pd-rule-agent').value = r.target_agent;+ };+ applyAgent();+ populateAgentOptions().then(applyAgent);+ $('pd-rule-form-title').textContent = 'Edit alert rule';+ $('pd-rule-save').textContent = 'Update alert rule';+ $('pd-rule-cancel').hidden = false;+ $('page-alerts').scrollIntoView({ behavior: 'smooth', block: 'start' });+ }++ function resetRuleForm() {+ _ruleEditingId = null;+ $('pd-rule-kind').value = 'graduation';+ $('pd-rule-scope').value = 'global';+ $('pd-rule-mint').value = '';+ if ($('pd-rule-agent')) $('pd-rule-agent').value = '';+ $('pd-rule-threshold').value = '';+ $('pd-rule-label').value = '';+ $('pd-rule-inapp').checked = true;+ $('pd-rule-webhook').value = '';+ $('pd-rule-telegram').value = '';+ $('pd-rule-cooldown').value = '300';+ updateRuleFormFields();+ $('pd-rule-form-title').textContent = 'New alert rule';+ $('pd-rule-save').textContent = 'Create alert rule';+ $('pd-rule-cancel').hidden = true;+ }++ function setRuleFormSignedOut(disabled) {+ const note = $('pd-rule-signin-note');+ if (note) note.hidden = !disabled;+ const ids = ['pd-rule-kind', 'pd-rule-scope', 'pd-rule-mint', 'pd-rule-agent', 'pd-rule-threshold', 'pd-rule-label', 'pd-rule-inapp', 'pd-rule-webhook', 'pd-rule-telegram', 'pd-rule-cooldown', 'pd-rule-save', 'pd-rule-cancel'];+ ids.forEach((id) => {+ const el = $(id);+ if (el) el.disabled = disabled;+ });+ }++ async function deleteRule(id) {+ const r = (state.alertRules || []).find((x) => x.id === id);+ const name = r ? ' (' + (r.label_display || r.label || r.kind) + ')' : '';+ if (!confirm('Delete this alert rule' + name + '? This can’t be undone.')) return;+ try {+ const csrf = await nativeCsrf();+ const headers = {};+ if (csrf) headers['x-csrf-token'] = csrf;+ const resp = await nativeFetch('/api/alerts/rules/' + id, { method: 'DELETE', headers });+ if (!resp.ok && resp.status !== 404) {+ const e = await resp.json().catch(() => ({}));+ toast(e.error_description || 'Delete failed (' + resp.status + ')', 'error');+ return;+ }+ toast('Alert rule deleted', 'success');+ if (_ruleEditingId === id) resetRuleForm();+ await loadAlertRules();+ } catch (e) {+ toast('Network error: ' + (e.message || 'delete failed'), 'error');+ }+ }++ async function toggleRule(id, enabled) {+ try {+ const csrf = await nativeCsrf();+ const headers = { 'Content-Type': 'application/json' };+ if (csrf) headers['x-csrf-token'] = csrf;+ const resp = await nativeFetch('/api/alerts/rules/' + id, { method: 'PATCH', headers, body: JSON.stringify({ enabled }) });+ if (!resp.ok) {+ const e = await resp.json().catch(() => ({}));+ toast(e.error_description || 'Update failed (' + resp.status + ')', 'error');+ await loadAlertRules();+ return;}+ const data = await resp.json();+ const idx = (state.alertRules || []).findIndex((x) => x.id === id);+ if (idx >= 0 && data.rule) {+ state.alertRules[idx] = data.rule;+ const card = document.querySelector('[data-rule-id="' + (window.CSS && CSS.escape ? CSS.escape(id) : id) + '"]');+ if (card) card.classList.toggle('is-disabled', !enabled);+ }+ toast(enabled ? 'Rule enabled' : 'Rule disabled', 'success');+ } catch {+ toast('Network error', 'error');+ await loadAlertRules();+ }+ }++ function copyRuleSecret(id) {+ const r = (state.alertRules || []).find((x) => x.id === id);+ if (!r || !r.webhook_secret) return;+ if (navigator.clipboard) {+ navigator.clipboard.writeText(r.webhook_secret).then(+ () => toast('Webhook secret copied', 'success'),+ () => toast('Copy failed — select the text manually', 'error'),+ );}}+ function onRulesListClick(e) {+ const t = e.target.closest('[data-rule-edit],[data-rule-delete],[data-rule-reveal],[data-rule-copy]');+ if (!t) return;+ if (t.dataset.ruleEdit) editRule(t.dataset.ruleEdit);+ else if (t.dataset.ruleDelete) deleteRule(t.dataset.ruleDelete);+ else if (t.dataset.ruleReveal) {+ const sel = '[data-secret-for="' + (window.CSS && CSS.escape ? CSS.escape(t.dataset.ruleReveal) : t.dataset.ruleReveal) + '"]';+ const row = document.querySelector(sel);+ if (row) {+ row.hidden = !row.hidden;+ t.setAttribute('aria-expanded', row.hidden ? 'false' : 'true');+ }+ } else if (t.dataset.ruleCopy) copyRuleSecret(t.dataset.ruleCopy);+ }+ function onRulesListChange(e) {+ const t = e.target.closest('[data-rule-toggle]');+ if (!t) return;+ toggleRule(t.dataset.ruleToggle, t.checked);+ }+// ── Watches ──────────────────────────────────────────────────async function refreshWatches() {@@ -4239,15 +4603,6 @@$('pd-cfg-rpc-url').value = state.rpcUrl;$('pd-api-endpoint-display').textContent = state.apiUrl;- const ac = state.alertConfig;- if (ac.graduation !== undefined) $('pd-alert-graduation').checked = ac.graduation;- if (ac.whale !== undefined) $('pd-alert-whale').checked = ac.whale;- if (ac.fees !== undefined) $('pd-alert-fees').checked = ac.fees;- if (ac.launch !== undefined) $('pd-alert-launch').checked = ac.launch;- if (ac.whaleThreshold) $('pd-threshold-whale').value = ac.whaleThreshold;- if (ac.claimThreshold) $('pd-threshold-claim').value = ac.claimThreshold;- if (ac.cooldown) $('pd-threshold-cooldown').value = ac.cooldown;-// Sidebar navdocument.querySelectorAll('.pd-sidebar nav a').forEach((a) => {a.addEventListener('click', (e) => {@@ -4307,8 +4662,14 @@$('pd-refresh-claims').addEventListener('click', refreshClaims);$('pd-export-claims').addEventListener('click', exportClaims);- // Alerts- $('pd-save-alerts').addEventListener('click', saveAlertConfig);+ // Alerts (server-persisted rules)+ $('pd-rule-save').addEventListener('click', saveRule);+ $('pd-rule-cancel').addEventListener('click', resetRuleForm);+ $('pd-rules-refresh').addEventListener('click', loadAlertRules);+ $('pd-rule-kind').addEventListener('change', updateRuleFormFields);+ $('pd-rule-scope').addEventListener('change', updateRuleFormFields);+ $('pd-rules-list').addEventListener('click', onRulesListClick);+ $('pd-rules-list').addEventListener('change', onRulesListChange);// Scanner$('pd-scan-token').addEventListener('click', scanToken);@@ -4321,9 +4682,6 @@$('pd-vanity-start').addEventListener('click', startVanity);$('pd-vanity-stop').addEventListener('click', stopVanity);- if (state.alertConfig.webhookUrl)- $('pd-alert-webhook').value = state.alertConfig.webhookUrl;-// Animations + TTS (Task 11)$('pd-speak-btn').addEventListener('click', () => agentAction('speak'));$('pd-speak-stop').addEventListener('click', stopSpeak);diff --git a/public/.well-known/3d-agent-card.schema.json b/public/.well-known/3d-agent-card.schema.jsonindex f02bb0cfa..93fafd0db 100644--- a/public/.well-known/3d-agent-card.schema.json+++ b/public/.well-known/3d-agent-card.schema.json@@ -39,7 +39,7 @@"registrations": {"type": "array",- "description": "ERC-8004 on-chain registrations as CAIP-10 references.",+ "description": "On-chain registrations as CAIP-10 references. EVM (ERC-8004 IdentityRegistry): eip155:<chainId>:0x<registry>. Solana (Metaplex Core agent collection): solana:<genesisHash>:<collectionAddress>, with agentId set to the asset address.","items": {"type": "object","required": ["agentId", "agentRegistry"],@@ -47,12 +47,30 @@"agentId": { "type": ["integer", "string"] },"agentRegistry": {"type": "string",- "pattern": "^eip155:[0-9]+:0x[a-fA-F0-9]{40}$"+ "pattern": "^(eip155:[0-9]+:0x[a-fA-F0-9]{40}|solana:[1-9A-HJ-NP-Za-km-z]{32,44}:[1-9A-HJ-NP-Za-km-z]{32,44})$"}}}},+ "onchain": {+ "type": "object",+ "description": "Canonical deployment descriptor for the agent's primary on-chain identity. Consumed by the three.ws on-chain badge (src/shared/onchain-badge.js). For Solana, contract_or_mint is the Metaplex Core asset address.",+ "required": ["family", "chain"],+ "properties": {+ "family": { "type": "string", "enum": ["solana", "evm"] },+ "chain": { "type": "string", "description": "CAIP-2 chain id, e.g. solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp or eip155:8453." },+ "cluster": { "type": "string", "enum": ["mainnet", "devnet"] },+ "contract_or_mint": { "type": "string" },+ "collection": { "type": "string" },+ "metadata_uri": { "type": "string" },+ "owner": { "type": "string" },+ "tx_hash": { "type": "string" },+ "onchain_id": { "type": "string" },+ "confirmed_at": { "type": "string" }+ }+ },+"supportedTrust": {"type": "array","items": { "type": "string", "enum": ["reputation", "validation", "tee"] }diff --git a/public/.well-known/three-ws-agent.json b/public/.well-known/three-ws-agent.jsondeleted file mode 100644index 4f6604b1c..000000000--- a/public/.well-known/three-ws-agent.json+++ /dev/null@@ -1,75 +0,0 @@-{- "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/agent-passport.html b/public/agent-passport.htmlindex 36a1994c3..3bc3747d5 100644--- a/public/agent-passport.html+++ b/public/agent-passport.html@@ -814,6 +814,18 @@setLive(!document.hidden);});+ function renderValidationBadge(v, network) {+ if (!v || typeof v.passed !== 'boolean') return '';+ const explorer = v.signature+ ? `https://explorer.solana.com/tx/${v.signature}${network === 'devnet' ? '?cluster=devnet' : ''}`+ : null;+ const proof = v.proof_uri || explorer || '#';+ const label = v.passed ? '✓ model verified' : '✗ model failed';+ const cls = v.passed ? 'ok' : 'warn';+ const title = `glTF/schema validation by platform validator${v.proof_hash ? ` · proof ${String(v.proof_hash).slice(0, 12)}…` : ''}`;+ return `<a class="pill ${cls}" href="${escapeHtml(proof)}" target="_blank" rel="noopener" title="${escapeHtml(title)}" style="text-decoration:none">${label}</a>`;+ }+function renderIdentity(card, rep, asset, network, history = []) {const id = card?.identity || {};const name = card?.name || '(unindexed agent)';@@ -835,6 +847,7 @@<div class="identity-name">${escapeHtml(name)}</div><span class="pill ${network === 'mainnet' ? 'ok' : 'warn'}">${network}</span>${vanity ? `<span class="pill vanity" title="Custom vanity address">✦ ${escapeHtml(vanity)}</span>` : ''}+ ${renderValidationBadge(card?.validation, network)}</div>${card?.description ? `<div class="muted" style="margin-top:.2rem">${escapeHtml(card.description)}</div>` : ''}<div class="identity-meta">@@ -1167,6 +1180,8 @@case 'threews.feedback.v1':return `score ${p.score}/5${p.task_id ? ` for task ${p.task_id}` : ''}${p.source ? ` (${p.source})` : ''}`;case 'threews.validation.v1':+ if (p.subkind === 'glb-schema')+ return `model validation ${p.passed ? '✓ passed' : '✗ failed'}${p.proof_hash ? ` (proof ${String(p.proof_hash).slice(0, 12)}…)` : ''}`;return `validation ${p.passed ? '✓ passed' : '✗ failed'}${p.task_hash ? ` (task hash ${String(p.task_hash).slice(0, 12)}…)` : ''}`;case 'threews.task.v1':return `task offered: ${p.task_id}`;diff --git a/public/changelog.json b/public/changelog.jsonindex bf7315c05..22b75b314 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-15T03:22:25.663Z",+ "generated_at": "2026-06-15T03:51:37.984Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -16,6 +16,17 @@"improvement"]},+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "Agent reputation now reflects a real pump.fun track record",+ "summary": "An agent's pump.fun behavior now feeds its reputation and shows on its passport. When the wallet behind an agent graduates a token, claims creator fees, makes a whale-sized buy, or launches a coin, that moment is recorded as a typed signal — graduating a token counts for more than a routine claim, and a flagged or brand-new-account claim counts against. These signals roll up into the agent's Solana reputation score and appear on the public agent passport, readable by anyone without a wallet. The live pump.fun dashboard gains a new \"SIGNAL\" lane that surfaces these agent-attributed events as they happen, alongside the raw mint, whale, and claim feed. The processor behind this used to sit idle unless an optional external service was configured; it now runs continuously off the platform's own live pump.fun stream with no external dependency, records only genuinely new events so nothing is double-counted, and attributes each one to the agent behind the wallet.",+ "link": "/pump-dashboard",+ "tags": [+ "improvement",+ "fix"+ ]+ },{"date": "2026-06-15","type": "update",@@ -37,6 +48,26 @@"infra"]},+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "Buy and sell USDC-paired coins straight from the trade widget",+ "summary": "The in-world trade widget now speaks both currencies. Open Buy on a coin and the widget reads its real pairing from the chain: a SOL coin asks for SOL exactly as before, while a USDC-paired coin denominates the amount in USDC, shows your wallet's USDC balance, and prices and settles the trade in USDC. A new Sell tab lets you sell a coin you hold back to its quote asset — pick 25%, 50%, or Max of your balance, see the live payout, and sign once; for USDC coins the payout account is opened for you automatically in the same transaction. Every state is handled: not enough USDC offers a one-tap Add-funds flow, a moved price explains your slippage, and a cancelled signature is quietly acknowledged. The whole flow is your own wallet, signed in your browser, with a Solscan link the moment it lands.",+ "link": "/play",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "Clearer launch & trade errors, and a graduated badge on coins",+ "summary": "When a token launch or an in-world trade can't go through, the app now tells you exactly why and what to do next — \"Not enough SOL to cover the launch + network fees,\" \"Price moved beyond your slippage limit,\" \"You cancelled the signature in your wallet,\" or \"Couldn't reach the Solana network\" — instead of a single catch-all \"Connection error.\" Coins also show their lifecycle at a glance: the trade panel carries a badge marking whether a coin is still on its bonding curve or has graduated to the PumpSwap AMM, so a graduated coin is unmistakable. Backed by new end-to-end browser tests that drive the full four-step launch flow and the buy/sell widget so this conversion path can't silently break.",+ "link": "/pump-dashboard",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-15","type": "update",@@ -48,6 +79,37 @@"improvement"]},+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "Live coin status — price, market cap and graduation — now unified across the platform",+ "summary": "The launches feed, agent profile token panels, and the in-world agent coin card now share one live coin-status display, so every place that shows a coin reads the same numbers from the same source. Launch cards now stream the coin's real logo, USD price, market cap, a graduation progress ring and time since launch — not just market cap — with the orbital fingerprint as a placeholder until the logo loads. Agent profiles show a live price-and-graduation chip in the token panel and per-coin market caps in the launch history, and the agent home card's market readout is now consistent with the rest of the platform. Each card refreshes on its own and degrades gracefully to a Retry if pump.fun is briefly unreachable.",+ "link": "/launches",+ "tags": [+ "improvement"+ ]+ },+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "On-chain model validation for Solana agents",+ "summary": "Solana agents now get the same verifiable, on-chain glTF/model validation that EVM agents get from the ValidationRegistry — no contract to deploy. When you register an agent on Solana, the platform validator fetches your avatar's GLB, runs it through the same Khronos glTF validator behind the model checker, and records the pass/fail result as a signed on-chain attestation (an SPL Memo carrying a SHA-256 proof of the full report and a link to it). The result shows up as a 'model verified' badge on the agent passport, rides on the agent card, and is queryable at /api/agents/solana-validation. Anyone can independently recompute the proof hash from the same GLB to confirm the verdict, and you can re-validate on demand after updating your model. Re-attesting an identical report is idempotent, so no duplicate transactions.",+ "link": null,+ "tags": [+ "feature",+ "security"+ ]+ },+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "Pump dashboard alerts now run server-side — fire across devices even with the tab closed",+ "summary": "Alert rules moved from your browser to our servers, so they fire whether or not a dashboard tab is open and follow you across every device you sign in on. Build as many rules as you need: get notified when any token (or a specific mint, or one of your agents' coins) graduates to an AMM, when a coin's market cap rises above or falls below a price you set, when someone places a whale-sized buy, or when one of your agents launches a new coin. Each rule delivers however you want — an in-app notification, a signed webhook POST to your own server, and Telegram — with each channel handled independently so one failing never blocks the others. Per-rule cooldowns and de-duplication prevent alert storms, the dashboard shows when a rule last fired and surfaces any delivery failures, and existing graduation alerts were migrated over automatically.",+ "link": "/pump-dashboard",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-15","type": "update",@@ -122,6 +184,17 @@"improvement"]},+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "three.ws can now register itself on-chain on Solana",+ "summary": "Alongside its ERC-8004 identity, three.ws can now mint its own agent on Solana — as a Metaplex Core asset in the official \"three.ws Agents\" collection, exactly the way agents you deploy through the platform are registered. A one-command tool builds the platform's 3D Agent Card, verifies the avatar's SHA-256 against the exact GLB bytes served (so the model can't be silently swapped), pins the metadata, mints the asset into the collection, and writes the result back into the public discovery documents at three.ws/.well-known so any wallet, explorer, or agent can resolve and verify three.ws. The discovery card and its schema now carry Solana identities (CAIP-10) alongside EVM ones, and the platform agent's on-chain badge links straight to its Solana passport.",+ "link": "/.well-known/agent-registration.json",+ "tags": [+ "feature",+ "infra"+ ]+ },{"date": "2026-06-15","type": "update",@@ -133,6 +206,17 @@"infra"]},+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "USDC-paired agent coins now record and display correct trade amounts",+ "summary": "Coins launched against USDC are now tracked in the right currency end to end. Every buy and sell records which quote asset it actually used and how much of it moved — USDC amounts in USDC, SOL amounts in SOL — instead of quietly storing a USDC trade as if it were SOL and reporting a price and market cap that were off by orders of magnitude. Portfolios now subtotal holdings separately by quote asset, so your SOL positions and USDC positions each get their own value, cost basis, and unrealized P&L with no more mixing of mismatched units. Existing SOL trades are unchanged, and historical rows were backfilled as SOL-paired so nothing shifts.",+ "link": null,+ "tags": [+ "fix",+ "feature"+ ]+ },{"date": "2026-06-14","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 1cafb8784..cdafca0ce 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>Agent reputation now reflects a real pump.fun track record</title>+ <link>https://three.ws/pump-dashboard</link>+ <guid isPermaLink="false">2026-06-15:Agent reputation now reflects a real pump.fun track record</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>An agent's pump.fun behavior now feeds its reputation and shows on its passport. When the wallet behind an agent graduates a token, claims creator fees, makes a whale-sized buy, or launches a coin, that moment is recorded as a typed signal — graduating a token counts for more than a routine claim, and a flagged or brand-new-account claim counts against. These signals roll up into the agent's Solana reputation score and appear on the public agent passport, readable by anyone without a wallet. The live pump.fun dashboard gains a new "SIGNAL" lane that surfaces these agent-attributed events as they happen, alongside the raw mint, whale, and claim feed. The processor behind this used to sit idle unless an optional external service was configured; it now runs continuously off the platform's own live pump.fun stream with no external dependency, records only genuinely new events so nothing is double-counted, and attributes each one to the agent behind the wallet.</description>+ </item><item><title>Agents can autonomously trade USDC-paired coins</title><link>https://three.ws/pump-dashboard</link>@@ -30,6 +38,22 @@<category>improvement</category><description>Coins launched through three.ws with autopilot enabled now have their buybacks and creator-fee distributions executed automatically on an hourly schedule, instead of waiting for a manual trigger. A new balance watchdog checks every Solana signer the platform uses to pay on-chain fees and alerts the team the moment one runs low, so autopilot never silently stalls for lack of gas. No action needed from coin owners — it just works in the background.</description></item>+ <item>+ <title>Buy and sell USDC-paired coins straight from the trade widget</title>+ <link>https://three.ws/play</link>+ <guid isPermaLink="false">2026-06-15:Buy and sell USDC-paired coins straight from the trade widget</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The in-world trade widget now speaks both currencies. Open Buy on a coin and the widget reads its real pairing from the chain: a SOL coin asks for SOL exactly as before, while a USDC-paired coin denominates the amount in USDC, shows your wallet's USDC balance, and prices and settles the trade in USDC. A new Sell tab lets you sell a coin you hold back to its quote asset — pick 25%, 50%, or Max of your balance, see the live payout, and sign once; for USDC coins the payout account is opened for you automatically in the same transaction. Every state is handled: not enough USDC offers a one-tap Add-funds flow, a moved price explains your slippage, and a cancelled signature is quietly acknowledged. The whole flow is your own wallet, signed in your browser, with a Solscan link the moment it lands.</description>+ </item>+ <item>+ <title>Clearer launch & trade errors, and a graduated badge on coins</title>+ <link>https://three.ws/pump-dashboard</link>+ <guid isPermaLink="false">2026-06-15:Clearer launch & trade errors, and a graduated badge on coins</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>When a token launch or an in-world trade can't go through, the app now tells you exactly why and what to do next — "Not enough SOL to cover the launch + network fees," "Price moved beyond your slippage limit," "You cancelled the signature in your wallet," or "Couldn't reach the Solana network" — instead of a single catch-all "Connection error." Coins also show their lifecycle at a glance: the trade panel carries a badge marking whether a coin is still on its bonding curve or has graduated to the PumpSwap AMM, so a graduated coin is unmistakable. Backed by new end-to-end browser tests that drive the full four-step launch flow and the buy/sell widget so this conversion path can't silently break.</description>+ </item><item><title>Launchpad Studio: pick your avatar from your own agents and the gallery</title><link>https://three.ws/launchpad</link>@@ -38,6 +62,30 @@<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>Live coin status — price, market cap and graduation — now unified across the platform</title>+ <link>https://three.ws/launches</link>+ <guid isPermaLink="false">2026-06-15:Live coin status — price, market cap and graduation — now unified across the platform</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>The launches feed, agent profile token panels, and the in-world agent coin card now share one live coin-status display, so every place that shows a coin reads the same numbers from the same source. Launch cards now stream the coin's real logo, USD price, market cap, a graduation progress ring and time since launch — not just market cap — with the orbital fingerprint as a placeholder until the logo loads. Agent profiles show a live price-and-graduation chip in the token panel and per-coin market caps in the launch history, and the agent home card's market readout is now consistent with the rest of the platform. Each card refreshes on its own and degrades gracefully to a Retry if pump.fun is briefly unreachable.</description>+ </item>+ <item>+ <title>On-chain model validation for Solana agents</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-15:On-chain model validation for Solana agents</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Solana agents now get the same verifiable, on-chain glTF/model validation that EVM agents get from the ValidationRegistry — no contract to deploy. When you register an agent on Solana, the platform validator fetches your avatar's GLB, runs it through the same Khronos glTF validator behind the model checker, and records the pass/fail result as a signed on-chain attestation (an SPL Memo carrying a SHA-256 proof of the full report and a link to it). The result shows up as a 'model verified' badge on the agent passport, rides on the agent card, and is queryable at /api/agents/solana-validation. Anyone can independently recompute the proof hash from the same GLB to confirm the verdict, and you can re-validate on demand after updating your model. Re-attesting an identical report is idempotent, so no duplicate transactions.</description>+ </item>+ <item>+ <title>Pump dashboard alerts now run server-side — fire across devices even with the tab closed</title>+ <link>https://three.ws/pump-dashboard</link>+ <guid isPermaLink="false">2026-06-15:Pump dashboard alerts now run server-side — fire across devices even with the tab closed</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Alert rules moved from your browser to our servers, so they fire whether or not a dashboard tab is open and follow you across every device you sign in on. Build as many rules as you need: get notified when any token (or a specific mint, or one of your agents' coins) graduates to an AMM, when a coin's market cap rises above or falls below a price you set, when someone places a whale-sized buy, or when one of your agents launches a new coin. Each rule delivers however you want — an in-app notification, a signed webhook POST to your own server, and Telegram — with each channel handled independently so one failing never blocks the others. Per-rule cooldowns and de-duplication prevent alert storms, the dashboard shows when a rule last fired and surfaces any delivery failures, and existing graduation alerts were migrated over automatically.</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>@@ -94,6 +142,14 @@<category>infra</category><description>The recent-graduations feed and the graduation data behind pump.fun signals and MCP tools now refresh continuously in the background, instead of only updating while someone had the live feed open. A new scheduled job listens to the real pump.fun migration stream and records graduations as they happen, so the feed shows up-to-date tokens even after quiet periods. Graduation data is also served straight from our own live records, so it never silently falls back to an empty list.</description></item>+ <item>+ <title>three.ws can now register itself on-chain on Solana</title>+ <link>https://three.ws/.well-known/agent-registration.json</link>+ <guid isPermaLink="false">2026-06-15:three.ws can now register itself on-chain on Solana</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Alongside its ERC-8004 identity, three.ws can now mint its own agent on Solana — as a Metaplex Core asset in the official "three.ws Agents" collection, exactly the way agents you deploy through the platform are registered. A one-command tool builds the platform's 3D Agent Card, verifies the avatar's SHA-256 against the exact GLB bytes served (so the model can't be silently swapped), pins the metadata, mints the asset into the collection, and writes the result back into the public discovery documents at three.ws/.well-known so any wallet, explorer, or agent can resolve and verify three.ws. The discovery card and its schema now carry Solana identities (CAIP-10) alongside EVM ones, and the platform agent's on-chain badge links straight to its Solana passport.</description>+ </item><item><title>three.ws now registers itself as an on-chain agent (ERC-8004)</title><link>https://three.ws/changelog</link>@@ -102,6 +158,14 @@<category>feature</category><description>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.</description></item>+ <item>+ <title>USDC-paired agent coins now record and display correct trade amounts</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-15:USDC-paired agent coins now record and display correct trade amounts</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Coins launched against USDC are now tracked in the right currency end to end. Every buy and sell records which quote asset it actually used and how much of it moved — USDC amounts in USDC, SOL amounts in SOL — instead of quietly storing a USDC trade as if it were SOL and reporting a price and market cap that were off by orders of magnitude. Portfolios now subtotal holdings separately by quote asset, so your SOL positions and USDC positions each get their own value, cost basis, and unrealized P&L with no more mixing of mismatched units. Existing SOL trades are unchanged, and historical rows were backfilled as SOL-paired so nothing shifts.</description>+ </item><item><title>Building 3D AI Agents Live</title><link>https://three.ws/events/build-3d-agents-live</link>diff --git a/public/features.json b/public/features.jsonindex 84709f3f5..f48556910 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-15T03:22:25.455Z",+ "generated_at": "2026-06-15T03:51:37.970Z","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.cssindex be917f7cc..195d995a6 100644--- a/public/pump-dashboard.css+++ b/public/pump-dashboard.css@@ -970,3 +970,193 @@ code, .pd-mono-inline {.pd-main { margin-left: 0; padding: 1rem; }.pd-feed-item { grid-template-columns: 56px 60px 1fr; gap: 0.5rem; padding: 0.55rem 0.75rem; }}++/* ── Alerts: rule builder + rule list ────────────────────── */++.pd-alert-grid {+ display: grid;+ grid-template-columns: minmax(0, 360px) 1fr;+ gap: 1rem;+ margin-bottom: 1rem;+ align-items: start;+}++@media (max-width: 960px) {+ .pd-alert-grid { grid-template-columns: 1fr; }+}++.pd-muted { color: var(--ink-dim); }++.pd-link { color: var(--accent); }++.pd-field-hint {+ margin-top: 0.3rem;+ font-size: 0.72rem;+ line-height: 1.45;+ color: var(--ink-dim);+}++/* Delivery channels block in the create/edit form */+.pd-rule-channels {+ margin: 0.4rem 0 0.9rem;+ padding: 0.85rem;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ background: rgba(255, 255, 255, 0.02);+}+.pd-rule-channels-title {+ font-size: 0.7rem;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--ink-dim);+ margin-bottom: 0.6rem;+}+.pd-check {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: 0.85rem;+ color: var(--ink);+ cursor: pointer;+ margin-bottom: 0.7rem;+}+.pd-check input { accent-color: var(--accent); width: 15px; height: 15px; }++.pd-rule-signin-note {+ margin-top: 0.7rem;+ font-size: 0.78rem;+ color: var(--ink-dim);+}++/* Rule list */+.pd-rules-list {+ display: flex;+ flex-direction: column;+ gap: 0.6rem;+ padding: 0.75rem;+ transition: opacity 0.15s ease;+}+.pd-rules-list[aria-busy='true'] { opacity: 0.5; }+.pd-rules-empty strong { color: var(--ink); }++.pd-rule-card {+ display: grid;+ grid-template-columns: 34px 1fr auto;+ gap: 0.75rem;+ align-items: start;+ padding: 0.85rem;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ background: rgba(255, 255, 255, 0.025);+ transition: border-color 0.12s ease, background 0.12s ease, opacity 0.12s ease;+}+.pd-rule-card:hover { border-color: var(--stroke-strong); background: rgba(255, 255, 255, 0.04); }+.pd-rule-card.is-disabled { opacity: 0.55; }++.pd-rule-icon { font-size: 1.25rem; line-height: 1.6; text-align: center; }++.pd-rule-body { min-width: 0; }+.pd-rule-title {+ font-weight: 600;+ font-size: 0.9rem;+ color: var(--ink);+ margin-bottom: 0.15rem;+ overflow-wrap: anywhere;+}+.pd-rule-summary { font-size: 0.8rem; color: var(--ink-dim); line-height: 1.5; }+.pd-rule-summary .pd-mono { color: var(--ink); }++.pd-rule-tags {+ display: flex;+ flex-wrap: wrap;+ gap: 0.4rem;+ margin-top: 0.55rem;+}+.pd-rule-tag {+ font-size: 0.68rem;+ color: var(--ink-dim);+ padding: 0.12rem 0.45rem;+ border: 1px solid var(--stroke);+ border-radius: 999px;+}+.pd-chip {+ display: inline-flex;+ align-items: center;+ gap: 0.3rem;+ font-size: 0.68rem;+ color: var(--ink);+ padding: 0.12rem 0.45rem;+ border: 1px solid var(--stroke-strong);+ border-radius: 999px;+ background: var(--accent-soft);+}+.pd-chip-action {+ background: none;+ border: none;+ color: var(--accent);+ font: inherit;+ font-size: 0.66rem;+ cursor: pointer;+ padding: 0;+ text-decoration: underline;+}++.pd-rule-secret-row {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 0.4rem;+ margin-top: 0.5rem;+ font-size: 0.72rem;+}+.pd-rule-secret-code {+ font-family: var(--font-mono);+ font-size: 0.7rem;+ color: var(--ink);+ background: rgba(255, 255, 255, 0.06);+ padding: 0.15rem 0.4rem;+ border-radius: 4px;+ overflow-wrap: anywhere;+}++.pd-rule-fail {+ margin-top: 0.5rem;+ font-size: 0.74rem;+ color: var(--warn);+}++.pd-rule-actions {+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: 0.4rem;+}++.pd-btn-xs { padding: 0.18rem 0.45rem; font-size: 0.68rem; }++.pd-feed-legend { font-size: 0.72rem; color: var(--ink-dim); margin-left: 0.6rem; }++/* Enable/disable switch */+.pd-switch { position: relative; display: inline-flex; cursor: pointer; }+.pd-switch input { position: absolute; opacity: 0; width: 100%; height: 100%; margin: 0; cursor: pointer; }+.pd-switch-track {+ width: 34px;+ height: 19px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.12);+ border: 1px solid var(--stroke);+ transition: background 0.15s ease;+ display: inline-flex;+ align-items: center;+ padding: 0 2px;+}+.pd-switch-thumb {+ width: 13px;+ height: 13px;+ border-radius: 50%;+ background: var(--ink);+ transition: transform 0.15s ease;+}+.pd-switch input:checked + .pd-switch-track { background: var(--accent); }+.pd-switch input:checked + .pd-switch-track .pd-switch-thumb { transform: translateX(15px); }+.pd-switch input:focus-visible + .pd-switch-track { outline: 2px solid var(--accent); outline-offset: 2px; }diff --git a/scripts/build-vercel.mjs b/scripts/build-vercel.mjsindex 740473e78..a040018e8 100644--- a/scripts/build-vercel.mjs+++ b/scripts/build-vercel.mjs@@ -210,6 +210,11 @@ try {// undeclared api/ imports — the classes behind the 2026-06-11 outage —// instead of 18 minutes into NFT tracing or, worse, at runtime.run('audit:deploy', 'node scripts/audit-deploy-artifacts.mjs'),+ // Solana address parity + on-chain provenance: fails the build on a+ // hardcoded non-$THREE coin or a drifted program ID/mint across the repo,+ // and confirms the canonical accounts are the right kind on mainnet+ // (live check degrades to a warning when the RPC is unreachable).+ run('verify:solana', 'node scripts/verify-solana-parity.mjs'),// MCP registry manifests: catches version drift, >100-char descriptions,// and mcpName mismatches at build time instead of on publish day.run('audit:mcp', 'node scripts/audit-mcp-manifests.mjs'),diff --git a/scripts/check-chart-screen.mjs b/scripts/check-chart-screen.mjsindex 8c281b395..3eea468da 100644--- a/scripts/check-chart-screen.mjs+++ b/scripts/check-chart-screen.mjs@@ -7,7 +7,7 @@ const RESULT = '/tmp/probe.json';const save = (o) => { try { writeFileSync(RESULT, JSON.stringify(o, null, 2)); } catch {} };const BASE = process.env.BASE || 'http://localhost:3000';-const MINT = process.env.MINT || '9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump'; // Fartcoin+const MINT = process.env.MINT || 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump'; // $THREE — override with MINT=<coin> for another communityconst errors = [];const browser = await chromium.launch({diff --git a/scripts/onchain-smoke.mjs b/scripts/onchain-smoke.mjsindex ad10bc5ce..2b973ad44 100644--- a/scripts/onchain-smoke.mjs+++ b/scripts/onchain-smoke.mjs@@ -39,6 +39,8 @@* 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_SOLANA_AGENT_ID agent_identities UUID to launch under (step 5; distinct from the numeric EVM agentId)+ * SMOKE_SOLANA_MINT reuse an existing devnet mint for the trade step without launching (step 6)* 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)*@@ -61,7 +63,6 @@ import {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';@@ -241,7 +242,9 @@ function inlineParityProblems() {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'}`);+ 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']) {@@ -268,47 +271,93 @@ function inlineParityProblems() {}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.+ // Prefer the dedicated task-05 guard when present — it owns address parity, the+ // drift trap, and the live-bytecode sweep, and is also wired into the Vercel+ // build. Delegating avoids two divergent parity implementations.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(' | ')}`,+ // Default to the offline address-parity check (deterministic, no egress) so+ // CI never blocks on RPC transport noise. The live bytecode sweep — which+ // hits up to 5 RPCs × 12s per address — is opt-in via --mainnet-readonly.+ const liveChains = cfg.mainnetReadonly+ ? process.env.VERIFY_ONCHAIN_CHAINS || '8453,84532'+ : 'none';+ const r = spawnSync(process.execPath, [parityScript], {+ encoding: 'utf8',+ timeout: 90_000,+ env: { ...process.env, VERIFY_ONCHAIN_CHAINS: liveChains },+ });+ if (r.error && (r.error.code === 'ETIMEDOUT' || r.signal)) {+ // Network sweep hung — fall back to the offline inline parity so the+ // drift assertion still runs deterministically.+ const problems = inlineParityProblems();+ if (problems.length) {+ return fail(`${problems.length} mismatch(es): ${problems.slice(0, 4).join('; ')}`);+ }+ return pass(+ 'address parity OK (inline; verify-onchain-parity.mjs live sweep timed out)',);}- source = 'verify-onchain-parity.mjs';- } else {- const problems = inlineParityProblems();- if (problems.length) {- return fail(`${problems.length} address mismatch(es): ${problems.slice(0, 4).join('; ')}`);+ if (r.status !== 0) {+ const tail = ((r.stdout || '') + (r.stderr || ''))+ .trim()+ .split('\n')+ .slice(-3)+ .join(' | ');+ return fail(`verify-onchain-parity.mjs exited ${r.status}: ${tail}`);}+ return pass(+ `address parity OK via verify-onchain-parity.mjs${cfg.mainnetReadonly ? ' (+ live bytecode sweep)' : ''}`,+ );}- // 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.+ // Fallback (task-05 script absent): inline parity across the three sources …+ const problems = inlineParityProblems();+ if (problems.length) {+ return fail(`${problems.length} address mismatch(es): ${problems.slice(0, 4).join('; ')}`);+ }+ // … plus a bounded live bytecode probe on Base mainnet + Base Sepolia. An empty+ // code result is a real FAIL; a network error/timeout degrades to a warning.const probes = [];for (const id of BYTECODE_PROBE_CHAINS) {- const dep = SDK_DEPLOYMENTS[id];- const addr = dep && dep.identityRegistry;+ const addr = SDK_DEPLOYMENTS[id]?.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') {+ 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}`);+ return pass(+ `address parity OK (inline)${probes.length ? ` · bytecode ${probes.join(' ')}` : ''}`,+ );+}++/**+ * Compose a three.ws 3D Agent Card (the ERC-8004 registration base from+ * buildRegistrationJSON, plus the v1 `model` superset the card schema requires).+ */+function buildCard({ name, description, glbUrl, agentId, chainId, registryAddr, glbSha, glbSize }) {+ const base = buildRegistrationJSON({+ name,+ description,+ glbUrl,+ imageUrl: '',+ agentId,+ chainId,+ registryAddr,+ services: [],+ x402Support: true,+ });+ return {+ ...base,+ type: [ERC8004_TYPE, THREEWS_CARD_TYPE],+ model: { uri: glbUrl, format: 'gltf-binary', sha256: glbSha, sizeBytes: glbSize },+ };}// ---------------------------------------------------------------------------@@ -329,7 +378,9 @@ async function stepEvmRegister(cfg, ctx) {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`);+ 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);@@ -355,28 +406,22 @@ async function stepEvmRegister(cfg, ctx) {const agentId = Number(registered.args.agentId);// 3. Build the 3D Agent Card (ERC-8004 base + the v1 `model` superset) and pin.- const base = buildRegistrationJSON({+ const card = buildCard({name: 'three.ws smoke agent',- description: 'Synthetic agent minted by scripts/onchain-smoke.mjs against testnet. Not a product launch.',+ 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,+ glbSha,+ glbSize: glb.length,});- 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);+ 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();@@ -439,7 +484,9 @@ async function stepEvmValidation(cfg, ctx) {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)');+ 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));@@ -547,9 +594,12 @@ async function stepEvmReputation(cfg, ctx) {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,- });+ return pass(+ `feedback from ${reviewer.address.slice(0, 10)}… · count ${countBefore} -> ${countAfter}`,+ {+ reputationTx: tx.hash,+ },+ );}// ---------------------------------------------------------------------------@@ -577,9 +627,11 @@ async function stepSolanaLaunch(cfg, ctx) {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 (!cfg.solanaAgentId) missing.push('SMOKE_SOLANA_AGENT_ID');if (missing.length) {- return skip(`devnet value step — set ${missing.join(', ')} (funded devnet wallet linked to the account)`);+ return skip(+ `devnet value step — set ${missing.join(', ')} (funded devnet wallet linked to the account)`,+ );}const sol = await loadSolana();@@ -591,7 +643,7 @@ async function stepSolanaLaunch(cfg, ctx) {const prep = await httpJson('POST', `${cfg.baseUrl}/api/pump/launch-prep`, {cookie: cfg.authCookie,body: {- agent_id: cfg.agentId,+ agent_id: cfg.solanaAgentId,wallet_address: wallet.publicKey.toBase58(),name: 'three.ws smoke',symbol: 'SMOKE',@@ -601,7 +653,10 @@ async function stepSolanaLaunch(cfg, ctx) {sol_buy_in: 0,},});- if (!prep.ok) return fail(`launch-prep ${prep.status}: ${prep.json?.message || prep.text?.slice(0, 160)}`);+ 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'));@@ -620,7 +675,10 @@ async function stepSolanaLaunch(cfg, ctx) {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)}`);+ 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`, {@@ -647,29 +705,44 @@ async function stepSolanaTrade(cfg, ctx) {const wallet = ctx.solana?.wallet || solanaKeypairFrom(sol, cfg.solanaKey);const conn = new Connection(cfg.solanaRpcDevnet, 'confirmed');+ const solAmount = 0.001;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,+ sol: solAmount,network: 'devnet',},});- if (!prep.ok) return fail(`buy-prep ${prep.status}: ${prep.json?.message || prep.text?.slice(0, 160)}`);+ 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');+ // buy-confirm verifies the tx on-chain; route comes back from buy-prep.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' },+ body: {+ mint,+ network: 'devnet',+ tx_signature: sig,+ wallet_address: wallet.publicKey.toBase58(),+ sol: solAmount,+ route: prep.json.route,+ },});- if (!confirm.ok) return fail(`buy-confirm ${confirm.status}: ${confirm.json?.message || confirm.text?.slice(0, 160)}`);+ 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 });+ return pass(`bought ${mint.slice(0, 8)}… on devnet · confirmed sig ${sig.slice(0, 10)}…`, {+ tradeSig: sig,+ });}// ---------------------------------------------------------------------------@@ -677,9 +750,12 @@ async function stepSolanaTrade(cfg, ctx) {// ---------------------------------------------------------------------------async function stepX402PayByName(cfg) {- if (!cfg.baseUrl) return skip('no SMOKE_BASE_URL — x402 pay-by-name runs against the deployed API');+ 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');+ return skip(+ 'no SMOKE_X402_NAME — set a resolvable @handle or .sol name to exercise the prep build',+ );}// 1. Resolve the name (read-only).@@ -688,7 +764,9 @@ async function stepX402PayByName(cfg) {`${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)}`);+ 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}"`);@@ -700,12 +778,16 @@ async function stepX402PayByName(cfg) {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)}`);+ 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)`);+ return pass(+ `resolved "${cfg.x402Name}" -> ${recipient.slice(0, 8)}… · prep tx built (not broadcast)`,+ );}// ---------------------------------------------------------------------------@@ -713,20 +795,27 @@ async function stepX402PayByName(cfg) {// ---------------------------------------------------------------------------async function stepSolanaInvoke(cfg) {- let sdk;+ // Read the program id from the light IDL module first — deciding SKIP without+ // pulling the heavy Anchor runtime keeps the common (undeployed) path fast.+ let programId;try {- sdk = await import('../agent-protocol-sdk/dist/index.js');+ ({ AGENT_INVOCATION_PROGRAM_ID: programId } =+ await import('../agent-protocol-sdk/dist/idl.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)');+ 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');+ return skip(+ `no funded devnet invoker — set SMOKE_SOLANA_PRIVATE_KEY (program ${programId.slice(0, 8)}…)`,+ );}+ const sdk = await import('../agent-protocol-sdk/dist/index.js');const sol = await loadSolana();const { Connection } = sol;const invoker = solanaKeypairFrom(sol, cfg.solanaKey);@@ -743,7 +832,10 @@ async function stepSolanaInvoke(cfg) {});// Assert the SkillInvoked event is in the confirmed tx's program logs.- const txInfo = await conn.getTransaction(sig, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 });+ const txInfo = await conn.getTransaction(sig, {+ commitment: 'confirmed',+ maxSupportedTransactionVersion: 0,+ });if (!txInfo || txInfo.meta?.err) {return fail(`invoke_skill tx ${sig} not confirmed cleanly`);}@@ -751,7 +843,10 @@ async function stepSolanaInvoke(cfg) {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 });+ return pass(+ `invoke_skill confirmed on devnet · SkillInvoked emitted · sig ${sig.slice(0, 10)}…`,+ { invokeSig: sig },+ );}// ---------------------------------------------------------------------------@@ -766,7 +861,12 @@ const STEPS = [{ 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 },+ {+ key: 'solana-invoke',+ num: 8,+ title: 'Solana agent_invocation (devnet)',+ run: stepSolanaInvoke,+ },];function parseArgs(argv) {@@ -776,7 +876,12 @@ function parseArgs(argv) {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);+ else if (a.startsWith('--only='))+ args.only = a+ .slice('--only='.length)+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);}return args;}@@ -788,6 +893,7 @@ function buildConfig(args) {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,+ solanaAgentId: process.env.SMOKE_SOLANA_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,@@ -822,13 +928,7 @@ function printTable(results) {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 || ''),- ),+ line(r.num, r.title, s.paint(`${s.icon} ${s.label}`), fmtMs(r.ms), dim(r.detail || '')),);}console.log(dim('─'.repeat(96)));@@ -883,13 +983,18 @@ async function main() {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)') : ''),+ (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 || {}) })) },+ {+ summary: counts,+ results: results.map(({ extra, ...r }) => ({ ...r, ...(extra || {}) })),+ },null,2,),@@ -899,9 +1004,25 @@ async function main() {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);- });+// Run only when invoked directly — importing the module (e.g. from the CI unit+// test) exposes the pure helpers without executing the harness.+const isMain = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);+if (isMain) {+ main()+ .then((code) => process.exit(code))+ .catch((err) => {+ console.error(red(`\nharness crashed: ${err.stack || err.message}`));+ process.exit(1);+ });+}++export {+ STEPS,+ inlineParityProblems,+ buildSyntheticGlb,+ sha256hex,+ buildCard,+ getCardValidator,+ ERC8004_TYPE,+ THREEWS_CARD_TYPE,+};diff --git a/scripts/pump-devnet-smoke.mjs b/scripts/pump-devnet-smoke.mjsnew file mode 100644index 000000000..e21c8d7eb--- /dev/null+++ b/scripts/pump-devnet-smoke.mjs@@ -0,0 +1,775 @@+#!/usr/bin/env node+// End-to-end devnet smoke for the pump.fun launchpad loop — Task 07.+// ----------------------------------------------------------------------------+// Proves the entire launch → buy → sell pipeline works against REAL on-chain+// state on Solana devnet, for BOTH a SOL-paired and a USDC-paired coin, plus a+// custodial (server-signed) buy/sell — the acceptance gate for Tasks 01–03:+//+// • Task 01 — every recorded `pump_agent_trades` row carries the correct+// quote_mint / quote_symbol / quote_amount (USDC legs in 1e6 atoms, SOL+// legs in lamports), asserted by re-reading the row from Postgres.+// • Task 02/03 — USDC buy_v2/sell_v2 and the custodial (held-key, server-+// signed) buy/sell paths transact correctly on a USDC-paired curve.+//+// This drives the SAME production helpers the dispatcher handlers use — not a+// reimplementation: getPumpSdk + the @pump-fun SDK v2 builders (createV2 /+// createV2AndBuyV2 / buyV2 / sellV2), pump-trade-args (slippage + token+// program + quote resolution), pump-quote (tradeQuoteColumns ++// walletQuoteDeltaAtomics), verifySignature, and the same `sql` client + the+// same recording logic as api/pump/[action].js's buy/sell-confirm. It signs+// locally with a funded devnet keypair, broadcasts, confirms, records, and+// asserts the row.+//+// DEVNET ONLY. Refuses any mainnet RPC. Never point it at a mainnet key.+//+// ── Funding the signer (required for a live run) ────────────────────────────+// SOL: the signer needs ~0.1 devnet SOL (create + buys + sells + ATA rent).+// The script auto-airdrops via the configured RPC, then Helius devnet,+// then the public faucet. If all return 429 ("airdrop limit / dry"),+// fund manually at https://faucet.solana.com (devnet) — the script+// prints the address — or point --rpc at a premium devnet endpoint+// (Helius/Triton/QuickNode) whose faucet isn't exhausted.+// USDC: the USDC legs need devnet USDC (mint 4zMMC9srt5Ri5X14GAgXhaHii3Gn+// PAEERYPJgZJDncDU — the only quote mint the devnet program whitelists).+// Its mint authority is an external faucet, so fund manually at+// https://faucet.circle.com (Solana devnet) — the script prints the+// address + amount. Without USDC the USDC legs SKIP (not fail).+//+// ── Flags / env ─────────────────────────────────────────────────────────────+// --rpc <url> | SOLANA_RPC_URL_DEVNET devnet RPC (default public)+// --keypair <path> | DEVNET_TEST_WALLET JSON byte-array or base58 key+// (default: the x402 demo solana+// wallet in ~/.config/...)+// --simulate-only build + simulate every leg on+// chain, never broadcast — needs+// no funds; proves the pipeline+// --sol-only run only the SOL legs+// --usdc <n> USDC per launch/buy (default 1)+// --sol <n> SOL per launch-buy/buy (0.01)+// --slippage-bps <n> default 500 (5%)+// --no-db skip Postgres record + assert+// --keep keep the seeded devnet DB rows+// --cleanup only delete prior smoke DB rows+//+// Examples:+// node scripts/pump-devnet-smoke.mjs --simulate-only+// node scripts/pump-devnet-smoke.mjs --keypair /tmp/devnet.json+// node scripts/pump-devnet-smoke.mjs --rpc https://devnet.helius-rpc.com/?api-key=…++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {+ Connection,+ Keypair,+ PublicKey,+ TransactionMessage,+ VersionedTransaction,+ SystemProgram,+ LAMPORTS_PER_SOL,+} from '@solana/web3.js';+import bs58 from 'bs58';+import BN from 'bn.js';+import * as spl from '@solana/spl-token';+import {+ getBuyTokenAmountFromSolAmount,+ getSellSolAmountFromTokenAmount,+} from '@pump-fun/pump-sdk';++import { getPumpSdk, getConnection, verifySignature } from '../api/_lib/pump.js';+import {+ slippagePercentFromBps,+ resolveTokenProgramForMintOwner,+ resolveCustodialQuote,+} from '../api/_lib/pump-trade-args.js';+import { tradeQuoteColumns, walletQuoteDeltaAtomics, usdcMintFor, WSOL_MINT } from '../api/_lib/pump-quote.js';++// ── tiny .env.local loader (so `sql` sees DATABASE_URL, like apply-migrations) ─+(function loadEnvLocal() {+ const p = path.join(process.cwd(), '.env.local');+ if (!fs.existsSync(p)) return;+ for (const line of fs.readFileSync(p, 'utf8').split('\n')) {+ const m = line.match(/^([A-Z0-9_]+)=(.*)$/i);+ if (!m) continue;+ const k = m[1];+ let v = m[2].trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1');+ if (process.env[k] == null || process.env[k] === '') process.env[k] = v;+ }+})();++// ── args ─────────────────────────────────────────────────────────────────────+function flag(name, fallbackEnv) {+ const i = process.argv.indexOf(`--${name}`);+ if (i !== -1 && process.argv[i + 1] && !process.argv[i + 1].startsWith('--'))+ return process.argv[i + 1];+ return fallbackEnv ? process.env[fallbackEnv] : undefined;+}+const has = (name) => process.argv.includes(`--${name}`);++const RPC = flag('rpc', 'SOLANA_RPC_URL_DEVNET') || 'https://api.devnet.solana.com';+const DEFAULT_WALLET = path.join(os.homedir(), '.config', 'x402-test-wallets', 'solana.json');+const KEYPAIR_PATH = flag('keypair', 'DEVNET_TEST_WALLET') || DEFAULT_WALLET;+const SIMULATE_ONLY = has('simulate-only');+const SOL_ONLY = has('sol-only');+const NO_DB = has('no-db');+const KEEP = has('keep');+const CLEANUP_ONLY = has('cleanup');+const USDC_PER = Number(flag('usdc') || '1'); // human USDC per launch/buy+const SOL_PER = Number(flag('sol') || '0.01'); // human SOL per launch-buy/buy+const SLIPPAGE_BPS = Number(flag('slippage-bps') || '500');++if (/mainnet|mainnet-beta/i.test(RPC)) {+ console.error('✗ Refusing to run against a mainnet RPC. Devnet only.');+ process.exit(1);+}+// getPumpSdk / getConnection resolve the devnet RPC from this env var.+process.env.SOLANA_RPC_URL_DEVNET = RPC;++const NETWORK = 'devnet';+const DEV_USDC = usdcMintFor('devnet'); // 4zMMC9…+const explorer = (sig) => `https://explorer.solana.com/tx/${sig}?cluster=devnet`;+const SOL_ATOMICS = (n) => new BN(Math.floor(n * LAMPORTS_PER_SOL));+const USDC_ATOMICS = (n) => new BN(Math.round(n * 1_000_000));++// ── result tracking ───────────────────────────────────────────────────────────+const results = []; // { leg, status: 'PASS'|'FAIL'|'SKIP', detail, sigs:[] }+function record(leg, status, detail, sigs = []) {+ results.push({ leg, status, detail, sigs });+ const icon = status === 'PASS' ? '✓' : status === 'SKIP' ? '∅' : '✗';+ console.log(`\n${icon} [${status}] ${leg}${detail ? ` — ${detail}` : ''}`);+ for (const s of sigs) console.log(` ${explorer(s)}`);+}++function loadKeypair(p) {+ const raw = fs.readFileSync(p, 'utf8').trim();+ try {+ const arr = JSON.parse(raw);+ return Keypair.fromSecretKey(Uint8Array.from(Array.isArray(arr) ? arr : Object.values(arr)));+ } catch {+ return Keypair.fromSecretKey(bs58.decode(raw));+ }+}++// ── on-chain send / simulate (the prep → sign → broadcast → confirm pipeline) ──+// Builds a VersionedTransaction (v0) exactly like the production handlers'+// buildUnsignedTxBase64, signs locally, broadcasts, and confirms.+async function submit(connection, instructions, signers, label) {+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');+ const msg = new TransactionMessage({+ payerKey: signers[0].publicKey,+ recentBlockhash: blockhash,+ instructions,+ }).compileToV0Message();+ const vtx = new VersionedTransaction(msg);+ vtx.sign(signers);++ if (SIMULATE_ONLY) {+ // Fund-independent build proof: the instruction was constructed by the+ // real SDK builder, compiled to a v0 message, and serializes within the+ // 1232-byte packet limit. Throws here only on a genuine malformed tx.+ const size = vtx.serialize().length;+ if (size > 1232) throw new Error(`${label}: serialized tx ${size} > 1232 bytes`);++ const sim = await connection.simulateTransaction(vtx, {+ sigVerify: false,+ replaceRecentBlockhash: true,+ });+ const err = sim.value.err;+ // A never-funded fee payer doesn't exist on-chain, so simulation halts with+ // AccountNotFound / insufficient-funds before executing — EXPECTED, and the+ // build above already proved the instruction is well-formed. Surface only+ // genuine program errors as failures.+ const logs = (sim.value.logs || []).join('\n');+ const fundingErr =+ err == null ||+ /AccountNotFound|could not find account|insufficient|0x1\b|debit an account|lamports|attempt to debit/i.test(+ JSON.stringify(err) + logs,+ );+ if (err && !fundingErr) {+ throw new Error(`${label} simulation failed: ${JSON.stringify(err)}\n${logs.slice(0, 800)}`);+ }+ console.log(+ ` [sim] ${label}: built OK (${size}B, v0)${err ? ' — sim halted on funding (expected)' : ' + simulated OK'}`,+ );+ return null; // no signature in simulate-only+ }++ const sig = await connection.sendRawTransaction(vtx.serialize(), {+ skipPreflight: false,+ maxRetries: 3,+ });+ await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');+ console.log(` ${label} tx: ${sig}`);+ console.log(` ${explorer(sig)}`);+ return sig;+}++// ── funding ────────────────────────────────────────────────────────────────────+async function ensureSol(connection, pubkey, minSol = 0.1) {+ let bal = await connection.getBalance(pubkey);+ if (bal >= minSol * LAMPORTS_PER_SOL) return bal;+ const helius = process.env.HELIUS_API_KEY;+ const endpoints = [RPC, helius ? `https://devnet.helius-rpc.com/?api-key=${helius}` : null, 'https://api.devnet.solana.com']+ .filter(Boolean)+ .filter((u, i, a) => a.indexOf(u) === i);+ for (const url of endpoints) {+ try {+ const conn = new Connection(url, 'confirmed');+ const sig = await conn.requestAirdrop(pubkey, Math.ceil(minSol * 2 * LAMPORTS_PER_SOL));+ await conn.confirmTransaction(sig, 'confirmed');+ break;+ } catch {+ /* try next endpoint */+ }+ }+ bal = await connection.getBalance(pubkey);+ return bal;+}++async function usdcBalanceAtomics(connection, owner) {+ try {+ const ata = spl.getAssociatedTokenAddressSync(new PublicKey(DEV_USDC), owner, true, spl.TOKEN_PROGRAM_ID);+ const b = await connection.getTokenAccountBalance(ata);+ return BigInt(b?.value?.amount ?? '0');+ } catch {+ return 0n;+ }+}++// ── DB: seed (idempotent) a synthetic devnet test user + agent ─────────────────+// Both columns on pump_agent_mints are NOT NULL FKs (agent_identities, users),+// so the recording path needs a real mint row. Everything is clearly synthetic,+// network='devnet', and cascade-cleaned at the end unless --keep.+const SMOKE_EMAIL = '[email protected]';+const SMOKE_AGENT = 'devnet-smoke';+let sql = null;+let dbCtx = null; // { userId, agentId }++async function dbConnect() {+ if (NO_DB) return false;+ if (!process.env.DATABASE_URL) {+ console.log(' (no DATABASE_URL — DB record + assert skipped; pass --no-db to silence)');+ return false;+ }+ ({ sql } = await import('../api/_lib/db.js'));+ return true;+}++async function dbSeed() {+ const [user] = await sql`+ insert into users (email, display_name, email_verified)+ values (${SMOKE_EMAIL}, 'Devnet Smoke', true)+ on conflict (email) do update set display_name = excluded.display_name+ returning id+ `;+ const [agent] = await sql`+ insert into agent_identities (user_id, name, description)+ values (${user.id}, ${SMOKE_AGENT}, 'pump.fun devnet smoke test agent')+ on conflict do nothing+ returning id+ `;+ let agentId = agent?.id;+ if (!agentId) {+ const [a] = await sql`+ select id from agent_identities where user_id = ${user.id} and name = ${SMOKE_AGENT} limit 1+ `;+ agentId = a?.id;+ }+ dbCtx = { userId: user.id, agentId };+}++async function dbCleanup() {+ if (!sql || !dbCtx || KEEP) return;+ // Cascade: deleting the agent removes its mints, which removes their trades.+ await sql`delete from agent_identities where id = ${dbCtx.agentId}`.catch(() => {});+ await sql`delete from users where id = ${dbCtx.userId} and email = ${SMOKE_EMAIL}`.catch(() => {});+}++// Register the launched coin so trade rows have a mint_id + quote source.+async function dbRegisterMint({ mint, name, symbol, quoteMint }) {+ if (!sql || !dbCtx) return null;+ const [row] = await sql`+ insert into pump_agent_mints+ (agent_id, user_id, network, mint, name, symbol, metadata_uri, agent_authority, buyback_bps, quote_mint)+ values+ (${dbCtx.agentId}, ${dbCtx.userId}, ${NETWORK}, ${mint}, ${name}, ${symbol},+ 'https://three.ws/devnet-smoke.json', ${null}, 0, ${quoteMint ?? null})+ on conflict (mint, network) do update set name = excluded.name+ returning id, quote_mint+ `;+ return row;+}++// Record a confirmed trade using the EXACT logic of buy/sell-confirm in+// api/pump/[action].js, then re-read it and assert the quote columns. Returns+// the asserted row.+async function dbRecordAndAssert({ mintRow, signature, wallet, direction, route, tokens, sol, usdcAmount }) {+ if (!sql || !dbCtx || !signature) return null;+ const tx = await verifySignature({ network: NETWORK, signature });+ const { quote_mint, quote_symbol } = tradeQuoteColumns({+ quoteMint: mintRow.quote_mint,+ network: NETWORK,+ });++ let lamports = null;+ let quoteAmount = null;+ if (direction === 'buy') {+ lamports = quote_symbol === 'SOL' && sol > 0 ? SOL_ATOMICS(sol).toString() : null;+ quoteAmount =+ quote_symbol === 'SOL'+ ? lamports+ : usdcAmount > 0+ ? USDC_ATOMICS(usdcAmount).toString()+ : walletQuoteDeltaAtomics({ tx, wallet, quoteSymbol: quote_symbol, quoteMint: quote_mint });+ } else {+ quoteAmount = walletQuoteDeltaAtomics({ tx, wallet, quoteSymbol: quote_symbol, quoteMint: quote_mint });+ lamports = quote_symbol === 'SOL' ? quoteAmount : null;+ }++ await sql`+ insert into pump_agent_trades+ (mint_id, user_id, wallet, direction, route, sol_amount, token_amount,+ quote_mint, quote_symbol, quote_amount, slippage_bps, tx_signature, network)+ values+ (${mintRow.id}, ${dbCtx.userId}, ${wallet}, ${direction}, ${route},+ ${lamports}, ${tokens ?? null}, ${quote_mint}, ${quote_symbol}, ${quoteAmount},+ ${SLIPPAGE_BPS}, ${signature}, ${NETWORK})+ on conflict (tx_signature, network) do nothing+ `;++ const [back] = await sql`+ select direction, quote_mint, quote_symbol, quote_amount+ from pump_agent_trades where tx_signature = ${signature} and network = ${NETWORK} limit 1+ `;+ if (!back) throw new Error('trade row not found after insert');++ // Assert: the right quote asset, in the right units, non-zero.+ const expectSymbol = mintRow.quote_mint ? 'USDC' : 'SOL';+ if (back.quote_symbol !== expectSymbol)+ throw new Error(`quote_symbol ${back.quote_symbol} !== ${expectSymbol}`);+ const expectMint = mintRow.quote_mint ? DEV_USDC : WSOL_MINT;+ if (back.quote_mint !== expectMint) throw new Error(`quote_mint ${back.quote_mint} !== ${expectMint}`);+ if (back.quote_amount == null || BigInt(back.quote_amount) <= 0n)+ throw new Error(`quote_amount must be > 0, got ${back.quote_amount}`);+ console.log(+ ` [db] ${direction} row: quote_symbol=${back.quote_symbol} quote_mint=${back.quote_mint.slice(0, 6)}… quote_amount=${back.quote_amount}`,+ );+ return back;+}++// ── leg builders (mirror api/pump/[action].js + api/agents/pumpfun/[action].js) ─++// Launch a fresh create_v2 coin (create-only — the buy leg supplies the first+// liquidity, which keeps every tx well under the 1232-byte packet limit and+// mirrors the launch-prep → buy-prep split the dispatcher exposes).+// quoteMint=null => SOL-paired; a USDC mint => USDC-paired.+async function launchCoin({ connection, sdk, payer, name, symbol, quoteMint }) {+ const mintKp = Keypair.generate();+ const mint = mintKp.publicKey;+ const ix = await sdk.createV2Instruction({+ mint,+ name,+ symbol,+ uri: 'https://three.ws/devnet-smoke.json',+ creator: payer.publicKey,+ user: payer.publicKey,+ ...(quoteMint ? { quoteMint: new PublicKey(quoteMint) } : {}),+ mayhemMode: false,+ });+ const instructions = Array.isArray(ix) ? ix : [ix];+ const sig = await submit(connection, instructions, [payer, mintKp], `launch ${symbol}`);+ return { mint: mint.toBase58(), sig };+}++// Buy on the bonding curve — SOL or USDC quote, mirroring handleBuy/handleBuyPrep.+async function buyCoin({ connection, sdk, buyer, mint, sol = 0, usdcAmount = 0 }) {+ const mintPk = new PublicKey(mint);+ const mintInfo = await connection.getAccountInfo(mintPk);+ if (!mintInfo) throw new Error(`mint ${mint} not found on devnet`);+ const tokenProgram = resolveTokenProgramForMintOwner(mintInfo.owner);++ const [global, feeConfig, state] = await Promise.all([+ sdk.fetchGlobal(),+ sdk.fetchFeeConfig().catch(() => null),+ sdk.fetchBuyState(mintPk, buyer.publicKey, tokenProgram),+ ]);+ if (!state?.bondingCurve || state.bondingCurve.complete)+ throw new Error('no active bonding curve (graduated or missing)');+ const quote = resolveCustodialQuote(state.bondingCurve?.quoteMint, NETWORK);++ const ixs = [];+ let amount;+ let quoteAmount;+ if (quote.isUsdc) {+ const quoteMintPk = new PublicKey(quote.quoteMint);+ const quoteInfo = await connection.getAccountInfo(quoteMintPk);+ const quoteTokenProgram = resolveTokenProgramForMintOwner(quoteInfo.owner);+ quoteAmount = USDC_ATOMICS(usdcAmount);+ amount = getBuyTokenAmountFromSolAmount({+ global,+ feeConfig,+ mintSupply: state.bondingCurve.tokenTotalSupply,+ bondingCurve: state.bondingCurve,+ amount: quoteAmount,+ quoteMint: quoteMintPk,+ });+ if (!amount.gt(new BN(0))) throw new Error('usdcAmount too small to buy any tokens');+ ixs.push(+ ...(await sdk.buyV2Instructions({+ global,+ bondingCurveAccountInfo: state.bondingCurveAccountInfo,+ bondingCurve: state.bondingCurve,+ associatedUserAccountInfo: state.associatedUserAccountInfo,+ mint: mintPk,+ user: buyer.publicKey,+ amount,+ quoteAmount,+ slippage: slippagePercentFromBps(SLIPPAGE_BPS),+ tokenProgram,+ quoteTokenProgram,+ })),+ );+ } else {+ quoteAmount = SOL_ATOMICS(sol);+ amount = getBuyTokenAmountFromSolAmount({+ global,+ feeConfig,+ mintSupply: state.bondingCurve.tokenTotalSupply,+ bondingCurve: state.bondingCurve,+ amount: quoteAmount,+ });+ if (!amount.gt(new BN(0))) throw new Error('sol amount too small to buy any tokens');+ ixs.push(+ ...(await sdk.buyV2Instructions({+ global,+ bondingCurveAccountInfo: state.bondingCurveAccountInfo,+ bondingCurve: state.bondingCurve,+ associatedUserAccountInfo: state.associatedUserAccountInfo,+ mint: mintPk,+ user: buyer.publicKey,+ amount,+ quoteAmount,+ slippage: slippagePercentFromBps(SLIPPAGE_BPS),+ tokenProgram,+ })),+ );+ }++ const sig = await submit(connection, ixs, [buyer], `buy ${quote.quoteSymbol}`);+ return { sig, tokenProgram, quoteSymbol: quote.quoteSymbol };+}++// Sell the full token balance back — SOL or USDC quote, mirroring handleSell.+async function sellCoin({ connection, sdk, seller, mint, tokenProgram }) {+ const mintPk = new PublicKey(mint);+ const userAta = spl.getAssociatedTokenAddressSync(mintPk, seller.publicKey, true, tokenProgram);+ const bal = await connection.getTokenAccountBalance(userAta);+ const tokens = new BN(bal.value.amount);+ if (!tokens.gt(new BN(0))) throw new Error('zero token balance to sell');++ const [global, feeConfig, state] = await Promise.all([+ sdk.fetchGlobal(),+ sdk.fetchFeeConfig().catch(() => null),+ sdk.fetchSellState(mintPk, seller.publicKey, tokenProgram),+ ]);+ const quote = resolveCustodialQuote(state.bondingCurve?.quoteMint, NETWORK);+ const expectedQuoteOut = getSellSolAmountFromTokenAmount({+ global,+ feeConfig,+ mintSupply: state.bondingCurve.tokenTotalSupply,+ bondingCurve: state.bondingCurve,+ amount: tokens,+ });++ const ixs = [];+ let quoteTokenProgram;+ if (quote.isUsdc) {+ const quoteMintPk = new PublicKey(quote.quoteMint);+ const quoteInfo = await connection.getAccountInfo(quoteMintPk);+ quoteTokenProgram = resolveTokenProgramForMintOwner(quoteInfo.owner);+ const userQuoteAta = spl.getAssociatedTokenAddressSync(quoteMintPk, seller.publicKey, true, quoteTokenProgram);+ ixs.push(+ spl.createAssociatedTokenAccountIdempotentInstruction(+ seller.publicKey,+ userQuoteAta,+ seller.publicKey,+ quoteMintPk,+ quoteTokenProgram,+ ),+ );+ }+ ixs.push(+ ...(await sdk.sellV2Instructions({+ global,+ bondingCurveAccountInfo: state.bondingCurveAccountInfo,+ bondingCurve: state.bondingCurve,+ mint: mintPk,+ user: seller.publicKey,+ amount: tokens,+ quoteAmount: expectedQuoteOut,+ slippage: slippagePercentFromBps(SLIPPAGE_BPS),+ tokenProgram,+ ...(quote.isUsdc ? { quoteTokenProgram } : {}),+ })),+ );++ const sig = await submit(connection, ixs, [seller], `sell ${quote.quoteSymbol}`);+ return { sig, tokens: tokens.toString(), quoteSymbol: quote.quoteSymbol };+}++// ── full launch → buy → sell leg (SOL or USDC), with DB record + assert ────────+async function runTradeLeg({ connection, sdk, signer, label, quoteMint, name, symbol }) {+ const isUsdc = !!quoteMint;+ const launch = await launchCoin({ connection, sdk, payer: signer, name, symbol, quoteMint });+ if (SIMULATE_ONLY) {+ record(label, 'PASS', `launch ix built + simulated (buy/sell need a live curve — funded run)`);+ return;+ }++ const mintRow = await dbRegisterMint({ mint: launch.mint, name, symbol, quoteMint });++ const buy = await buyCoin({+ connection,+ sdk,+ buyer: signer,+ mint: launch.mint,+ sol: isUsdc ? 0 : SOL_PER,+ usdcAmount: isUsdc ? USDC_PER : 0,+ });+ if (mintRow)+ await dbRecordAndAssert({+ mintRow,+ signature: buy.sig,+ wallet: signer.publicKey.toBase58(),+ direction: 'buy',+ route: 'bonding_curve',+ sol: isUsdc ? 0 : SOL_PER,+ usdcAmount: isUsdc ? USDC_PER : 0,+ });++ const sell = await sellCoin({+ connection,+ sdk,+ seller: signer,+ mint: launch.mint,+ tokenProgram: buy.tokenProgram,+ });+ if (mintRow)+ await dbRecordAndAssert({+ mintRow,+ signature: sell.sig,+ wallet: signer.publicKey.toBase58(),+ direction: 'sell',+ route: 'bonding_curve',+ tokens: sell.tokens,+ });++ record(label, 'PASS', `mint ${launch.mint}`, [launch.sig, buy.sig, sell.sig].filter(Boolean));+}++// ── custodial leg: a separately-held "agent" keypair signs server-side ─────────+async function runCustodialLeg({ connection, sdk, funder, quoteMint }) {+ const label = `Custodial buy+sell (${quoteMint ? 'USDC' : 'SOL'})`;+ const agent = Keypair.generate(); // stands in for loadAgentForSigning's recovered key+ // The custodial wallet needs its own SOL for fees/rent, and (USDC leg) USDC.+ if (!SIMULATE_ONLY) {+ const transfer = SystemProgram.transfer({+ fromPubkey: funder.publicKey,+ toPubkey: agent.publicKey,+ lamports: Math.floor(0.04 * LAMPORTS_PER_SOL),+ });+ await submit(connection, [transfer], [funder], 'fund custodial wallet');+ }++ // Launch a coin the custodial wallet will own + trade.+ const name = quoteMint ? 'three.ws custodial USDC smoke' : 'three.ws custodial SOL smoke';+ const symbol = quoteMint ? 'T3CUSDC' : 'T3CSOL';+ const launch = await launchCoin({ connection, sdk, payer: agent, name, symbol, quoteMint });+ if (SIMULATE_ONLY) {+ record(label, 'PASS', 'custodial launch ix built + simulated');+ return;+ }++ const mintRow = await dbRegisterMint({ mint: launch.mint, name, symbol, quoteMint });+ const buy = await buyCoin({+ connection,+ sdk,+ buyer: agent,+ mint: launch.mint,+ sol: quoteMint ? 0 : SOL_PER,+ usdcAmount: quoteMint ? USDC_PER : 0,+ });+ if (mintRow)+ await dbRecordAndAssert({+ mintRow,+ signature: buy.sig,+ wallet: agent.publicKey.toBase58(),+ direction: 'buy',+ route: 'bonding_curve',+ sol: quoteMint ? 0 : SOL_PER,+ usdcAmount: quoteMint ? USDC_PER : 0,+ });+ const sell = await sellCoin({ connection, sdk, seller: agent, mint: launch.mint, tokenProgram: buy.tokenProgram });+ if (mintRow)+ await dbRecordAndAssert({+ mintRow,+ signature: sell.sig,+ wallet: agent.publicKey.toBase58(),+ direction: 'sell',+ route: 'bonding_curve',+ tokens: sell.tokens,+ });+ record(label, 'PASS', `custodial wallet ${agent.publicKey.toBase58()} · mint ${launch.mint}`, [+ launch.sig,+ buy.sig,+ sell.sig,+ ].filter(Boolean));+}++// ── main ────────────────────────────────────────────────────────────────────+async function main() {+ console.log('pump.fun devnet smoke — launch → buy → sell (Task 07)');+ console.log(` rpc: ${RPC}`);+ console.log(` mode: ${SIMULATE_ONLY ? 'SIMULATE-ONLY (no broadcast, no funds needed)' : 'LIVE'}`);+ console.log(` network: ${NETWORK}`);++ const connection = getConnection({ network: NETWORK });+ const { sdk } = await getPumpSdk({ network: NETWORK });+ const signer = loadKeypair(KEYPAIR_PATH);+ console.log(` signer: ${signer.publicKey.toBase58()}`);++ const dbOn = await dbConnect();+ if (dbOn && CLEANUP_ONLY) {+ await dbSeed();+ await sql`delete from pump_agent_mints where agent_id = ${dbCtx.agentId} and network = ${NETWORK}`.catch(() => {});+ await dbCleanup();+ console.log('\n✓ cleaned prior devnet smoke rows. Done.');+ return;+ }+ if (dbOn && !SIMULATE_ONLY) await dbSeed();++ // Verify the devnet program whitelists devnet USDC (gates the USDC legs).+ let usdcWhitelisted = false;+ try {+ const g = await sdk.fetchGlobal();+ usdcWhitelisted = (g.whitelistedQuoteMints || []).map((k) => k.toBase58()).includes(DEV_USDC);+ } catch {+ /* leave false */+ }+ console.log(` usdc gate: ${usdcWhitelisted ? 'OPEN' : 'CLOSED'} (devnet USDC ${DEV_USDC})`);++ // Fund SOL (live only).+ if (!SIMULATE_ONLY) {+ const bal = await ensureSol(connection, signer.publicKey, 0.12);+ console.log(` sol bal: ${(bal / LAMPORTS_PER_SOL).toFixed(4)} SOL`);+ if (bal < 0.05 * LAMPORTS_PER_SOL) {+ record(+ 'Funding',+ 'FAIL',+ `signer has ${(bal / LAMPORTS_PER_SOL).toFixed(4)} SOL; need ~0.12. Airdrop is rate-limited (429). ` ++ `Fund ${signer.publicKey.toBase58()} at https://faucet.solana.com (devnet) or pass --rpc <premium devnet endpoint>, then re-run. ` ++ `Or run with --simulate-only to validate the build pipeline without funds.`,+ );+ await summarize();+ return;+ }+ }++ // ── SOL leg ──+ try {+ await runTradeLeg({+ connection,+ sdk,+ signer,+ label: 'SOL launch + buy + sell',+ quoteMint: null,+ name: 'three.ws devnet SOL smoke',+ symbol: 'T3SOL',+ });+ } catch (e) {+ record('SOL launch + buy + sell', 'FAIL', stepError(e));+ }++ // ── USDC leg ──+ if (SOL_ONLY) {+ record('USDC launch + buy + sell', 'SKIP', '--sol-only');+ } else if (!usdcWhitelisted) {+ record('USDC launch + buy + sell', 'SKIP', 'devnet program does not whitelist devnet USDC');+ } else {+ let usdcOk = SIMULATE_ONLY;+ if (!SIMULATE_ONLY) {+ const have = await usdcBalanceAtomics(connection, signer.publicKey);+ const need = USDC_ATOMICS(USDC_PER * 2);+ usdcOk = have >= BigInt(need.toString());+ if (!usdcOk) {+ record(+ 'USDC launch + buy + sell',+ 'SKIP',+ `signer holds ${Number(have) / 1e6} devnet USDC, needs ~${USDC_PER * 2}. ` ++ `Fund ${signer.publicKey.toBase58()} with devnet USDC (mint ${DEV_USDC}) at https://faucet.circle.com, then re-run.`,+ );+ }+ }+ if (usdcOk) {+ try {+ await runTradeLeg({+ connection,+ sdk,+ signer,+ label: 'USDC launch + buy + sell',+ quoteMint: DEV_USDC,+ name: 'three.ws devnet USDC smoke',+ symbol: 'T3USDC',+ });+ } catch (e) {+ record('USDC launch + buy + sell', 'FAIL', stepError(e));+ }+ }+ }++ // ── Custodial leg (SOL always; USDC when whitelisted) ──+ try {+ await runCustodialLeg({ connection, sdk, funder: signer, quoteMint: null });+ } catch (e) {+ record('Custodial buy+sell (SOL)', 'FAIL', stepError(e));+ }+ if (!SOL_ONLY && usdcWhitelisted) {+ try {+ await runCustodialLeg({ connection, sdk, funder: signer, quoteMint: DEV_USDC });+ } catch (e) {+ record('Custodial buy+sell (USDC)', 'FAIL', stepError(e));+ }+ }++ await summarize();+}++function stepError(e) {+ return (e?.message || String(e)).split('\n')[0].slice(0, 240);+}++async function summarize() {+ try {+ await dbCleanup();+ } catch {+ /* best-effort */+ }+ const pass = results.filter((r) => r.status === 'PASS').length;+ const fail = results.filter((r) => r.status === 'FAIL').length;+ const skip = results.filter((r) => r.status === 'SKIP').length;+ console.log('\n──────────────────────────────────────────────────────────────');+ console.log(`SUMMARY — ${pass} PASS · ${fail} FAIL · ${skip} SKIP`);+ for (const r of results) {+ const icon = r.status === 'PASS' ? '✓' : r.status === 'SKIP' ? '∅' : '✗';+ console.log(` ${icon} ${r.leg}${r.detail ? ` — ${r.detail}` : ''}`);+ }+ console.log('──────────────────────────────────────────────────────────────');+ if (SIMULATE_ONLY)+ console.log('Mode was SIMULATE-ONLY: instruction-build paths validated on-chain; ' + 'no broadcast. Re-run without --simulate-only (funded signer) for live tx + DB assertions.');+ process.exit(fail > 0 ? 1 : 0);+}++main().catch((e) => {+ console.error('\n✗ fatal:', e?.stack || e?.message || e);+ process.exit(1);+});diff --git a/scripts/pump-v2-smoke.mjs b/scripts/pump-v2-smoke.mjsindex 0cb258972..9bcbfd439 100644--- a/scripts/pump-v2-smoke.mjs+++ b/scripts/pump-v2-smoke.mjs@@ -32,10 +32,10 @@ const RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';const USDC_MAINNET = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');const WSOL = new PublicKey('So11111111111111111111111111111111111111112');-// A live mainnet pump.fun coin to exercise real bonding-curve reads against.-// Override with PUMP_SMOKE_MINT when this one graduates / 404s.+// A live mainnet pump.fun coin to exercise real bonding-curve / AMM reads against.+// Defaults to $THREE; override with PUMP_SMOKE_MINT to target another coin.const TARGET_MINT_STR = process.env.PUMP_SMOKE_MINT- || 'BD1Soa3PKTkcJkGtn14d7jLy4dUiztwo6tP2KkqJpump';+ || 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';console.log(`RPC: ${RPC}`);console.log(`Mint: ${TARGET_MINT_STR}`);diff --git a/scripts/register-three-ws-agent-solana.mjs b/scripts/register-three-ws-agent-solana.mjsnew file mode 100644index 000000000..8b65aaa1b--- /dev/null+++ b/scripts/register-three-ws-agent-solana.mjs@@ -0,0 +1,593 @@+#!/usr/bin/env node+/**+ * Register three.ws ITSELF as an on-chain agent on Solana.+ * ------------------------------------------------------------------------------+ * three.ws tells users to register their agents on-chain; this registers the+ * platform's own identity, eating our own dog food. The agent is minted as a+ * Metaplex Core asset inside the "three.ws Agents" collection — exactly the flow+ * api/_lib/onchain-deploy.js runs for user agents — and (best-effort) enrolled in+ * the Metaplex Agent Registry. The result is written back into the public+ * discovery documents so any agent/indexer that reads three.ws can verify it.+ *+ * This is self-contained (no DB, no api/_lib/env.js coupling) so it runs from a+ * CLI with only a funded authority key — mirroring scripts/batch-mint-agents.mjs.+ *+ * Source of truth for the agent's identity is the committed card:+ * public/.well-known/3d-agent-card.json (name, description, model, services)+ * The model bytes are verified against model.sha256 before anything is minted+ * (three.ws Card v1 conformance point 3) — a mismatch aborts the run.+ *+ * Usage:+ * # devnet dry-run of the whole flow (no tx sent)+ * node scripts/register-three-ws-agent-solana.mjs --network devnet --dry-run+ *+ * # real devnet registration (authority must hold a little devnet SOL)+ * SOLANA_AGENT_COLLECTION_AUTHORITY_KEY=<bs58> \+ * node scripts/register-three-ws-agent-solana.mjs --network devnet+ *+ * # real mainnet registration (authority must hold ~0.02 SOL; irreversible)+ * SOLANA_AGENT_COLLECTION_AUTHORITY_KEY=<bs58> SOLANA_RPC_URL=<rpc> \+ * CONFIRM_MAINNET=yes \+ * node scripts/register-three-ws-agent-solana.mjs --network mainnet+ *+ * Authority resolution (first that parses):+ * SOLANA_AGENT_COLLECTION_AUTHORITY_KEY → LAUNCH_FUNDER_SECRET → .keys/authority-3WS.json+ * Collection resolution:+ * SOLANA_AGENT_COLLECTION_<NET> env → ledger → deploy with .keys/collection-3ws.json+ *+ * Re-running is safe: once the asset for a network is in the ledger and exists+ * on-chain, the mint is skipped and only the discovery docs are reconciled.+ */++import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';+import { createHash } from 'node:crypto';+import { dirname, resolve, basename } from 'node:path';+import { fileURLToPath } from 'node:url';+import process from 'node:process';++import { Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js';+import bs58 from 'bs58';+import { CID } from 'multiformats/cid';+import * as rawCodec from 'multiformats/codecs/raw';+import { sha256 as mfSha256 } from 'multiformats/hashes/sha2';+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';+import {+ mplCore,+ create,+ createCollection,+ fetchCollection,+ ruleSet,+} from '@metaplex-foundation/mpl-core';+import {+ generateSigner,+ publicKey as umiPublicKey,+ createSignerFromKeypair,+ signerIdentity,+} from '@metaplex-foundation/umi';++const __dirname = dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = resolve(__dirname, '..');++// ── Canonical brand (mirrors api/_lib/three-brand.js — the single source) ──────+const THREE_WS = {+ name: 'three.ws',+ tagline: 'Give your AI a body.',+ website: 'https://three.ws',+ x: 'https://x.com/trythreews',+ github: 'https://github.com/nirholas/three.ws',+ ogImage: 'https://three.ws/og-image.png',+};+// $THREE — the only coin this platform references.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++// CAIP-2 genesis-hash chain refs.+const SOLANA_REFS = {+ mainnet: '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ devnet: 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1',+};++const CARD_PATH = resolve(REPO_ROOT, 'public/.well-known/3d-agent-card.json');+const REG_PATH = resolve(REPO_ROOT, 'public/.well-known/agent-registration.json');+const LEDGER_PATH = resolve(REPO_ROOT, 'data/three-ws-agent-onchain.json');+const MANIFEST_PUBLIC_PATH = resolve(REPO_ROOT, 'public/.well-known/three-ws-agent.metaplex.json');+const MANIFEST_PUBLIC_URL = `${THREE_WS.website}/.well-known/three-ws-agent.metaplex.json`;++// Cost estimates (rent + fee): collection deploy ~0.005, mint ~0.004, registry+// ~0.003. Add buffer; refuse to attempt with less so we never half-finish.+const NEED_LAMPORTS = Math.floor(0.02 * LAMPORTS_PER_SOL);++// ── args / env ────────────────────────────────────────────────────────────────++function arg(name, fallback) {+ const i = process.argv.indexOf(name);+ return i >= 0 && process.argv[i + 1] && !process.argv[i + 1].startsWith('--')+ ? process.argv[i + 1]+ : fallback;+}+function flag(name) {+ return process.argv.includes(name);+}++function loadDotEnv() {+ // Best-effort, like the other scripts: pick up .env / .vercel preview without+ // making dotenv a hard dep. Never overrides an already-set process env var.+ for (const p of [resolve(REPO_ROOT, '.env'), resolve(REPO_ROOT, '.env.local')]) {+ if (!existsSync(p)) continue;+ for (const raw of readFileSync(p, 'utf8').split('\n')) {+ const line = raw.trim();+ if (!line || line.startsWith('#')) continue;+ const eq = line.indexOf('=');+ if (eq < 0) continue;+ const k = line.slice(0, eq).trim();+ let v = line.slice(eq + 1).trim();+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {+ v = v.slice(1, -1);+ }+ if (process.env[k] === undefined && v) process.env[k] = v;+ }+ }+}++// Parse a secret in any of the formats we store keys in (bs58, base64, json array).+function parseKeypair(value) {+ if (!value) return null;+ const v = value.trim();+ try {+ if (v.startsWith('[')) return Keypair.fromSecretKey(new Uint8Array(JSON.parse(v)));+ } catch {+ /* not json */+ }+ try {+ const b = bs58.decode(v);+ if (b.length === 64) return Keypair.fromSecretKey(b);+ if (b.length === 32) return Keypair.fromSeed(b);+ } catch {+ /* not bs58 */+ }+ try {+ const b = Buffer.from(v, 'base64');+ if (b.length === 64) return Keypair.fromSecretKey(new Uint8Array(b));+ } catch {+ /* not base64 */+ }+ return null;+}++function loadKeypairFile(rel) {+ const p = resolve(REPO_ROOT, rel);+ if (!existsSync(p)) return null;+ try {+ return Keypair.fromSecretKey(new Uint8Array(JSON.parse(readFileSync(p, 'utf8'))));+ } catch {+ return null;+ }+}++function resolveAuthority() {+ for (const env of ['SOLANA_AGENT_COLLECTION_AUTHORITY_KEY', 'LAUNCH_FUNDER_SECRET']) {+ const kp = parseKeypair(process.env[env]);+ if (kp) return { kp, source: env };+ }+ const file = loadKeypairFile('.keys/authority-3WS.json');+ if (file) return { kp: file, source: '.keys/authority-3WS.json' };+ return { kp: null, source: null };+}++function rpcEndpoint(network) {+ const key = process.env.HELIUS_API_KEY;+ const alch = process.env.ALCHEMY_API_KEY;+ if (network === 'devnet') {+ return (+ process.env.SOLANA_RPC_URL_DEVNET ||+ (key && `https://devnet.helius-rpc.com/?api-key=${key}`) ||+ (alch && `https://solana-devnet.g.alchemy.com/v2/${alch}`) ||+ 'https://api.devnet.solana.com'+ );+ }+ return (+ process.env.SOLANA_RPC_URL ||+ process.env.SOLANA_MAINNET_RPC ||+ (key && `https://mainnet.helius-rpc.com/?api-key=${key}`) ||+ (alch && `https://solana-mainnet.g.alchemy.com/v2/${alch}`) ||+ 'https://api.mainnet-beta.solana.com'+ );+}++// ── ledger / discovery-doc IO ───────────────────────────────────────────────────++function readJson(path, fallback) {+ if (!existsSync(path)) return fallback;+ try {+ return JSON.parse(readFileSync(path, 'utf8'));+ } catch {+ return fallback;+ }+}++function writeJsonTabs(path, obj) {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, JSON.stringify(obj, null, '\t') + '\n');+}++function loadLedger() {+ return readJson(LEDGER_PATH, { agent: 'three.ws', networks: {} });+}++// ── IPFS pinning (mirrors api/_lib/ipfs-pin.js) ─────────────────────────────────++async function pinToIPFS(buf, filename) {+ if (process.env.PINATA_JWT) {+ const form = new FormData();+ form.append('file', new Blob([buf]), filename);+ const resp = await fetch('https://api.pinata.cloud/pinning/pinFileToIPFS', {+ method: 'POST',+ headers: { Authorization: `Bearer ${process.env.PINATA_JWT}` },+ body: form,+ });+ if (!resp.ok) throw new Error(`Pinata error ${resp.status}: ${await resp.text().catch(() => '')}`);+ const data = await resp.json();+ return { cid: data.IpfsHash, uri: `https://ipfs.io/ipfs/${data.IpfsHash}`, provider: 'pinata' };+ }+ if (process.env.WEB3_STORAGE_TOKEN) {+ const resp = await fetch('https://api.web3.storage/upload', {+ method: 'POST',+ headers: { Authorization: `Bearer ${process.env.WEB3_STORAGE_TOKEN}`, 'X-NAME': filename },+ body: buf,+ });+ if (!resp.ok) throw new Error(`web3.storage error ${resp.status}`);+ const data = await resp.json();+ return { cid: data.cid, uri: `https://ipfs.io/ipfs/${data.cid}`, provider: 'web3.storage' };+ }+ return null;+}++async function cidv1(buf) {+ const digest = await mfSha256.digest(new Uint8Array(buf));+ return CID.create(1, rawCodec.code, digest).toString();+}++// ── manifest (Metaplex superset + 3D Card v1, mirrors three-brand.js) ───────────++function buildManifest(card, { glbUrl, ownerAddress }) {+ const image = card.image || THREE_WS.ogImage;+ return {+ // 3D Agent Card v1 conformance (type array w/ both URIs, model, trust)+ type: card.type,+ // Metaplex token-metadata standard+ name: card.name,+ symbol: 'AGENT',+ description: card.description,+ image,+ animation_url: glbUrl,+ external_url: THREE_WS.website,+ active: true,+ model: card.model,+ body: { uri: glbUrl, format: card.model?.format || 'gltf-binary' },+ services: card.services,+ x402Support: card.x402Support !== false,+ x402Endpoints: card.x402Endpoints || [],+ supportedTrust: card.supportedTrust || ['reputation', 'validation'],+ attributes: [+ { trait_type: 'Platform', value: THREE_WS.name },+ { trait_type: 'Standard', value: 'Metaplex Core' },+ { trait_type: 'Schema', value: 'agent-manifest/0.1' },+ { trait_type: '$THREE', value: THREE_MINT },+ ],+ properties: {+ category: 'vr',+ files: [+ { uri: image, type: 'image/png' },+ { uri: glbUrl, type: 'model/gltf-binary' },+ ],+ creators: ownerAddress ? [{ address: ownerAddress, share: 100 }] : [],+ },+ platform: {+ name: THREE_WS.name,+ url: THREE_WS.website,+ tagline: THREE_WS.tagline,+ x: THREE_WS.x,+ github: THREE_WS.github,+ },+ token: { symbol: 'THREE', mint: THREE_MINT, url: `https://pump.fun/coin/${THREE_MINT}` },+ $schema: 'https://3d-agent.io/schemas/manifest/0.1.json',+ spec: 'agent-manifest/0.1',+ tags: ['three.ws', 'ai-agent', 'platform'],+ };+}++function onchainAttributes() {+ return [+ { key: 'platform', value: THREE_WS.name },+ { key: 'url', value: THREE_WS.website },+ { key: 'agent', value: THREE_WS.name },+ { key: 'x', value: THREE_WS.x },+ { key: 'github', value: THREE_WS.github },+ { key: '$THREE', value: THREE_MINT },+ { key: 'standard', value: 'metaplex-core' },+ { key: 'schema', value: 'agent-manifest/0.1' },+ ];+}++// ── discovery-doc reconciliation ────────────────────────────────────────────────++function applyOnchainToDoc(path, onchain, registration) {+ const doc = readJson(path, null);+ if (!doc) return false;+ doc.onchain = onchain;+ const regs = Array.isArray(doc.registrations) ? doc.registrations : [];+ const exists = regs.some(+ (r) => r.agentId === registration.agentId && r.agentRegistry === registration.agentRegistry,+ );+ if (!exists) regs.push(registration);+ doc.registrations = regs;+ writeJsonTabs(path, doc);+ return true;+}++// ── main ────────────────────────────────────────────────────────────────────────++async function main() {+ loadDotEnv();+ const network = arg('--network', 'devnet') === 'mainnet' ? 'mainnet' : 'devnet';+ const dryRun = flag('--dry-run');+ const ownerOverride = arg('--owner', null);++ if (network === 'mainnet' && !dryRun && process.env.CONFIRM_MAINNET !== 'yes') {+ console.error('Refusing mainnet registration without CONFIRM_MAINNET=yes (irreversible, costs real SOL).');+ process.exit(1);+ }++ // 1. Load + verify the canonical card.+ const card = readJson(CARD_PATH, null);+ if (!card || !card.model?.uri || !card.model?.sha256) {+ console.error(`Canonical card missing or malformed: ${CARD_PATH}`);+ process.exit(1);+ }+ const glbName = basename(card.model.uri);+ const glbLocal = resolve(REPO_ROOT, 'public/avatars', glbName);+ if (!existsSync(glbLocal)) {+ console.error(`Model file not found locally: ${glbLocal} (model.uri=${card.model.uri})`);+ process.exit(1);+ }+ const glbBytes = readFileSync(glbLocal);+ const actualSha = createHash('sha256').update(glbBytes).digest('hex');+ if (actualSha !== card.model.sha256) {+ console.error('Card model.sha256 does NOT match the model bytes — card is unverified per spec point 3.');+ console.error(` expected ${card.model.sha256}`);+ console.error(` actual ${actualSha}`);+ process.exit(1);+ }+ console.log(`✓ model verified: ${glbName} sha256=${actualSha} (${glbBytes.length} bytes)`);++ // 2. Authority (fee payer + collection update authority).+ const { kp: authorityKp, source: authSource } = resolveAuthority();+ if (!authorityKp) {+ console.error('No authority keypair: set SOLANA_AGENT_COLLECTION_AUTHORITY_KEY or provide .keys/authority-3WS.json');+ process.exit(1);+ }+ const authorityAddr = authorityKp.publicKey.toBase58();++ // Collection signer (for first-run deploy) — vanity preferred.+ const envCollection =+ network === 'mainnet'+ ? process.env.SOLANA_AGENT_COLLECTION_MAINNET+ : process.env.SOLANA_AGENT_COLLECTION_DEVNET;+ const ledger = loadLedger();+ let collectionAddr = (envCollection && envCollection.trim()) || ledger.networks?.[network]?.collection || null;+ const collectionKp = loadKeypairFile('.keys/collection-3ws.json');++ // Owner of the platform agent asset: explicit → www vanity → authority custody.+ const wwwKp = loadKeypairFile('scripts/www-vanity.json');+ const ownerAddr = ownerOverride || wwwKp?.publicKey.toBase58() || authorityAddr;++ const rpc = rpcEndpoint(network);+ console.log(`network: ${network}`);+ console.log(`rpc: ${rpc.replace(/api-key=[^&]+/i, 'api-key=***')}`);+ console.log(`authority: ${authorityAddr} (from ${authSource})`);+ console.log(`owner: ${ownerAddr}${ownerAddr === authorityAddr ? ' (custody)' : ''}`);+ console.log(`collection: ${collectionAddr || (collectionKp ? collectionKp.publicKey.toBase58() + ' (to deploy)' : 'fresh keypair (to deploy)')}`);+ console.log(`mode: ${dryRun ? 'DRY RUN' : 'LIVE'}`);++ // 3. Idempotency — already registered on this network?+ const existing = ledger.networks?.[network];+ if (existing?.asset && !dryRun) {+ console.log(`\nAlready registered on ${network}: asset ${existing.asset}. Reconciling discovery docs only.`);+ reconcile(network, existing);+ console.log('Done (no new mint).');+ return;+ }++ // 4. Umi + authority signer.+ const umi = createUmi(rpc).use(mplCore());+ const authoritySigner = createSignerFromKeypair(+ umi,+ umi.eddsa.createKeypairFromSecretKey(authorityKp.secretKey),+ );+ umi.use(signerIdentity(authoritySigner));++ // 5. Build + pin the manifest. GLB stays first-party (verifiable via sha256);+ // optionally also pinned to IPFS for immutability.+ let glbUrl = card.model.uri;+ if (!dryRun) {+ const pinnedGlb = await pinToIPFS(glbBytes, glbName).catch((e) => {+ console.log(` GLB pin skipped (${e.message}); using first-party URL`);+ return null;+ });+ if (pinnedGlb) {+ glbUrl = pinnedGlb.uri;+ console.log(`✓ GLB pinned: ${pinnedGlb.uri} (cid ${pinnedGlb.cid})`);+ // Verify pinned bytes hash to the same sha256 (spec point 3 over IPFS).+ const back = Buffer.from(await (await fetch(pinnedGlb.uri)).arrayBuffer());+ const backSha = createHash('sha256').update(back).digest('hex');+ if (backSha !== card.model.sha256) throw new Error(`pinned GLB sha256 mismatch: ${backSha}`);+ console.log('✓ pinned GLB bytes verified against model.sha256');+ }+ }++ const manifest = buildManifest(card, { glbUrl, ownerAddress: ownerAddr });+ const manifestBytes = Buffer.from(JSON.stringify(manifest), 'utf-8');+ let metadataUri;+ if (dryRun) {+ metadataUri = MANIFEST_PUBLIC_URL;+ console.log(`[dry-run] would pin manifest (${manifestBytes.length} bytes); cidv1=${await cidv1(manifestBytes)}`);+ } else {+ const pinnedManifest = await pinToIPFS(manifestBytes, 'three-ws-agent.json').catch(() => null);+ if (pinnedManifest) {+ metadataUri = pinnedManifest.uri;+ console.log(`✓ manifest pinned: ${metadataUri} (cid ${pinnedManifest.cid})`);+ } else {+ // First-party fallback — write the resolvable Metaplex metadata to public/.+ writeJsonTabs(MANIFEST_PUBLIC_PATH, manifest);+ metadataUri = MANIFEST_PUBLIC_URL;+ console.log(`✓ manifest written first-party (no IPFS provider): ${metadataUri}`);+ }+ }++ if (dryRun) {+ console.log('\n[dry-run] all inputs verified. Re-run without --dry-run (and with a funded authority) to mint.');+ return;+ }++ // 6. Funding gate — never half-finish.+ const balLamports = Number((await umi.rpc.getBalance(authoritySigner.publicKey)).basisPoints);+ console.log(`balance: ${(balLamports / LAMPORTS_PER_SOL).toFixed(5)} SOL`);+ if (balLamports < NEED_LAMPORTS) {+ console.error(+ `\nInsufficient SOL. Fund the authority wallet, then re-run:\n` ++ ` address: ${authorityAddr}\n` ++ ` need: ~${(NEED_LAMPORTS / LAMPORTS_PER_SOL).toFixed(3)} SOL on ${network}\n` ++ (network === 'devnet'+ ? ` devnet: solana airdrop 1 ${authorityAddr} --url ${rpc} (or https://faucet.solana.com)\n`+ : ` mainnet: transfer ~0.02 SOL to the address above\n`),+ );+ process.exit(2);+ }++ // 7. Ensure the collection exists (deploy on first run with the vanity key).+ if (!collectionAddr) {+ const collectionSigner = collectionKp+ ? createSignerFromKeypair(umi, umi.eddsa.createKeypairFromSecretKey(collectionKp.secretKey))+ : generateSigner(umi);+ const collectionUri = `${THREE_WS.website}/api/agents/solana-collection-metadata?network=${network}`;+ console.log(`Deploying collection ${collectionSigner.publicKey}…`);+ await createCollection(umi, {+ collection: collectionSigner,+ name: 'three.ws Agents',+ uri: collectionUri,+ plugins: [+ {+ type: 'Attributes',+ attributeList: [+ { key: 'platform', value: 'three.ws' },+ { key: 'url', value: THREE_WS.website },+ { key: 'standard', value: 'metaplex-core' },+ { key: 'schema', value: 'agent-manifest/0.1' },+ { key: 'chain', value: `solana:${SOLANA_REFS[network]}` },+ ],+ },+ ],+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ collectionAddr = collectionSigner.publicKey.toString();+ console.log(`✓ collection deployed: ${collectionAddr}`);+ }+ const collectionAsset = await fetchCollection(umi, umiPublicKey(collectionAddr));++ // 8. Mint the platform agent asset into the collection.+ const assetSigner = generateSigner(umi);+ const ownerPk = umiPublicKey(ownerAddr);+ console.log(`Minting agent asset ${assetSigner.publicKey}…`);+ const result = await create(umi, {+ asset: assetSigner,+ collection: collectionAsset,+ authority: authoritySigner,+ owner: ownerPk,+ name: card.name.slice(0, 32),+ uri: metadataUri,+ plugins: [+ { type: 'Attributes', attributeList: onchainAttributes() },+ {+ type: 'Royalties',+ basisPoints: 500,+ creators: [{ address: ownerPk, percentage: 100 }],+ ruleSet: ruleSet('None'),+ },+ ],+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ const asset = assetSigner.publicKey.toString();+ const signature = bs58.encode(result.signature);+ console.log(`✓ minted: asset ${asset} tx ${signature}`);++ // 9. Best-effort: enrol in the Metaplex Agent Registry (Agent Identity PDA).+ let identityPda = null;+ try {+ const { registerAgentIdentity } = await import('../api/_lib/agent-registry.js');+ const reg = await registerAgentIdentity({+ umi,+ authoritySigner,+ asset,+ collectionAddr,+ registrationUri: `${THREE_WS.website}/.well-known/agent-registration.json`,+ });+ identityPda = reg.identityPda;+ console.log(`✓ Agent Registry: identity PDA ${identityPda}${reg.alreadyRegistered ? ' (existing)' : ''}`);+ } catch (e) {+ console.log(` Agent Registry enrolment skipped (${e.message}) — Core asset registration stands.`);+ }++ // 10. Persist ledger + reconcile discovery docs.+ const record = {+ asset,+ collection: collectionAddr,+ owner: ownerAddr,+ custody: ownerAddr === authorityAddr,+ authority: authorityAddr,+ metadata_uri: metadataUri,+ tx_hash: signature,+ ...(identityPda ? { identity_pda: identityPda } : {}),+ confirmed_at: new Date().toISOString(),+ explorer: `https://solscan.io/account/${asset}${network === 'devnet' ? '?cluster=devnet' : ''}`,+ };+ const led = loadLedger();+ led.networks[network] = record;+ writeJsonTabs(LEDGER_PATH, led);+ console.log(`✓ ledger: ${LEDGER_PATH}`);++ reconcile(network, record);+ console.log(`\n✅ three.ws registered on Solana ${network}.`);+ console.log(` passport: ${THREE_WS.website}/agent-passport.html?asset=${asset}&network=${network}`);+ console.log(` explorer: ${record.explorer}`);+}++// Reconcile the two public discovery docs from a ledger record.+function reconcile(network, record) {+ const onchain = {+ family: 'solana',+ chain: `solana:${SOLANA_REFS[network]}`,+ cluster: network,+ contract_or_mint: record.asset,+ collection: record.collection,+ metadata_uri: record.metadata_uri,+ owner: record.owner,+ tx_hash: record.tx_hash,+ ...(record.identity_pda ? { onchain_id: record.identity_pda } : {}),+ confirmed_at: record.confirmed_at,+ };+ const registration = {+ agentId: record.asset,+ agentRegistry: `solana:${SOLANA_REFS[network]}:${record.collection}`,+ };+ // Mainnet is the canonical identity written into the docs; devnet stays in the+ // ledger only so it never overwrites a mainnet registration in the public docs.+ if (network === 'mainnet') {+ for (const p of [CARD_PATH, REG_PATH]) {+ if (applyOnchainToDoc(p, onchain, registration)) console.log(`✓ updated ${basename(p)}`);+ }+ } else {+ console.log(' (devnet — discovery docs reserved for the mainnet identity; recorded in ledger)');+ }+}++main().catch((err) => {+ console.error('\n❌ failed:', err?.message || err);+ process.exit(1);+});diff --git a/scripts/verify-solana-parity.mjs b/scripts/verify-solana-parity.mjsindex 9e0ff9a86..0f9c51b5b 100644--- a/scripts/verify-solana-parity.mjs+++ b/scripts/verify-solana-parity.mjs@@ -40,6 +40,7 @@*/import { execFileSync } from 'node:child_process';import { readFileSync, readdirSync } from 'node:fs';+import { readFile } from 'node:fs/promises';import { resolve, dirname } from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';@@ -65,16 +66,66 @@ const TOKEN_2022_PROGRAM = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';*/function canonicalRegistry(pumpIds) {return [- { label: '$THREE mint', address: THREE_MINT, kind: 'token-2022-mint', names: ['THREE_MINT', 'THREE_TOKEN_MINT', 'TOKEN_MINT'] },- { label: 'Pump bonding-curve program', address: pumpIds.PUMP_PROGRAM_ID, kind: 'program', names: ['PUMP_PROGRAM', 'PUMP_PROGRAM_ID'] },- { label: 'PumpSwap AMM program', address: pumpIds.PUMP_AMM_PROGRAM_ID, kind: 'program', names: ['PUMP_AMM_PROGRAM', 'PUMP_AMM_PROGRAM_ID'] },- { label: 'PumpFees program', address: pumpIds.PUMP_FEE_PROGRAM_ID, kind: 'program', names: ['PUMP_FEE_PROGRAM', 'PUMP_FEE_PROGRAM_ID'] },- { label: 'SPL Token program', address: SPL_TOKEN_PROGRAM, kind: 'program', names: ['TOKEN_PROGRAM', 'TOKEN_PROGRAM_ID', 'SPL_TOKEN_PROGRAM_ID'] },- { label: 'Token-2022 program', address: TOKEN_2022_PROGRAM, kind: 'program', names: ['TOKEN_2022_PROGRAM_ID', 'TOKEN2022_PROGRAM_ID'] },- { label: 'Memo program', address: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr', kind: 'program', names: ['MEMO_PROGRAM', 'MEMO_PROGRAM_ID'] },- { label: 'Associated-Token program', address: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL', kind: 'program', names: ['ASSOCIATED_TOKEN_PROGRAM_ID', 'ASSOCIATED_TOKEN_PROGRAM'] },- { label: 'Wrapped SOL mint', address: pumpIds.WSOL_MINT, kind: 'token-mint', names: ['WSOL_MINT', 'WSOL', 'NATIVE_SOL_MINT', 'SOL_MINT'] },- { label: 'USDC (mainnet) mint', address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', kind: 'token-mint', names: ['USDC_MINT', 'USDC_MAINNET_MINT', 'USDC_SOLANA_MINT'] },+ {+ label: '$THREE mint',+ address: THREE_MINT,+ kind: 'token-2022-mint',+ names: ['THREE_MINT', 'THREE_TOKEN_MINT', 'TOKEN_MINT'],+ },+ {+ label: 'Pump bonding-curve program',+ address: pumpIds.PUMP_PROGRAM_ID,+ kind: 'program',+ names: ['PUMP_PROGRAM', 'PUMP_PROGRAM_ID'],+ },+ {+ label: 'PumpSwap AMM program',+ address: pumpIds.PUMP_AMM_PROGRAM_ID,+ kind: 'program',+ names: ['PUMP_AMM_PROGRAM', 'PUMP_AMM_PROGRAM_ID'],+ },+ {+ label: 'PumpFees program',+ address: pumpIds.PUMP_FEE_PROGRAM_ID,+ kind: 'program',+ names: ['PUMP_FEE_PROGRAM', 'PUMP_FEE_PROGRAM_ID'],+ },+ {+ label: 'SPL Token program',+ address: SPL_TOKEN_PROGRAM,+ kind: 'program',+ names: ['TOKEN_PROGRAM', 'TOKEN_PROGRAM_ID', 'SPL_TOKEN_PROGRAM_ID'],+ },+ {+ label: 'Token-2022 program',+ address: TOKEN_2022_PROGRAM,+ kind: 'program',+ names: ['TOKEN_2022_PROGRAM_ID', 'TOKEN2022_PROGRAM_ID'],+ },+ {+ label: 'Memo program',+ address: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr',+ kind: 'program',+ names: ['MEMO_PROGRAM', 'MEMO_PROGRAM_ID'],+ },+ {+ label: 'Associated-Token program',+ address: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL',+ kind: 'program',+ names: ['ASSOCIATED_TOKEN_PROGRAM_ID', 'ASSOCIATED_TOKEN_PROGRAM'],+ },+ {+ label: 'Wrapped SOL mint',+ address: pumpIds.WSOL_MINT,+ kind: 'token-mint',+ names: ['WSOL_MINT', 'WSOL', 'NATIVE_SOL_MINT', 'SOL_MINT'],+ },+ {+ label: 'USDC (mainnet) mint',+ address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ kind: 'token-mint',+ names: ['USDC_MINT', 'USDC_MAINNET_MINT', 'USDC_SOLANA_MINT'],+ },];}@@ -90,18 +141,24 @@ export async function loadCanonical({ root = ROOT } = {}) {// $THREE mint: read the env.js default by regex (importing env.js pulls the// whole server config surface; the literal default is all we need).const envSrc = readFileSync(resolve(root, 'api/_lib/env.js'), 'utf8');- const m = envSrc.match(/opt\(\s*['"]THREE_TOKEN_MINT['"]\s*,\s*['"]([1-9A-HJ-NP-Za-km-z]{32,44})['"]\s*\)/);+ const m = envSrc.match(+ /opt\(\s*['"]THREE_TOKEN_MINT['"]\s*,\s*['"]([1-9A-HJ-NP-Za-km-z]{32,44})['"]\s*\)/,+ );const envMint = m?.[1];const internal = [];if (envMint !== THREE_MINT) {- internal.push(`api/_lib/env.js THREE_TOKEN_MINT default ${JSON.stringify(envMint)} != canonical ${THREE_MINT}`);+ internal.push(+ `api/_lib/env.js THREE_TOKEN_MINT default ${JSON.stringify(envMint)} != canonical ${THREE_MINT}`,+ );}if (programs.WSOL_MINT !== 'So11111111111111111111111111111111111111112') {internal.push(`api/_lib/solana/programs.js WSOL_MINT drifted: ${programs.WSOL_MINT}`);}if (internal.length) {- const err = new Error('canonical source-of-truth disagreement:\n ' + internal.join('\n '));+ const err = new Error(+ 'canonical source-of-truth disagreement:\n ' + internal.join('\n '),+ );err.internal = internal;throw err;}@@ -120,25 +177,39 @@ const SCAN_EXTS = /\.(js|mjs|ts)$/;const SCAN_SKIP = /(^|\/)(node_modules|dist|dist-lib|build|\.vercel|coverage)\//;// 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;+const SCAN_SKIP_FILE =+ /(\.test\.|\.spec\.|\/fixtures\/|_demo-fixtures|\/idl\/|\.min\.js$|\.bundle\.js$|\/(libs|draco|ktx2|vendor|wasm)\/)/;export function listSourceFiles({ root = ROOT } = {}) {let files;try {- const out = execFileSync('git', ['ls-files'], { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });+ const out = execFileSync('git', ['ls-files'], {+ cwd: root,+ encoding: 'utf8',+ maxBuffer: 64 * 1024 * 1024,+ stdio: ['ignore', 'pipe', 'pipe'],+ });files = out.split('\n').filter(Boolean);} catch {files = listOnDisk(root);}- return files.filter((f) => SCAN_EXTS.test(f) && !SCAN_SKIP.test(`/${f}`) && !SCAN_SKIP_FILE.test(`/${f}`));+ return files.filter(+ (f) => SCAN_EXTS.test(f) && !SCAN_SKIP.test(`/${f}`) && !SCAN_SKIP_FILE.test(`/${f}`),+ );}function listOnDisk(root) {const out = [];const stack = [''];- const skipDir = new Set(['node_modules', '.git', 'dist', 'dist-lib', 'build', '.vercel', 'coverage']);+ const skipDir = new Set([+ 'node_modules',+ '.git',+ 'dist',+ 'dist-lib',+ 'build',+ '.vercel',+ 'coverage',+ ]);while (stack.length) {const rel = stack.pop();let entries;@@ -162,7 +233,9 @@ function listOnDisk(root) {// ---------------------------------------------------------------------------const BASE58 = '[1-9A-HJ-NP-Za-km-z]';-const PUMP_LITERAL = new RegExp(`['"\`](${BASE58}{42,43}pump)['"\`]`, 'g');+// A pump.fun mint is a 32–44 char base58 address ending in `pump`, so the prefix+// before `pump` is 28–40 chars. Quoted so we only flag hardcoded literals.+const PUMP_LITERAL = new RegExp(`['"\`](${BASE58}{28,40}pump)['"\`]`, 'g');/*** Scans first-party source for:@@ -171,9 +244,14 @@ const PUMP_LITERAL = new RegExp(`['"\`](${BASE58}{42,43}pump)['"\`]`, 'g');* - named-constant drift: any assignment to a canonical constant identifier* whose base58 literal differs from the canonical address.*- * Returns { problems } — each with file, line, and a precise diff string.+ * Returns an array of problems — each with file, line, and a precise diff string.+ * Reads files in parallel batches (the overlay FS is latency-bound, not+ * throughput-bound) and scans each file's full text in a single regex pass.*/-export function scanForDrift(registry, { root = ROOT, files = listSourceFiles({ root }) } = {}) {+export async function scanForDrift(+ registry,+ { root = ROOT, files = listSourceFiles({ root }) } = {},+) {const problems = [];// name → {address,label} lookup for the constant-assignment scan.const byName = new Map();@@ -181,53 +259,97 @@ export function scanForDrift(registry, { root = ROOT, files = listSourceFiles({const nameAlternation = [...byName.keys()].sort((a, b) => b.length - a.length).join('|');// `NAME = … 'BASE58'` or `NAME = new PublicKey('BASE58')`. \b guards against// matching USDC_MINT inside USDC_MINT_DEVNET etc.- const assignRe = new RegExp(`\\b(${nameAlternation})\\b\\s*(?::[^=]+)?=\\s*(?:new\\s+PublicKey\\(\\s*)?['"\`](${BASE58}{32,44})['"\`]`, 'g');+ const assignRe = new RegExp(+ `\\b(${nameAlternation})\\b\\s*(?::[^=]+)?=\\s*(?:new\\s+PublicKey\\(\\s*)?['"\`](${BASE58}{32,44})['"\`]`,+ 'g',+ );- for (const rel of files) {- let text;- try {- text = readFileSync(resolve(root, rel), 'utf8');- } catch {- continue;+ // Match offsets back to line numbers without a per-line matchAll (which clones+ // the alternation regex for every line of every file — the build-gate killer).+ const lineNumberAt = (newlineOffsets, index) => {+ let lo = 0;+ let hi = newlineOffsets.length;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (newlineOffsets[mid] < index) lo = mid + 1;+ else hi = mid;}- 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];-- // 1. rogue / drifted $THREE mint- for (const mt of line.matchAll(PUMP_LITERAL)) {- if (mt[1] !== THREE_MINT) {- problems.push({- type: 'rogue-coin',- file: rel,- line: i + 1,- detail: `hardcoded pump.fun mint "${mt[1]}" is not the canonical $THREE CA ${THREE_MINT} — $THREE is the only coin (CLAUDE.md); fix or remove`,- });- }+ return lo + 1;+ };+ const lineTextAt = (text, index) => {+ const start = text.lastIndexOf('\n', index - 1) + 1;+ let end = text.indexOf('\n', index);+ if (end === -1) end = text.length;+ return text.slice(start, end);+ };++ const scanText = (rel, text) => {+ if (text.length > 4_000_000) return; // generated bundle++ // Single linear newline scan: feeds both the minified-blob guard (max line+ // length) and offset→line mapping. Avoids the O(n²) /[^\n]{20000}/ regex.+ const newlineOffsets = [];+ let prev = -1;+ let maxLine = 0;+ for (let p = text.indexOf('\n'); p !== -1; p = text.indexOf('\n', p + 1)) {+ newlineOffsets.push(p);+ if (p - prev > maxLine) maxLine = p - prev;+ prev = p;+ }+ if (text.length - prev > maxLine) maxLine = text.length - prev;+ // Authored source never has 20k-char lines; a file that does is a minified+ // blob that slipped past the path filter — skip it.+ if (maxLine > 20_000) return;++ // 1. rogue / drifted $THREE mint — one whole-file pass.+ PUMP_LITERAL.lastIndex = 0;+ for (let mt = PUMP_LITERAL.exec(text); mt; mt = PUMP_LITERAL.exec(text)) {+ if (mt[1] !== THREE_MINT) {+ problems.push({+ type: 'rogue-coin',+ file: rel,+ line: lineNumberAt(newlineOffsets, mt.index),+ detail: `hardcoded pump.fun mint "${mt[1]}" is not the canonical $THREE CA ${THREE_MINT} — $THREE is the only coin (CLAUDE.md); fix or remove`,+ });}+ }- // 2. drifted canonical constant- for (const mt of line.matchAll(assignRe)) {- const entry = byName.get(mt[1]);- const got = mt[2];- if (entry && got !== entry.address) {- // A devnet/test variant legitimately differs — skip lines that- // self-identify as such (e.g. SOLANA_USDC_MINT_DEVNET on its own line).- if (/devnet|testnet|localnet/i.test(line)) continue;- problems.push({- type: 'const-drift',- file: rel,- line: i + 1,- detail: `${mt[1]} = ${got} but canonical ${entry.label} is ${entry.address}`,- });- }+ // 2. drifted canonical constant — one whole-file pass.+ assignRe.lastIndex = 0;+ for (let mt = assignRe.exec(text); mt; mt = assignRe.exec(text)) {+ const entry = byName.get(mt[1]);+ const got = mt[2];+ if (entry && got !== entry.address) {+ const lineText = lineTextAt(text, mt.index);+ // A devnet/test variant legitimately differs — skip lines that+ // self-identify as such (e.g. SOLANA_USDC_MINT_DEVNET on its own line).+ if (/devnet|testnet|localnet/i.test(lineText)) continue;+ problems.push({+ type: 'const-drift',+ file: rel,+ line: lineNumberAt(newlineOffsets, mt.index),+ detail: `${mt[1]} = ${got} but canonical ${entry.label} is ${entry.address}`,+ });}}+ };++ const BATCH = 64;+ for (let i = 0; i < files.length; i += BATCH) {+ await Promise.all(+ files.slice(i, i + BATCH).map(async (rel) => {+ let text;+ try {+ text = await readFile(resolve(root, rel), 'utf8');+ } catch {+ return;+ }+ scanText(rel, text);+ }),+ );}+ // Stable order regardless of read-completion races, so a CI diff is reproducible.+ problems.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);return problems;}@@ -237,7 +359,8 @@ export function scanForDrift(registry, { root = ROOT, files = listSourceFiles({// ---------------------------------------------------------------------------function rpcEndpoint(env = process.env) {- if (env.SOLANA_RPC_URL && !/api\.mainnet-beta\.solana\.com/.test(env.SOLANA_RPC_URL)) return env.SOLANA_RPC_URL;+ if (env.SOLANA_RPC_URL && !/api\.mainnet-beta\.solana\.com/.test(env.SOLANA_RPC_URL))+ return env.SOLANA_RPC_URL;if (env.HELIUS_API_KEY) return `https://mainnet.helius-rpc.com/?api-key=${env.HELIUS_API_KEY}`;return env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';}@@ -247,7 +370,12 @@ async function getAccountInfo(url, address) {const res = await fetch(url, {method: 'POST',headers: { 'content-type': 'application/json' },- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getAccountInfo', params: [address, { encoding: 'jsonParsed' }] }),+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'getAccountInfo',+ params: [address, { encoding: 'jsonParsed' }],+ }),signal: AbortSignal.timeout(15_000),});if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };@@ -290,11 +418,24 @@ export async function checkLiveProvenance(registry, { env = process.env } = {})if (r.value.executable) ok.push({ ...ctx, note: 'executable' });else wrong.push({ ...ctx, reason: `not executable (owner ${owner})` });} else if (entry.kind === 'token-2022-mint') {- if (owner === TOKEN_2022_PROGRAM && program === 'spl-token-2022') ok.push({ ...ctx, note: 'token-2022 mint' });- else wrong.push({ ...ctx, reason: `expected a Token-2022 mint, got owner ${owner} (${program})` });+ if (owner === TOKEN_2022_PROGRAM && program === 'spl-token-2022')+ ok.push({ ...ctx, note: 'token-2022 mint' });+ else+ wrong.push({+ ...ctx,+ reason: `expected a Token-2022 mint, got owner ${owner} (${program})`,+ });} else if (entry.kind === 'token-mint') {- if ((owner === SPL_TOKEN_PROGRAM || owner === TOKEN_2022_PROGRAM) && program?.startsWith('spl-token')) ok.push({ ...ctx, note: `${program} mint` });- else wrong.push({ ...ctx, reason: `expected an SPL mint, got owner ${owner} (${program})` });+ if (+ (owner === SPL_TOKEN_PROGRAM || owner === TOKEN_2022_PROGRAM) &&+ program?.startsWith('spl-token')+ )+ ok.push({ ...ctx, note: `${program} mint` });+ else+ wrong.push({+ ...ctx,+ reason: `expected an SPL mint, got owner ${owner} (${program})`,+ });}}return { wrong, unreachable, ok };@@ -317,33 +458,46 @@ if (isMain) {process.exit(1);}- const problems = scanForDrift(registry);+ const problems = await scanForDrift(registry);if (problems.length) {failed = true;const rogue = problems.filter((p) => p.type === 'rogue-coin');const drift = problems.filter((p) => p.type === 'const-drift');- if (rogue.length) console.error(`[verify:solana] FAIL — ${rogue.length} non-$THREE coin / drifted mint literal(s):`);+ if (rogue.length)+ console.error(+ `[verify:solana] FAIL — ${rogue.length} non-$THREE coin / drifted mint literal(s):`,+ );for (const p of rogue) console.error(` ${p.file}:${p.line} — ${p.detail}`);- if (drift.length) console.error(`[verify:solana] FAIL — ${drift.length} drifted Solana constant(s):`);+ if (drift.length)+ console.error(`[verify:solana] FAIL — ${drift.length} drifted Solana constant(s):`);for (const p of drift) console.error(` ${p.file}:${p.line} — ${p.detail}`);} else {- console.log(`[verify:solana] parity OK — $THREE mint + ${registry.length - 1} canonical Solana addresses consistent across all first-party source`);+ console.log(+ `[verify:solana] parity OK — $THREE mint + ${registry.length - 1} canonical Solana addresses consistent across all first-party source`,+ );}const liveOn = (process.env.VERIFY_SOLANA_LIVE ?? '1') !== '0';if (liveOn) {const { wrong, unreachable, ok } = await checkLiveProvenance(registry);- for (const e of ok) console.log(`[verify:solana] live ${e.label} ${e.address} — ${e.note}`);+ for (const e of ok)+ console.log(`[verify:solana] live ${e.label} ${e.address} — ${e.note}`);if (unreachable.length) {- console.warn(`[verify:solana] WARN — ${unreachable.length} account(s) unreachable (network — not failing the build):`);+ console.warn(+ `[verify:solana] WARN — ${unreachable.length} account(s) unreachable (network — not failing the build):`,+ );for (const u of unreachable) console.warn(` ${u.label} ${u.address} — ${u.error}`);}if (wrong.length) {failed = true;- console.error(`[verify:solana] FAIL — ${wrong.length} account(s) are the wrong kind on-chain:`);+ console.error(+ `[verify:solana] FAIL — ${wrong.length} account(s) are the wrong kind on-chain:`,+ );for (const w of wrong) console.error(` ${w.label} ${w.address} — ${w.reason}`);}- console.log(`[verify:solana] live check — ${ok.length} verified, ${wrong.length} wrong, ${unreachable.length} unreachable`);+ console.log(+ `[verify:solana] live check — ${ok.length} verified, ${wrong.length} wrong, ${unreachable.length} unreachable`,+ );} else {console.log('[verify:solana] live provenance check skipped (VERIFY_SOLANA_LIVE=0)');}diff --git a/src/agent-detail.js b/src/agent-detail.jsindex bda2fe32e..0ad97b7cf 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -1684,15 +1684,34 @@ function normalize(rec, avatar) {// the requester is the owner — see api/agents.js decorate(row, isOwner).isOwner: !!rec.user_id,// On-chain ERC-8004 identifiers for the validation attestation badge.- // Present only for EVM-registered agents (Solana token agents have no- // erc8004_agent_id, so the validation badge is correctly skipped for them).- chainId: Number(onchain?.chain_id ?? rec.chain_id) || null,- erc8004AgentId: rec.erc8004_agent_id != null ? String(rec.erc8004_agent_id) : null,+ // Owner responses carry chain_id / erc8004_agent_id directly; public+ // responses carry them through the canonical `onchain` block (caip2 chain ++ // onchain_id). Resolved for EVM agents only — Solana token agents have no+ // ValidationRegistry record, so the badge is correctly skipped for them.+ ...erc8004Ids(rec, onchain),glbUrl: rec.avatar_glb_url || onchain?.body_uri || meta.glb_url || null,rawMetadata: rec,};}+/** Resolve { chainId, erc8004AgentId } from owner or public on-chain fields (EVM only). */+function erc8004Ids(rec, onchain) {+ const caip2Match = /^eip155:(\d+)$/.exec(String(onchain?.chain || ''));+ const isEvm = onchain+ ? onchain.family === 'evm' || !!caip2Match+ : rec.chain_id != null && rec.erc8004_agent_id != null;+ if (!isEvm) return { chainId: null, erc8004AgentId: null };++ const chainId = Number(rec.chain_id ?? onchain?.chain_id ?? caip2Match?.[1]) || null;+ const agentId =+ rec.erc8004_agent_id != null+ ? String(rec.erc8004_agent_id)+ : onchain?.onchain_id != null+ ? String(onchain.onchain_id)+ : null;+ return { chainId, erc8004AgentId: agentId };+}+// Agents and avatars live in separate tables with separate UUIDs — an agent// merely references an avatar via avatar_id. So an id that 404s as an agent may// actually be an avatar shared (or old-linked) as /agents/:id. Probe the avatardiff --git a/src/game/coin-buy.js b/src/game/coin-buy.jsindex 39c33e503..ccbedab73 100644--- a/src/game/coin-buy.js+++ b/src/game/coin-buy.js@@ -403,7 +403,10 @@ class TradeModal {this.balLine.hidden = false;if (this.holdings) {if (this.holdings.ui > 0) {+ const over = this.amount > this.holdings.ui + 1e-9;+ this.balLine.classList.toggle('cc-buy-bal-warn', over);this.balLine.append(el('span', { text: `You hold ${compactCount(this.holdings.ui)} ${this.symTokens}` }));+ if (over) this.balLine.append(el('span', { class: 'cc-buy-bal-sep', text: ' · ' }), el('span', { text: `more than you hold` }));} else {this.balLine.append(el('span', { class: 'cc-buy-wallet-off', text: `You don't hold any ${this.symTokens} yet` }));}@@ -440,12 +443,12 @@ class TradeModal {if (!connected) { this.cta.textContent = 'Connect wallet'; this.ctaLabel = 'connect'; this.cta.disabled = false; return; }if (this.mode === 'sell') {+ // Holdings are advisory: a read can lag the chain, so a typed sell is+ // never blocked on our balance read — the chain is the source of truth and+ // an over-sell surfaces as an actionable error. We only flag it (below).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;+ this.cta.disabled = !(this.amount > 0);return;}@@ -586,12 +589,15 @@ class TradeModal {// 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;+ const haveHoldings = !!hold && hold.ui > 0 && !!hold.base;+ if (this._sellMax && haveHoldings) 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) {+ // Only clamp against a real, positive holdings read — a 0/failed read is+ // treated as unknown, not as "sell nothing", so the chain can reject it.+ if (haveHoldings) {const max = BigInt(hold.base);if (want > max) want = max;}diff --git a/src/pump/coin-status-card.dom.test.js b/src/pump/coin-status-card.dom.test.jsnew file mode 100644index 000000000..e643aff91--- /dev/null+++ b/src/pump/coin-status-card.dom.test.js@@ -0,0 +1,124 @@+// @vitest-environment jsdom+//+// DOM-level tests for mountCoinStatus: each variant renders against a stubbed+// /api/pump/coin response, the error state recovers via Retry, and destroy()+// stops the refresh timer. fetch is stubbed at the global boundary.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mountCoinStatus } from './coin-status-card.js';++const MINT = 'THREEsynthetic1111111111111111111111111111';++// A representative pump.fun coin object (the shape /api/pump/coin proxies).+function coinBody(overrides = {}) {+ return {+ mint: MINT,+ name: 'Synthetic Coin',+ symbol: 'SYN',+ image_uri: 'https://example.test/logo.png',+ usd_market_cap: 34_500, // ~50% to the ~$69k graduation cap+ total_supply: 1_000_000_000_000_000, // 1e9 tokens at 6 decimals+ complete: false,+ created_timestamp: Date.now() - 5 * 60_000,+ volume_24h: 12_345,+ ...overrides,+ };+}++function okFetch(body) {+ return vi.fn().mockResolvedValue({ ok: true, json: () => Promise.resolve(body) });+}++let container;++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+});++afterEach(() => {+ container.remove();+ vi.restoreAllMocks();+ vi.useRealTimers();+});++describe('mountCoinStatus — variants', () => {+ it('renders the chip variant with symbol, price, mcap and graduation', async () => {+ vi.stubGlobal('fetch', okFetch(coinBody()));+ const handle = mountCoinStatus(container, MINT, { variant: 'chip', refreshMs: 0 });+ // Wait for a populated-only marker (the skeleton shares the .csc-chip base class).+ await vi.waitFor(() => expect(container.querySelector('.csc-sym')).toBeTruthy());++ expect(container.querySelector('.csc-sym').textContent).toBe('$SYN');+ expect(container.querySelector('.csc-mcap').textContent).toBe('$34.5K');+ expect(container.querySelector('.csc-price')).toBeTruthy();+ expect(container.querySelector('.csc-grad').textContent).toMatch(/to grad/);+ expect(container.getAttribute('aria-busy')).toBe('false');+ handle.destroy();+ });++ it('renders the row variant inside its container', async () => {+ vi.stubGlobal('fetch', okFetch(coinBody()));+ const handle = mountCoinStatus(container, MINT, { variant: 'row', refreshMs: 0 });+ await vi.waitFor(() => expect(container.querySelector('.csc-sym')).toBeTruthy());++ expect(container.querySelector('.csc-mint').textContent).toContain('…');+ expect(container.querySelector('.csc-vol').textContent).toContain('Vol');+ handle.destroy();+ });++ it('renders the card variant with a graduation ring and crossfaded placeholder', async () => {+ vi.stubGlobal('fetch', okFetch(coinBody()));+ const placeholder = document.createElement('span');+ placeholder.className = 'my-placeholder';+ const handle = mountCoinStatus(container, MINT, { variant: 'card', refreshMs: 0, placeholder, showBuy: true });+ await vi.waitFor(() => expect(container.querySelector('.csc-card-name')).toBeTruthy());++ expect(container.querySelector('.csc-ring')).toBeTruthy();+ expect(container.querySelector('.csc-avatar .my-placeholder')).toBeTruthy();+ expect(container.querySelector('.csc-card-img')).toBeTruthy();+ expect(container.querySelector('.csc-buy').getAttribute('href')).toBe(`https://pump.fun/${MINT}`);+ handle.destroy();+ });++ it('marks a graduated coin as graduated', async () => {+ vi.stubGlobal('fetch', okFetch(coinBody({ complete: true })));+ const handle = mountCoinStatus(container, MINT, { variant: 'chip', refreshMs: 0 });+ await vi.waitFor(() => expect(container.querySelector('.csc-grad-done')).toBeTruthy());+ expect(container.querySelector('.csc-grad-done').textContent).toBe('Graduated');+ handle.destroy();+ });+});++describe('mountCoinStatus — error + lifecycle', () => {+ it('shows an error state with a Retry button that re-fetches and recovers', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce({ ok: false, status: 502, json: () => Promise.resolve({}) })+ .mockResolvedValue({ ok: true, json: () => Promise.resolve(coinBody()) });+ vi.stubGlobal('fetch', fetchMock);++ const handle = mountCoinStatus(container, MINT, { variant: 'chip', refreshMs: 0 });+ await vi.waitFor(() => expect(container.querySelector('.csc-error')).toBeTruthy());+ expect(container.querySelector('[role="alert"]')).toBeTruthy();++ container.querySelector('.csc-retry').click();+ await vi.waitFor(() => expect(container.querySelector('.csc-chip')).toBeTruthy());+ expect(container.querySelector('.csc-error')).toBeFalsy();+ handle.destroy();+ });++ it('stops fetching after destroy()', async () => {+ vi.useFakeTimers();+ const fetchMock = okFetch(coinBody());+ vi.stubGlobal('fetch', fetchMock);++ const handle = mountCoinStatus(container, MINT, { variant: 'chip', refreshMs: 1000 });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));++ handle.destroy();+ const callsAtDestroy = fetchMock.mock.calls.length;+ await vi.advanceTimersByTimeAsync(3000);+ expect(fetchMock.mock.calls.length).toBe(callsAtDestroy); // timer cleared+ });+});diff --git a/tasks/onchain-deployment/00-PLAN.md b/tasks/onchain-deployment/00-PLAN.mdindex 981f42c35..232e1cc33 100644--- a/tasks/onchain-deployment/00-PLAN.md+++ b/tasks/onchain-deployment/00-PLAN.md@@ -11,6 +11,7 @@ shows what can run in parallel.## Current state (verified 2026-06-14)Solid:+- ERC-8004 contracts (`contracts/src/{Identity,Reputation,Validation}Registry.sol`),25 passing Foundry tests.- IdentityRegistry + ReputationRegistry deployed deterministically (CREATE2) on@@ -21,6 +22,7 @@ Solid:- Specs published: avatar schema v1, agent-manifest v0.2, 3D Agent Card v1.Gaps (what these tasks close):+1. Mainnet ValidationRegistry never deployed → mainnet `recordValidation()` throws.2. ThreeWSPayments on Base mined-but-no-bytecode → treat as not deployed.3. Solana `agent_invocation` program uses a placeholder ID, never deployed.@@ -34,18 +36,18 @@ Gaps (what these tasks close):## Task list-| # | Task | Wave | Blocks |-|---|------|------|--------|-| 01 | Deploy mainnet ValidationRegistry (15 chains) + wire addresses | 1 | 06, 07 |-| 02 | Re-deploy ThreeWSPayments on Base + verify bytecode | 1 | 10 |-| 03 | Deploy Solana `agent_invocation` program + replace placeholder ID | 1 | 10 |-| 04 | Register three.ws itself (ERC-8004) + fill `.well-known` record | 2 | — |-| 05 | Backfill DEPLOYMENTS.md provenance + address-parity guard script | 1 | — |-| 06 | "Bind existing agent → on-chain" flow + auto-populate manifest | 2 | 10 |-| 07 | Wire ValidationRegistry attestation into registration + allowlist | 2 | — |-| 08 | Surface ReputationRegistry in agent profiles + `/agents` directory | 2 | — |-| 09 | Fund Solana relayers, verify buyback/distribution crons + devnet smoke | 1 | 10 |-| 10 | On-chain end-to-end smoke harness (CI-runnable) | 3 | — |+| # | Task | Wave | Blocks |+| --- | ---------------------------------------------------------------------- | ---- | ------ |+| 01 | Deploy mainnet ValidationRegistry (15 chains) + wire addresses | 1 | 06, 07 |+| 02 | Re-deploy ThreeWSPayments on Base + verify bytecode | 1 | 10 |+| 03 | Deploy Solana `agent_invocation` program + replace placeholder ID | 1 | 10 |+| 04 | Register three.ws itself (ERC-8004) + fill `.well-known` record | 2 | — |+| 05 | Backfill DEPLOYMENTS.md provenance + address-parity guard script | 1 | — |+| 06 | "Bind existing agent → on-chain" flow + auto-populate manifest | 2 | 10 |+| 07 | Wire ValidationRegistry attestation into registration + allowlist | 2 | — |+| 08 | Surface ReputationRegistry in agent profiles + `/agents` directory | 2 | — |+| 09 | Fund Solana relayers, verify buyback/distribution crons + devnet smoke | 1 | 10 |+| 10 | On-chain end-to-end smoke harness (CI-runnable) | 3 | — |## Definition of done (whole plan)@@ -57,6 +59,45 @@ Gaps (what these tasks close):carry reputation — all from the product UI, no manual scripts.- `node scripts/onchain-smoke.mjs` (task 10) passes against testnet/devnet in CI.+## Standing verification net (task 10)++`scripts/onchain-smoke.mjs` is the capstone — the one script that exercises the+whole on-chain agent lifecycle in a single pass and proves "100% wired" stays+true. Run it with `npm run smoke:onchain` (or `node scripts/onchain-smoke.mjs`).++Eight ordered steps, each reporting **PASS / FAIL / SKIP** with timing in a final+table; the process exits non-zero if any step FAILs (SKIP never fails the run):++| # | Step | Default without credentials |+| --- | ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- |+| 1 | Address parity (delegates to `verify-onchain-parity.mjs`; inline fallback) | **PASS** — offline drift check; `--mainnet-readonly` adds the live bytecode sweep |+| 2 | EVM register on Base Sepolia → tokenURI round-trip + 3D-Agent-Card schema + `model.sha256` | SKIP — needs `SMOKE_EVM_PRIVATE_KEY` (funded) |+| 3 | EVM validation attestation → `getLatestByKind` read-back | SKIP — needs a funded allow-listed validator |+| 4 | EVM reputation feedback from a 2nd signer → count increments | SKIP — needs `SMOKE_EVM_PRIVATE_KEY_2` |+| 5 | Solana launch (devnet) `launch-prep`→`launch-confirm` → `pump_agent_mints` row | SKIP — needs `SMOKE_BASE_URL` + `SMOKE_AUTH_COOKIE` + funded devnet wallet |+| 6 | Solana trade (devnet) `buy-prep`→`buy-confirm` → confirmed sig | SKIP — same Solana credentials |+| 7 | x402 pay-by-name resolve + `mode=prep` build (never broadcasts) | SKIP — needs `SMOKE_BASE_URL` + `SMOKE_X402_NAME` |+| 8 | Solana `agent_invocation` `invokeSkill()` → `SkillInvoked` event | SKIP — program id is still the Anchor placeholder (task 03 pending) |++Design contract:++- **CI subset is deterministic and offline.** `npm run smoke:onchain:ci`+ (`--only=parity`) hard-fails on any registry-address drift and needs no egress+ or secrets — safe to block a build on. The full run is reported, not blocking.+- **Value steps SKIP, never FAIL, without their funded signer / deployment /+ credential**, so the read-only subset stays green. Supplying the credentials+ turns each SKIP into PASS/FAIL.+- **Testnet/devnet only by default.** `--mainnet-readonly` permits read-only+ mainnet checks (parity + bytecode) and never broadcasts value.+- **Synthetic signers/mints only.** The harness never touches a real third-party+ token or wallet; `$THREE` is the only coin referenced.+- `--only=<step>` (key or number, comma-separated), `--list`, `--json`, `--help`.+ Credentials load from the environment or `node --env-file=.env`.++As dependency tasks land (01 mainnet validation, 02 Base payments, 03 Solana+`agent_invocation`, 09 funded relayers) and credentials are provided, the matching+SKIPs become PASS — the harness is how we prove each one is actually wired.+## Hard rules (inherited from CLAUDE.md)- The only coin is `$THREE` (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Neverdiff --git a/tasks/pump-dashboard-real-apis/12-alerts-server-persist.md b/tasks/pump-dashboard-real-apis/12-alerts-server-persist.mdindex 5d3e3da84..055a8fec7 100644--- a/tasks/pump-dashboard-real-apis/12-alerts-server-persist.md+++ b/tasks/pump-dashboard-real-apis/12-alerts-server-persist.md@@ -1,5 +1,8 @@# 12 — Alerts page: persist alert config server-side and deliver real notifications+> **DONE — superseded by [Task 04 — Alert rules: server persistence + real delivery](../pumpfun-launchpad-100/04-alerts-server-persistence.md).**+> The original single-config-per-user model (`user_alert_configs` + `GET/PUT /api/alerts/config`) shipped and is now replaced by the richer multi-rule system: `pump_alert_rules` with per-rule kind/target/threshold/cooldown/enabled, full CRUD at `/api/alerts/rules`, server-side evaluation of every kind (graduation, price above/below, whale buy, new-mint-by-agent) in the `pumpfun-monitor` cron via `api/_lib/pump-alert-runner.js`, and multi-channel delivery (in-app + HMAC-signed webhook + Telegram) in `api/_lib/alert-delivery.js`. Existing graduation configs were migrated forward. The original intent below is fully carried over.+## Problem[pump-dashboard.html](../../pump-dashboard.html) `saveAlertConfig()` (lines ~1455–1467) writes to `localStorage` only. Alerts therefore:- Don't survive a different browser / device.diff --git a/tasks/pumpfun-launchpad-100/07-devnet-smoke-runbook.md b/tasks/pumpfun-launchpad-100/07-devnet-smoke-runbook.mdnew file mode 100644index 000000000..94c8850b6--- /dev/null+++ b/tasks/pumpfun-launchpad-100/07-devnet-smoke-runbook.md@@ -0,0 +1,82 @@+# Devnet smoke runbook — `scripts/pump-devnet-smoke.mjs`++The acceptance gate for Tasks 01–03. Proves the launch → buy → sell loop works against **real+on-chain devnet state** for a SOL-paired coin, a USDC-paired coin, and the custodial+(server-signed) path — and that every trade lands in `pump_agent_trades` with the correct+`quote_mint` / `quote_symbol` / `quote_amount`.++It drives the **same production helpers the dispatcher handlers use** — not a reimplementation:+`getPumpSdk`, the `@pump-fun` v2 builders (`createV2` / `buyV2` / `sellV2`), `pump-trade-args`+(slippage, token-program, `resolveCustodialQuote`), `pump-quote` (`tradeQuoteColumns`,+`walletQuoteDeltaAtomics`), `verifySignature`, and the same `sql` client + the exact recording+logic from `api/pump/[action].js`'s buy/sell-confirm. It signs locally, broadcasts, confirms, then+re-reads the row from Postgres and asserts the quote columns.++**Devnet only.** It refuses any mainnet RPC.++## What it runs++| Leg | Proves |+| --- | --- |+| SOL launch + buy + sell | create_v2 (SOL-paired) → buy_v2 → sell_v2, row recorded `quote_symbol='SOL'`, lamports |+| USDC launch + buy + sell | create_v2 (USDC-paired) → buy_v2 → sell_v2 against the whitelisted devnet USDC, row recorded `quote_symbol='USDC'`, 1e6 atoms (Task 01) |+| Custodial buy + sell (SOL & USDC) | a server-held keypair signs + broadcasts, mirroring `loadAgentForSigning` + the custodial handler (Task 03) |++Each leg prints its tx signatures with devnet explorer links and a final `PASS / FAIL / SKIP`+summary. Failures are actionable (which step, the RPC error). It is idempotent: it seeds a+clearly-synthetic devnet user+agent (`[email protected]`), records the trades, asserts, then+cascade-deletes everything it created (pass `--keep` to retain for inspection).++## Funding the signer (required for a live run)++The signer defaults to the x402 demo Solana wallet+(`~/.config/x402-test-wallets/solana.json`); override with `--keypair <path>` or `DEVNET_TEST_WALLET`.++1. **Devnet SOL** (~0.12 needed: create + buys + sells + ATA rent). The script auto-airdrops via+ the configured RPC → Helius devnet (if `HELIUS_API_KEY` is set) → the public faucet. The public+ devnet faucet is aggressively rate-limited (HTTP 429 "airdrop limit reached / faucet dry") and is+ frequently exhausted from shared CI/Codespace IPs. If airdrop fails:+ - fund the printed address at <https://faucet.solana.com> (devnet), **or**+ - pass `--rpc https://devnet.helius-rpc.com/?api-key=<KEY>` (or any premium devnet endpoint)+ whose faucet isn't exhausted — this is the reliable path in an automated environment.+2. **Devnet USDC** (only for the USDC legs). The pump.fun devnet program whitelists exactly one+ quote mint: `4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU`. Its mint authority is an external+ faucet, so it can't be minted locally — fund the printed address at <https://faucet.circle.com>+ (Solana devnet). Without USDC the USDC legs report `SKIP` (not `FAIL`), with the exact address ++ amount to fund.++## Running it++```bash+# Validate the whole build pipeline on-chain WITHOUT funds (simulation only):+node scripts/pump-devnet-smoke.mjs --simulate-only++# Full live run (needs a funded signer; DATABASE_URL from .env.local for the row assertions):+node scripts/pump-devnet-smoke.mjs++# Live run against a premium devnet RPC (bypasses the public-faucet 429):+node scripts/pump-devnet-smoke.mjs --rpc 'https://devnet.helius-rpc.com/?api-key=…'++# Useful flags:+# --sol-only run only the SOL legs+# --no-db skip the Postgres record + assert (chain-only proof)+# --keep keep the seeded devnet rows+# --cleanup delete prior smoke rows and exit+# --usdc <n> / --sol <n> / --slippage-bps <n>+```++`--simulate-only` needs no funds and no DB: it builds every launch instruction with the real SDK,+compiles it to a v0 transaction, checks it serializes within the 1232-byte packet limit, and+simulates it on devnet (halting only on the unfunded fee payer — expected). This is the+fund-independent proof that the instruction-building pipeline is correct.++## Verified status (2026-06-15)++- `--simulate-only`: **4/4 PASS** — SOL, USDC, custodial-SOL, custodial-USDC launch instructions all+ build, compile to v0 (817–922 B), and reach the devnet program. Devnet USDC confirmed whitelisted.+- Live broadcast + DB assertions: **blocked solely by devnet funding** — the public airdrop returns+ 429 (exhausted), `HELIUS_API_KEY` is empty under `vercel env pull`, and devnet USDC needs the+ Circle faucet. Re-run with a premium devnet RPC key or a pre-funded keypair to complete the live+ legs; the script then prints real signatures and asserts the recorded quote columns.+- Tasks 01/03 unit coverage (`tests/pump-quote.test.js`, `tests/api/pump.test.js`): green+ (the trades-quote migration `20260614000000_pump_trades_quote.sql` is applied to the DB).diff --git a/tasks/pumpfun-launchpad-100/07-devnet-smoke-trade.md b/tasks/pumpfun-launchpad-100/07-devnet-smoke-trade.mdindex 332cfa2d2..3be2a0c76 100644--- a/tasks/pumpfun-launchpad-100/07-devnet-smoke-trade.md+++ b/tasks/pumpfun-launchpad-100/07-devnet-smoke-trade.md@@ -53,3 +53,18 @@ notes the devnet smoke "awaits a funded signer" — getting one funded is part o## Out of scopeMainnet execution. This is a devnet correctness proof.++## Deliverables / status (2026-06-15)++- **Script:** [`scripts/pump-devnet-smoke.mjs`](../../scripts/pump-devnet-smoke.mjs) — SOL + USDC ++ custodial launch→buy→sell over the real production helpers, signing locally, with Postgres+ record + quote-column assertions, an idempotent self-seeded test agent, a `--simulate-only`+ build proof, and a `PASS/FAIL/SKIP` summary with explorer links. Refuses mainnet RPC.+- **Runbook:** [`07-devnet-smoke-runbook.md`](07-devnet-smoke-runbook.md) — how to fund the signer+ (SOL faucet + devnet USDC) and run it.+- **Verified:** `--simulate-only` is **4/4 PASS** (all launch instructions build, compile to v0,+ and reach the whitelisted devnet program). Tasks 01/03 landed in commits `3ac9c6e9` + `870bb372`+ (quote columns wired into every INSERT site + custodial USDC); the `20260614000000_pump_trades_quote.sql`+ migration is applied. The **live broadcast + DB assertions are blocked only by devnet funding**+ (public airdrop 429; devnet USDC needs the Circle faucet) — re-run with a premium devnet RPC key+ or pre-funded keypair to complete the live legs.diff --git a/tests/e2e/README.md b/tests/e2e/README.mdnew file mode 100644index 000000000..e2d836d8c--- /dev/null+++ b/tests/e2e/README.md@@ -0,0 +1,77 @@+# Browser end-to-end specs (Playwright)++Real-Chromium specs that drive product UI against the Vite dev server. Kept+separate from Vitest (which only globs `*.test.js`) by the `.spec.js` suffix and+`testDir: tests/e2e` in [`playwright.config.js`](../../playwright.config.js).++## Running++```bash+# whole suite (Vitest unit + Playwright e2e)+npm test++# just the browser specs+npm run test:e2e # = playwright test++# one spec, fast iteration (no retries, single worker)+npx playwright test tests/e2e/launch-token-flow.spec.js --retries=0 --workers=1+npx playwright test tests/e2e/coin-buy-trade.spec.js --retries=0 --workers=1+```++### Pre-start the dev server (avoids cold-start flakiness)++`playwright.config.js` will start `npm run dev` itself, but a cold Vite server+plus the first transform of the Solana/pump SDK module graph can take 30–60s. To+keep that cost out of the per-test budget, **pre-start a dedicated dev server**+and let Playwright reuse it (`reuseExistingServer` is on when `CI` is unset):++```bash+npm run dev # leave running on :3000 in another shell+npx playwright test # reuses the running server+```++Do not wait on `networkidle` in specs — the app holds long-lived connections+(HMR socket, live feeds). Wait on concrete DOM/state instead.++## The conversion-path specs++`launch-token-flow.spec.js` and `coin-buy-trade.spec.js` cover the platform's+most important path — launching a coin and trading it. Both follow the same+fidelity contract as `galaxy.spec.js`:++- **Real product code, driven — not re-implemented.** The specs import and run+ the actual modules ([`src/pump/launch-token-modal.js`](../../src/pump/launch-token-modal.js),+ [`src/game/coin-buy.js`](../../src/game/coin-buy.js)) on a minimal same-origin+ harness page so the dev server still resolves `/src/*` imports and relative+ `/api/*` fetches without booting the heavy homepage.+- **Endpoints fulfilled at the route layer with realistic payloads.** Vite dev+ proxies `/api/*` to production, so the launch-quote / launch-prep /+ launch-confirm endpoints, the pump buy/sell prep+confirm endpoints, and the+ Solana RPC proxy are intercepted with `page.route` to stay deterministic and+ never touch a real chain. The client makes the real fetches; the specs assert+ the real prep/confirm calls fire with the expected body. Prep transactions are+ genuine, parseable `@solana/web3.js` transactions built in Node.+- **`window.solana` is the only stubbed surface** — it is an external browser+ extension, not our code or a real API. Its `signTransaction` returns a+ serialized transaction exactly as a real wallet would, so the broadcast path+ runs for real against the fulfilled RPC.++### `launch-token-flow.spec.js` — all four launch steps++1. step 1 form validation (malformed symbol rejected, flow blocked)+2. step 2 cost breakdown + bonding-curve chart render+3. step 3 wallet connect arms the launch button+4. step 4 sign → broadcast → confirm → success share card (mint chip, share+ link, pump.fun link), asserting real `launch-prep` + `launch-confirm` fire+5. a broadcast failure surfaces specific, actionable copy (no generic catch-all)++### `coin-buy-trade.spec.js` — the buy/sell trade widget++1. wallet gating (connect → buy CTA)+2. lifecycle stage pill: a bonding-curve coin vs a graduated coin render+ distinct, unmistakable states (driven by the real `/api/pump/quote`+ detection)+3. SOL buy happy path: prep → sign → broadcast → settle+4. USDC buy happy path on a graduated coin (denomination upgrades to USDC)+5. sell happy path: switch to Sell, enter amount, prep → broadcast+6. a failed prep surfaces specific, actionable copydiff --git a/tests/e2e/coin-buy-trade.spec.js b/tests/e2e/coin-buy-trade.spec.jsindex 61efac849..eb737064f 100644--- a/tests/e2e/coin-buy-trade.spec.js+++ b/tests/e2e/coin-buy-trade.spec.js@@ -114,8 +114,42 @@ async function installHarness(page, cfg) {return ok(999_999);case 'getSignatureStatuses':return ok({ context: { slot: 1 }, value: [null] });- case 'getTokenAccountsByOwner':+ case 'getTokenAccountsByOwner': {+ // Give a healthy USDC balance so a USDC buy isn't gated into the fund+ // flow; everything else (coin holdings) reads empty — typed sells don't+ // need a holdings fixture. Match on the request body so we're robust to+ // the exact mint-filter param shape web3.js sends.+ if ((route.request().postData() || '').includes(USDC)) {+ return ok({+ context: { slot: 1 },+ value: [{+ pubkey: Keypair.generate().publicKey.toBase58(),+ account: {+ lamports: 2039280,+ owner: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',+ executable: false,+ rentEpoch: 0,+ space: 165,+ data: {+ program: 'spl-token',+ space: 165,+ parsed: {+ type: 'account',+ info: {+ isNative: false,+ mint: USDC,+ owner: WALLET_ADDR,+ state: 'initialized',+ tokenAmount: { amount: '1000000000', decimals: 6, uiAmount: 1000, uiAmountString: '1000' },+ },+ },+ },+ },+ }],+ });+ }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.@@ -200,10 +234,12 @@ test.describe('Coin trade widget', () => {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 });+ // Settles to a confirmed CTA; the durable end state is asserted (the+ // transient "Submitted" status can be raced past when confirm is instant).+ await expect(page.locator('.cc-buy-cta')).toContainText('Bought', { timeout: 60_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 });+ await expect(page.locator('.cc-buy-status[data-kind="ok"]')).toContainText('Bought');});test('USDC buy happy path on a graduated coin', async ({ page }) => {@@ -213,10 +249,13 @@ test.describe('Coin trade widget', () => {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');+ // Wait for the USDC balance to settle so the CTA is stably the buy action+ // (an unsettled balance would route the CTA to the fund flow).+ await expect(page.locator('.cc-buy-bal')).toContainText('1,000 USDC', { timeout: 15_000 });+ await expect(page.locator('.cc-buy-cta')).toContainText('Buy 5 USDC');await page.locator('.cc-buy-cta').click(); // buy- await expect(page.locator('.cc-buy-status')).toContainText('Submitted', { timeout: 30_000 });+ await expect(page.locator('.cc-buy-cta')).toContainText('Bought', { timeout: 60_000 });expect(calls.buyPrep).toMatchObject({ mint: USDC_COIN.mint, wallet_address: WALLET_ADDR, usdc_amount: 5 });expect(calls.broadcast).toBe(1);});@@ -235,12 +274,11 @@ test.describe('Coin trade widget', () => {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 });+ await expect(page.locator('.cc-buy-cta')).toContainText('Sold', { timeout: 60_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 }) => {diff --git a/tests/onchain-smoke.test.js b/tests/onchain-smoke.test.jsnew file mode 100644index 000000000..9e29d9a52--- /dev/null+++ b/tests/onchain-smoke.test.js@@ -0,0 +1,84 @@+// Network-free unit coverage for the on-chain smoke harness (scripts/onchain-smoke.mjs).+//+// The harness itself runs against testnet/devnet and is exercised end-to-end via+// `npm run smoke:onchain`. This suite locks down its two deterministic, offline+// invariants so a regression is caught in CI without any RPC:+// 1. Address parity across the three hand-maintained registry sources holds,+// and an injected drift is detected (the harness's step-1 guarantee).+// 2. A built 3D Agent Card validates against the published schema and its+// model.sha256 matches the synthetic GLB bytes (the harness's step-2 round-trip).++import { describe, expect, it } from 'vitest';++import {+ inlineParityProblems,+ buildSyntheticGlb,+ sha256hex,+ buildCard,+ getCardValidator,+ ERC8004_TYPE,+ THREEWS_CARD_TYPE,+} from '../scripts/onchain-smoke.mjs';+import { REGISTRY_DEPLOYMENTS } from '../src/erc8004/abi.js';++describe('onchain-smoke · address parity (step 1)', () => {+ it('the three registry sources agree today', () => {+ expect(inlineParityProblems()).toEqual([]);+ });++ it('detects an injected address drift', () => {+ const chainId = 84532; // Base Sepolia+ const original = REGISTRY_DEPLOYMENTS[chainId].identityRegistry;+ REGISTRY_DEPLOYMENTS[chainId].identityRegistry =+ '0x000000000000000000000000000000000000dEaD';+ try {+ const problems = inlineParityProblems();+ expect(problems.length).toBeGreaterThan(0);+ expect(problems.join(' ')).toContain('identityRegistry');+ } finally {+ REGISTRY_DEPLOYMENTS[chainId].identityRegistry = original;+ }+ // Restored — parity clean again.+ expect(inlineParityProblems()).toEqual([]);+ });+});++describe('onchain-smoke · synthetic GLB', () => {+ it('builds a structurally valid GLB container with a stable sha256', () => {+ const glb = buildSyntheticGlb();+ expect(glb.readUInt32LE(0)).toBe(0x46546c67); // magic 'glTF'+ expect(glb.readUInt32LE(4)).toBe(2); // version+ expect(glb.readUInt32LE(8)).toBe(glb.length); // declared total length matches+ expect(glb.readUInt32LE(16)).toBe(0x4e4f534a); // first chunk type 'JSON'+ // Deterministic bytes ⇒ deterministic hash (no Date/random in the fixture).+ expect(sha256hex(glb)).toBe(sha256hex(buildSyntheticGlb()));+ expect(sha256hex(glb)).toMatch(/^[a-f0-9]{64}$/);+ });+});++describe('onchain-smoke · 3D Agent Card (step 2)', () => {+ it('builds a card that validates against 3d-agent-card.schema.json with a matching model.sha256', async () => {+ const glb = buildSyntheticGlb();+ const glbSha = sha256hex(glb);+ const glbUrl = `data:model/gltf-binary;base64,${glb.toString('base64')}`;+ const card = buildCard({+ name: 'three.ws smoke agent',+ description: 'Synthetic agent for the schema round-trip test.',+ glbUrl,+ agentId: 1,+ chainId: 84532,+ registryAddr: REGISTRY_DEPLOYMENTS[84532].identityRegistry,+ glbSha,+ glbSize: glb.length,+ });++ const validate = await getCardValidator();+ const ok = validate(card);+ if (!ok) throw new Error(JSON.stringify(validate.errors, null, 2));+ expect(ok).toBe(true);++ expect(card.model.sha256).toBe(glbSha);+ expect(card.type).toEqual([ERC8004_TYPE, THREEWS_CARD_TYPE]);+ expect(card.registrations[0].agentRegistry).toMatch(/^eip155:84532:0x[a-fA-F0-9]{40}$/);+ });+});diff --git a/tests/pump-alert-eval.test.js b/tests/pump-alert-eval.test.jsnew file mode 100644index 000000000..a7c3c09ae--- /dev/null+++ b/tests/pump-alert-eval.test.js@@ -0,0 +1,210 @@+import { describe, it, expect } from 'vitest';+import {+ cooldownElapsed,+ gradMatchesRule,+ newMintMatchesRule,+ isWhaleBuy,+ evaluatePriceRule,+ buildGraduationPayload,+ buildNewMintPayload,+ buildWhalePayload,+ buildPricePayload,+ formatAlertSummary,+ deriveRuleLabel,+ MINT_TARGETED_KINDS,+ AGENT_TARGETED_KINDS,+ THRESHOLD_KINDS,+} from '../api/_lib/pump-alert-eval.js';++const baseRule = (over = {}) => ({+ id: 'rule-1',+ user_id: 'user-1',+ kind: 'graduation',+ target_mint: null,+ target_agent: null,+ threshold: null,+ deliver_in_app: true,+ cooldown_seconds: 300,+ enabled: true,+ ...over,+});++describe('cooldownElapsed', () => {+ it('returns true when never fired', () => {+ expect(cooldownElapsed(null, 300)).toBe(true);+ expect(cooldownElapsed(undefined, 300)).toBe(true);+ });+ it('returns false inside the cooldown window', () => {+ const now = 1_000_000_000_000;+ const lastFired = new Date(now - 60_000); // 60s ago+ expect(cooldownElapsed(lastFired, 300, now)).toBe(false);+ });+ it('returns true once the window has elapsed', () => {+ const now = 1_000_000_000_000;+ const lastFired = new Date(now - 301_000); // 301s ago+ expect(cooldownElapsed(lastFired, 300, now)).toBe(true);+ });+ it('treats an unparseable timestamp as elapsed (fail open)', () => {+ expect(cooldownElapsed('not-a-date', 300)).toBe(true);+ });+});++describe('gradMatchesRule', () => {+ it('global rule matches any graduation', () => {+ expect(gradMatchesRule(baseRule(), { mint: 'MINT_A' })).toBe(true);+ });+ it('mint-scoped rule matches only its mint', () => {+ const r = baseRule({ target_mint: 'MINT_A' });+ expect(gradMatchesRule(r, { mint: 'MINT_A' })).toBe(true);+ expect(gradMatchesRule(r, { mint: 'MINT_B' })).toBe(false);+ });+ it('agent-scoped rule matches only the agent’s mints', () => {+ const r = baseRule({ target_agent: 'agent-9' });+ const agentMints = new Set(['MINT_A', 'MINT_C']);+ expect(gradMatchesRule(r, { mint: 'MINT_A' }, { agentMints })).toBe(true);+ expect(gradMatchesRule(r, { mint: 'MINT_B' }, { agentMints })).toBe(false);+ expect(gradMatchesRule(r, { mint: 'MINT_A' }, {})).toBe(false); // no set → no match+ });+ it('rejects non-graduation kinds and missing mints', () => {+ expect(gradMatchesRule(baseRule({ kind: 'whale_buy' }), { mint: 'X' })).toBe(false);+ expect(gradMatchesRule(baseRule(), {})).toBe(false);+ });+});++describe('newMintMatchesRule', () => {+ const r = baseRule({ kind: 'new_mint', target_agent: 'agent-9' });+ it('matches the target agent’s new mint', () => {+ expect(newMintMatchesRule(r, { agent_id: 'agent-9', mint: 'MINT_A' })).toBe(true);+ });+ it('ignores other agents and requires a target', () => {+ expect(newMintMatchesRule(r, { agent_id: 'agent-1' })).toBe(false);+ expect(newMintMatchesRule(baseRule({ kind: 'new_mint' }), { agent_id: 'agent-9' })).toBe(false);+ });+});++describe('isWhaleBuy', () => {+ const r = baseRule({ kind: 'whale_buy', target_mint: 'MINT_A', threshold: 5 });+ it('fires on a buy at or above the SOL threshold for the right mint', () => {+ expect(isWhaleBuy(r, { mint: 'MINT_A', is_buy: true, sol_amount: 5 })).toBe(true);+ expect(isWhaleBuy(r, { mint: 'MINT_A', is_buy: true, sol_amount: 12.3 })).toBe(true);+ });+ it('ignores sells, small buys, and other mints', () => {+ expect(isWhaleBuy(r, { mint: 'MINT_A', is_buy: false, sol_amount: 50 })).toBe(false);+ expect(isWhaleBuy(r, { mint: 'MINT_A', is_buy: true, sol_amount: 4.99 })).toBe(false);+ expect(isWhaleBuy(r, { mint: 'MINT_B', is_buy: true, sol_amount: 50 })).toBe(false);+ });+ it('requires a positive threshold', () => {+ const bad = baseRule({ kind: 'whale_buy', target_mint: 'MINT_A', threshold: 0 });+ expect(isWhaleBuy(bad, { mint: 'MINT_A', is_buy: true, sol_amount: 100 })).toBe(false);+ });+});++describe('evaluatePriceRule (edge-triggered)', () => {+ it('price_above fires on the up-crossing, then stays quiet while held', () => {+ const r = baseRule({ kind: 'price_above', target_mint: 'M', threshold: 1000 });+ // First observation already above → fire, arm 'over'.+ const a = evaluatePriceRule(r, 1500, {});+ expect(a.fire).toBe(true);+ expect(a.nextState.side).toBe('over');+ // Still above → no re-fire.+ const b = evaluatePriceRule(r, 1600, a.nextState);+ expect(b.fire).toBe(false);+ // Drops below → re-arm 'under', no fire.+ const c = evaluatePriceRule(r, 900, b.nextState);+ expect(c.fire).toBe(false);+ expect(c.nextState.side).toBe('under');+ // Crosses up again → fire.+ const d = evaluatePriceRule(r, 1100, c.nextState);+ expect(d.fire).toBe(true);+ });+ it('price_below fires on the down-crossing', () => {+ const r = baseRule({ kind: 'price_below', target_mint: 'M', threshold: 1000 });+ const a = evaluatePriceRule(r, 800, {});+ expect(a.fire).toBe(true);+ expect(a.nextState.side).toBe('under');+ const b = evaluatePriceRule(r, 700, a.nextState);+ expect(b.fire).toBe(false);+ const c = evaluatePriceRule(r, 1200, b.nextState);+ expect(c.fire).toBe(false);+ expect(c.nextState.side).toBe('over');+ const d = evaluatePriceRule(r, 950, c.nextState);+ expect(d.fire).toBe(true);+ });+ it('does not fire without a usable price and preserves prior state', () => {+ const r = baseRule({ kind: 'price_above', target_mint: 'M', threshold: 1000 });+ const res = evaluatePriceRule(r, null, { side: 'over' });+ expect(res.fire).toBe(false);+ expect(res.nextState.side).toBe('over');+ });+});++describe('payload builders', () => {+ it('graduation payload carries the tx signature as the dedupe key', () => {+ const p = buildGraduationPayload(baseRule(), {+ tx_signature: 'SIG1',+ mint: 'M',+ name: 'Name',+ symbol: 'SYM',+ amount_sol: '12.5',+ market_cap_usd: '90000',+ seen_at: '2026-06-15T00:00:00.000Z',+ });+ expect(p.kind).toBe('graduation');+ expect(p.event_id).toBe('SIG1');+ expect(p.amount_sol).toBe(12.5);+ expect(p.market_cap_usd).toBe(90000);+ });+ it('new_mint payload keys on the mint', () => {+ const p = buildNewMintPayload(baseRule({ kind: 'new_mint', target_agent: 'A' }), { mint: 'M', agent_id: 'A' });+ expect(p.event_id).toBe('M');+ expect(p.agent_id).toBe('A');+ });+ it('whale payload keys on the trade signature', () => {+ const p = buildWhalePayload(+ baseRule({ kind: 'whale_buy', target_mint: 'M', threshold: 5 }),+ { mint: 'M', symbol: 'S' },+ { signature: 'TSIG', sol_amount: 9, sol_value_usd: 1800, buyer: 'B' },+ );+ expect(p.event_id).toBe('TSIG');+ expect(p.amount_sol).toBe(9);+ expect(p.amount_usd).toBe(1800);+ });+ it('price payload buckets the dedupe key by hour', () => {+ const p = buildPricePayload(baseRule({ kind: 'price_above', target_mint: 'M', threshold: 1000 }), {+ mint: 'M',+ market_cap_usd: 1500,+ });+ expect(p.kind).toBe('price_above');+ expect(p.event_id.startsWith('price_above:M:')).toBe(true);+ expect(p.threshold_usd).toBe(1000);+ });+});++describe('formatAlertSummary', () => {+ it('renders a readable line per kind', () => {+ expect(formatAlertSummary({ kind: 'graduation', symbol: 'ABC', market_cap_usd: 90000 })).toContain('graduated');+ expect(formatAlertSummary({ kind: 'whale_buy', symbol: 'ABC', amount_sol: 12 })).toContain('Whale');+ expect(formatAlertSummary({ kind: 'price_above', symbol: 'ABC', threshold_usd: 1000, market_cap_usd: 1500 })).toContain('above');+ expect(formatAlertSummary({ kind: 'new_mint', symbol: 'ABC' })).toContain('launched');+ });+ it('falls back to a shortened mint when no symbol/name', () => {+ const s = formatAlertSummary({ kind: 'graduation', mint: 'ABCD1234EFGH5678' });+ expect(s).toContain('ABCD');+ });+});++describe('deriveRuleLabel', () => {+ it('produces a sensible default label per kind', () => {+ expect(deriveRuleLabel(baseRule())).toContain('all tokens');+ expect(deriveRuleLabel(baseRule({ kind: 'whale_buy', target_mint: 'ABCD1234EFGH5678', threshold: 5 }))).toContain('Whale');+ expect(deriveRuleLabel(baseRule({ kind: 'price_below', target_mint: 'ABCD1234EFGH5678', threshold: 1000 }))).toContain('below');+ });+});++describe('kind classification constants', () => {+ it('partitions kinds correctly', () => {+ expect(MINT_TARGETED_KINDS).toEqual(['price_above', 'price_below', 'whale_buy']);+ expect(AGENT_TARGETED_KINDS).toEqual(['new_mint']);+ expect(THRESHOLD_KINDS).toEqual(['price_above', 'price_below', 'whale_buy']);+ });+});diff --git a/tests/pump-alert-rules-validation.test.js b/tests/pump-alert-rules-validation.test.jsnew file mode 100644index 000000000..1e5c125db--- /dev/null+++ b/tests/pump-alert-rules-validation.test.js@@ -0,0 +1,158 @@+import { describe, it, expect } from 'vitest';+import {+ createRuleSchema,+ updateRuleSchema,+ validateUpdate,+ normalizeForKind,+ serializeRule,+} from '../api/alerts/_rules.js';++// $THREE — the only coin the platform references — used here as a valid base58+// mint fixture for validation tests.+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const AGENT = '11111111-2222-4333-8444-555555555555';++describe('createRuleSchema', () => {+ it('accepts a valid global graduation rule', () => {+ const r = createRuleSchema.safeParse({ kind: 'graduation' });+ expect(r.success).toBe(true);+ });++ it('requires a target_mint + positive threshold for price rules', () => {+ expect(createRuleSchema.safeParse({ kind: 'price_above' }).success).toBe(false);+ expect(createRuleSchema.safeParse({ kind: 'price_above', target_mint: MINT }).success).toBe(false);+ expect(+ createRuleSchema.safeParse({ kind: 'price_above', target_mint: MINT, threshold: 50000 }).success,+ ).toBe(true);+ });++ it('requires a target_agent for new_mint and forbids a mint', () => {+ expect(createRuleSchema.safeParse({ kind: 'new_mint' }).success).toBe(false);+ expect(createRuleSchema.safeParse({ kind: 'new_mint', target_agent: AGENT }).success).toBe(true);+ expect(+ createRuleSchema.safeParse({ kind: 'new_mint', target_agent: AGENT, target_mint: MINT }).success,+ ).toBe(false);+ });++ it('rejects whale_buy without mint or threshold', () => {+ expect(createRuleSchema.safeParse({ kind: 'whale_buy', target_mint: MINT }).success).toBe(false);+ expect(+ createRuleSchema.safeParse({ kind: 'whale_buy', target_mint: MINT, threshold: 10 }).success,+ ).toBe(true);+ });++ it('rejects non-https webhook URLs', () => {+ expect(+ createRuleSchema.safeParse({ kind: 'graduation', webhook_url: 'http://evil.example' }).success,+ ).toBe(false);+ expect(+ createRuleSchema.safeParse({ kind: 'graduation', webhook_url: 'https://ok.example/hook' }).success,+ ).toBe(true);+ });++ it('requires at least one delivery channel', () => {+ expect(createRuleSchema.safeParse({ kind: 'graduation', deliver_in_app: false }).success).toBe(false);+ expect(+ createRuleSchema.safeParse({ kind: 'graduation', deliver_in_app: false, telegram_chat: '12345' }).success,+ ).toBe(true);+ });++ it('validates telegram chat format', () => {+ expect(+ createRuleSchema.safeParse({ kind: 'graduation', deliver_in_app: false, telegram_chat: 'not a chat!!' }).success,+ ).toBe(false);+ expect(+ createRuleSchema.safeParse({ kind: 'graduation', deliver_in_app: false, telegram_chat: '-1001234567890' }).success,+ ).toBe(true);+ expect(+ createRuleSchema.safeParse({ kind: 'graduation', deliver_in_app: false, telegram_chat: '@mychannel' }).success,+ ).toBe(true);+ });++ it('clamps cooldown to the allowed range', () => {+ expect(createRuleSchema.safeParse({ kind: 'graduation', cooldown_seconds: 1 }).success).toBe(false);+ expect(createRuleSchema.safeParse({ kind: 'graduation', cooldown_seconds: 100000 }).success).toBe(false);+ expect(createRuleSchema.safeParse({ kind: 'graduation', cooldown_seconds: 600 }).success).toBe(true);+ });+});++describe('normalizeForKind', () => {+ it('nulls out threshold + agent for graduation; defaults delivery', () => {+ const out = normalizeForKind({ kind: 'graduation', target_mint: MINT, threshold: 5, target_agent: null });+ expect(out.threshold).toBe(null);+ expect(out.target_mint).toBe(MINT); // graduation may keep a mint scope+ expect(out.deliver_in_app).toBe(true);+ expect(out.cooldown_seconds).toBe(300);+ expect(out.enabled).toBe(true);+ });+ it('drops a stray mint when normalizing a new_mint rule', () => {+ const out = normalizeForKind({ kind: 'new_mint', target_agent: AGENT, target_mint: MINT });+ expect(out.target_mint).toBe(null);+ expect(out.target_agent).toBe(AGENT);+ });+});++describe('validateUpdate (merge + re-validate)', () => {+ const current = {+ kind: 'price_above',+ target_mint: MINT,+ target_agent: null,+ threshold: 50000,+ deliver_in_app: true,+ webhook_url: null,+ telegram_chat: null,+ cooldown_seconds: 300,+ enabled: true,+ label: null,+ };++ it('allows a partial threshold update', () => {+ const r = validateUpdate(current, { threshold: 75000 });+ expect(r.ok).toBe(true);+ expect(r.value.threshold).toBe(75000);+ expect(r.value.target_mint).toBe(MINT);+ });++ it('rejects an update that drops a required field', () => {+ const r = validateUpdate(current, { target_mint: null });+ expect(r.ok).toBe(false);+ });++ it('re-validates when kind changes and clears incompatible targets', () => {+ const r = validateUpdate(current, { kind: 'new_mint', target_agent: AGENT });+ expect(r.ok).toBe(true);+ expect(r.value.target_mint).toBe(null);+ expect(r.value.threshold).toBe(null);+ });++ it('rejects disabling every delivery channel', () => {+ const r = validateUpdate(current, { deliver_in_app: false });+ expect(r.ok).toBe(false);+ });+});++describe('serializeRule', () => {+ it('derives a display label but keeps the raw label separate', () => {+ const row = {+ id: 'r1',+ kind: 'graduation',+ target_mint: null,+ target_agent: null,+ threshold: null,+ deliver_in_app: true,+ webhook_url: null,+ webhook_secret: null,+ telegram_chat: null,+ cooldown_seconds: 300,+ enabled: true,+ label: null,+ created_at: '2026-06-15T00:00:00Z',+ updated_at: '2026-06-15T00:00:00Z',+ };+ const s = serializeRule(row);+ expect(s.label).toBe(null);+ expect(s.label_display).toContain('Graduations');+ expect(s.recent_failures).toBe(0);+ expect(Array.isArray(s.recent_deliveries)).toBe(true);+ });+});diff --git a/tests/pump-channel-feed.test.js b/tests/pump-channel-feed.test.jsindex dee503eca..4a6d250b3 100644--- a/tests/pump-channel-feed.test.js+++ b/tests/pump-channel-feed.test.js@@ -5,11 +5,13 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';const mintsMock = vi.fn();const whalesMock = vi.fn();const claimsMock = vi.fn();+const signalsMock = vi.fn();vi.mock('../api/_lib/channel-feed-sources.js', () => ({getMints: (...a) => mintsMock(...a),getWhales: (...a) => whalesMock(...a),getClaims: (...a) => claimsMock(...a),+ getSignals: (...a) => signalsMock(...a),}));vi.mock('../api/_lib/rate-limit.js', () => ({@@ -52,9 +54,11 @@ describe('channel-feed endpoint', () => {mintsMock.mockReset();whalesMock.mockReset();claimsMock.mockReset();+ signalsMock.mockReset();mintsMock.mockResolvedValue([]);whalesMock.mockResolvedValue([]);claimsMock.mockResolvedValue([]);+ signalsMock.mockResolvedValue([]);});it('returns 200 with items array', async () => {@@ -166,4 +170,44 @@ describe('channel-feed endpoint', () => {const body = JSON.parse(res.body);expect(body.items).toEqual([]);});++ it('includes agent-attributed signals in the default feed', async () => {+ signalsMock.mockResolvedValueOnce([+ {+ signature: 'signal:gradtx:graduation',+ tx_signature: 'gradtx',+ mint: 'GM',+ signal_kind: 'graduation',+ weight: 0.3,+ agent_name: 'Atlas',+ summary: 'Atlas — graduated a token (+0.3)',+ timestamp: 5000,+ },+ ]);++ const res = mockRes();+ await handler(mockReq(), res);++ const body = JSON.parse(res.body);+ const sig = body.items.find((i) => i.kind === 'signal');+ expect(sig).toBeTruthy();+ expect(sig.signature).toBe('signal:gradtx:graduation');+ expect(sig.signal_kind).toBe('graduation');+ });++ it('kinds=mint excludes the signal lane', async () => {+ mintsMock.mockResolvedValueOnce([{ signature: 'mint1', mint: 'M1', timestamp: 100 }]);+ signalsMock.mockResolvedValueOnce([+ { signature: 'signal:x:launch', tx_signature: 'x', signal_kind: 'launch', timestamp: 200 },+ ]);++ const res = mockRes();+ await handler(mockReq('?kinds=mint'), res);++ const body = JSON.parse(res.body);+ expect(body.items.some((i) => i.kind === 'signal')).toBe(false);+ expect(body.items.some((i) => i.kind === 'mint')).toBe(true);+ // signal source must not even be queried when filtered out+ expect(signalsMock).not.toHaveBeenCalled();+ });});diff --git a/tests/pumpfun-signals.test.js b/tests/pumpfun-signals.test.jsindex 706a7533e..af9fec501 100644--- a/tests/pumpfun-signals.test.js+++ b/tests/pumpfun-signals.test.js@@ -1,18 +1,33 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, beforeEach, vi } from 'vitest';-const sqlMock = vi.fn();-vi.mock('../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));+// ── hoisted mocks ─────────────────────────────────────────────────────────────+// vi.mock factories are hoisted above imports, so the doubles they reference must+// be created with vi.hoisted().+const h = vi.hoisted(() => ({+ recentClaims: vi.fn(),+ graduations: vi.fn(),+ getClaims: vi.fn(),+ getWhales: vi.fn(),+ getMints: vi.fn(),+ getSignals: vi.fn(),+ sql: vi.fn(),+ state: { botEnabled: true },+}));-const recentClaimsMock = vi.fn();-const graduationsMock = vi.fn();+vi.mock('../api/_lib/db.js', () => ({ sql: (...a) => h.sql(...a) }));vi.mock('../api/_lib/pumpfun-mcp.js', () => ({pumpfunMcp: {- recentClaims: (...a) => recentClaimsMock(...a),- graduations: (...a) => graduationsMock(...a),+ recentClaims: (...a) => h.recentClaims(...a),+ graduations: (...a) => h.graduations(...a),},- pumpfunBotEnabled: () => true,+ pumpfunBotEnabled: () => h.state.botEnabled,+}));+vi.mock('../api/_lib/channel-feed-sources.js', () => ({+ getClaims: (...a) => h.getClaims(...a),+ getWhales: (...a) => h.getWhales(...a),+ getMints: (...a) => h.getMints(...a),+ getSignals: (...a) => h.getSignals(...a),}));-vi.mock('../api/_lib/env.js', () => ({env: { APP_ORIGIN: 'http://test', ISSUER: 'http://test', MCP_RESOURCE: 'http://test' },}));@@ -21,76 +36,172 @@ const { default: dispatcher } = await import('../api/cron/[name].js');const handler = (req, res) =>dispatcher({ ...req, query: { ...(req.query || {}), name: 'pumpfun-signals' } }, res);+// ── faithful in-memory Postgres double ────────────────────────────────────────+// The previous test returned [{id:1}] for every sql call, which masked the+// tx_signature-unique bug. This double enforces the real unique(tx_signature,+// kind) constraint and persists cursor state across calls so cursor behaviour is+// actually exercised.+let cursorState; // Map<source, last_seen_ms>+let insertedKeys; // Set<"tx:kind">+let insertedRows; // [{ wallet, agent_asset, kind, weight, tx_signature }]+let cursorWrites; // [{ source, last_seen_ms, last_signature }]+let linkedRows; // rows returned by the user_wallets → agent_identities lookup++function installSqlRouter() {+ h.sql.mockImplementation((strings, ...vals) => {+ const q = Array.isArray(strings) ? strings.join(' ? ') : String(strings);++ if (/from pumpfun_signals_cursor/.test(q)) {+ return Promise.resolve(+ [...cursorState.entries()].map(([source, last_seen_ms]) => ({ source, last_seen_ms })),+ );+ }+ if (/into pumpfun_signals_cursor/.test(q)) {+ const [source, ms, sig] = vals;+ cursorState.set(source, Math.max(cursorState.get(source) ?? 0, Number(ms) || 0));+ cursorWrites.push({ source, last_seen_ms: Number(ms) || 0, last_signature: sig ?? null });+ return Promise.resolve([]);+ }+ if (/from user_wallets/.test(q)) {+ return Promise.resolve(linkedRows);+ }+ if (/into pumpfun_signals\b/.test(q)) {+ // values: (wallet, agent_asset, kind, weight, payload, tx_signature)+ const [wallet, agent_asset, kind, weight, , tx_signature] = vals;+ const key = `${tx_signature}:${kind}`;+ if (insertedKeys.has(key)) return Promise.resolve([]); // unique(tx_signature, kind)+ insertedKeys.add(key);+ insertedRows.push({ wallet, agent_asset, kind, weight, tx_signature });+ return Promise.resolve([{ id: insertedKeys.size }]);+ }+ return Promise.resolve([]);+ });+}+function mockRes() {- const res = {+ return {statusCode: 200,headers: {},body: null,- setHeader(k, v) {- this.headers[k.toLowerCase()] = v;- },- getHeader(k) {- return this.headers[k.toLowerCase()];- },- end(b) {- this.body = b;- },+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(b) { this.body = b; },};- return res;+}++const SECRET = 'topsecret';+async function run() {+ process.env.CRON_SECRET = SECRET;+ const req = { headers: { authorization: `Bearer ${SECRET}` }, method: 'POST' };+ const res = mockRes();+ await handler(req, res);+ return { res, body: JSON.parse(res.body) };}describe('pumpfun-signals cron', () => {beforeEach(() => {- sqlMock.mockReset();- recentClaimsMock.mockReset();- graduationsMock.mockReset();+ cursorState = new Map();+ insertedKeys = new Set();+ insertedRows = [];+ cursorWrites = [];+ linkedRows = [];+ h.state.botEnabled = true;+ h.recentClaims.mockReset().mockResolvedValue({ ok: true, data: [] });+ h.graduations.mockReset().mockResolvedValue({ ok: true, data: [] });+ h.getClaims.mockReset().mockResolvedValue([]);+ h.getWhales.mockReset().mockResolvedValue([]);+ h.getMints.mockReset().mockResolvedValue([]);+ h.getSignals.mockReset().mockResolvedValue([]);+ installSqlRouter();delete process.env.CRON_SECRET;});- it('writes typed signals only for linked wallets', async () => {- recentClaimsMock.mockResolvedValueOnce({+ it('writes typed signals only for linked wallets, one row per (tx, kind)', async () => {+ h.recentClaims.mockResolvedValue({ok: true,data: [{- tx_signature: 'sig1',- claimer: 'WALLET_A',- first_time_claim: true,- tier: 'influencer',+ tx_signature: 'sig1', signature: 'sig1', timestamp: 1000,+ claimer: 'WALLET_A', first_time_claim: true, tier: 'influencer',github_account_age_days: 5,},- {- tx_signature: 'sig2',- claimer: 'WALLET_UNKNOWN',- first_time_claim: true,- },+ { tx_signature: 'sig2', signature: 'sig2', timestamp: 1001, claimer: 'WALLET_UNKNOWN', first_time_claim: true },],});- graduationsMock.mockResolvedValueOnce({ ok: true, data: [] });+ linkedRows = [{ address: 'WALLET_A', agent_asset: 'AGENT_A' }];- // 1st sql: linked-wallet lookup → only WALLET_A is linked.- sqlMock.mockResolvedValueOnce([- { address: 'WALLET_A', agent_asset: 'AGENT_A' },- ]);- // Subsequent sql calls: insert returning [{id}] for each insert.- sqlMock.mockResolvedValue([{ id: 1 }]);-- // Vercel cron sends `Authorization: Bearer $CRON_SECRET`; the handler now- // requires a valid secret unconditionally (the `x-vercel-cron` header is no- // longer trusted as an auth bypass).- process.env.CRON_SECRET = 'topsecret';- const req = { headers: { authorization: 'Bearer topsecret' }, method: 'POST' };- const res = mockRes();- await handler(req, res);+ const { body } = await run();- const body = JSON.parse(res.body);- expect(body.claims).toBe(2);- expect(body.skipped).toBeGreaterThanOrEqual(1); // WALLET_UNKNOWN skipped- // WALLET_A: first_claim + influencer + new_account = 3 inserts+ expect(body.sources.claims).toBe(2);+ expect(body.skipped_unlinked).toBeGreaterThanOrEqual(1); // WALLET_UNKNOWN+ // WALLET_A: first_claim + influencer + new_account — three DISTINCT rows+ // for one tx, which the old single-column tx_signature unique forbade.expect(body.inserted).toBe(3);+ expect(insertedRows.map((r) => r.kind).sort()).toEqual(['first_claim', 'influencer', 'new_account']);+ expect(insertedRows.every((r) => r.agent_asset === 'AGENT_A')).toBe(true);+ });++ it('cursor skips already-seen events on the next run', async () => {+ h.recentClaims.mockResolvedValue({+ ok: true,+ data: [+ { tx_signature: 'c1', signature: 'c1', timestamp: 100, claimer: 'W', first_time_claim: true },+ { tx_signature: 'c2', signature: 'c2', timestamp: 200, claimer: 'W', first_time_claim: true },+ ],+ });+ linkedRows = [{ address: 'W', agent_asset: 'A' }];++ const first = await run();+ expect(first.body.inserted).toBe(2);+ expect(first.body.skipped_by_cursor).toBe(0);+ // cursor advanced to the newest event (200s → 200000ms) for the claims lane+ expect(cursorState.get('claims')).toBe(200000);++ const second = await run();+ // Nothing new persists: c1 is strictly older than the cursor (skipped), c2+ // is at the boundary and collides on (tx, kind).+ expect(second.body.inserted).toBe(0);+ expect(second.body.skipped_by_cursor).toBeGreaterThanOrEqual(1);+ });++ it('emits whale_buy and launch signals from the redis lanes', async () => {+ h.getWhales.mockResolvedValue([+ { signature: 'w1', timestamp: 10, mint: 'M1', amount_sol: 12.5, buyer: 'WB' },+ ]);+ h.getMints.mockResolvedValue([+ { signature: 'm1', timestamp: 11, mint: 'M2', name: 'Tok', symbol: 'TK', creator: 'WC' },+ ]);+ linkedRows = [+ { address: 'WB', agent_asset: 'AB' },+ { address: 'WC', agent_asset: 'AC' },+ ];++ const { body } = await run();++ expect(body.inserted).toBe(2);+ const byKind = Object.fromEntries(insertedRows.map((r) => [r.kind, r]));+ expect(byKind.whale_buy?.agent_asset).toBe('AB');+ expect(byKind.launch?.agent_asset).toBe('AC');+ });++ it('runs without the upstream bot — graduations still emit, claims are not fetched', async () => {+ h.state.botEnabled = false;+ h.graduations.mockResolvedValue({+ ok: true,+ data: [{ tx_signature: 'g1', signature: 'g1', timestamp: 7, mint: 'GM', symbol: 'GS', name: 'GN', creator: 'GW' }],+ });+ linkedRows = [{ address: 'GW', agent_asset: 'GA' }];++ const { body } = await run();++ expect(h.recentClaims).not.toHaveBeenCalled();+ expect(body.bot).toBe(false);+ expect(body.inserted).toBe(1);+ expect(insertedRows[0]).toMatchObject({ kind: 'graduation', agent_asset: 'GA' });});it('rejects without cron secret when CRON_SECRET set', async () => {- process.env.CRON_SECRET = 'topsecret';+ process.env.CRON_SECRET = SECRET;const req = { headers: {}, method: 'POST' };const res = mockRes();await handler(req, res);diff --git a/tests/solana-parity.test.js b/tests/solana-parity.test.jsnew file mode 100644index 000000000..62b59b10e--- /dev/null+++ b/tests/solana-parity.test.js@@ -0,0 +1,66 @@+// Guards the Solana address surface the platform actually runs on:+// 1. The $THREE mint (the one and only coin, CLAUDE.md) hardcoded across ~25+// source files must never drift from the canonical CA, and no OTHER+// pump.fun mint may be baked into first-party source.+// 2. Pump program IDs and well-known Solana programs/mints (canonical home:+// api/_lib/solana/programs.js) must agree wherever they are re-declared.+//+// The same checks gate the Vercel build (scripts/build-vercel.mjs phase 1,+// `verify:solana`); running them here means `npm test` catches a drift or a+// leaked second coin before a push. The live on-chain probe is exercised by the+// CLI, not here — unit tests stay offline and deterministic.++import { describe, it, expect, beforeAll } from 'vitest';+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { loadCanonical, scanForDrift, THREE_MINT } from '../scripts/verify-solana-parity.mjs';++let registry;+beforeAll(async () => {+ // Throws if api/_lib/env.js or api/_lib/solana/programs.js drift from the+ // constants baked into the guard — a source-of-truth disagreement.+ registry = await loadCanonical();+});++describe('solana parity (real repo)', () => {+ it('canonical source-of-truth files agree (loadCanonical resolves)', () => {+ expect(registry.find((e) => e.address === THREE_MINT)).toBeTruthy();+ });++ it('has no address drift or non-$THREE coin across first-party source', async () => {+ expect(await scanForDrift(registry)).toEqual([]);+ });+});++describe('drift detection logic', () => {+ const withTempFile = async (contents, fn) => {+ const dir = mkdtempSync(join(tmpdir(), 'sol-parity-'));+ try {+ writeFileSync(join(dir, 'subject.js'), contents);+ return await fn(dir);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ };++ it('flags a drifted program ID and a non-$THREE pump mint', async () => {+ const problems = await withTempFile(+ `const PUMP_PROGRAM_ID = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6X';\n` ++ `const OTHER_COIN = 'ABCdefGHJKLMNPQRstuvwxyz123456789abcdefgpump';\n`,+ (dir) => scanForDrift(registry, { root: dir, files: ['subject.js'] }),+ );+ expect(problems.map((p) => p.type).sort()).toEqual(['const-drift', 'rogue-coin']);+ expect(problems.every((p) => p.line > 0 && p.detail)).toBe(true);+ });++ it('does not flag correct canonical values or devnet variants', async () => {+ const problems = await withTempFile(+ `const PUMP_PROGRAM_ID = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';\n` ++ `const THREE_MINT = '${THREE_MINT}';\n` ++ `const USDC_MINT_DEVNET = '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU';\n`,+ (dir) => scanForDrift(registry, { root: dir, files: ['subject.js'] }),+ );+ expect(problems).toEqual([]);+ });+});diff --git a/vercel.json b/vercel.jsonindex 21bc00c51..99c6f406b 100644--- a/vercel.json+++ b/vercel.json@@ -355,6 +355,14 @@"src": "/api/agents/solana-reputation-history","dest": "/api/agents/solana/[action]?action=reputation-history"},+ {+ "src": "/api/agents/solana-validate",+ "dest": "/api/agents/solana/[action]?action=validate"+ },+ {+ "src": "/api/agents/solana-validation",+ "dest": "/api/agents/solana/[action]?action=validation"+ },{"src": "/api/agents/([^/]+)/skills-pricing","dest": "/api/agents/[id]/skills-pricing?id=$1"