Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Add agent-sniper first-claim strategy, pump trading, rewards ledger migration

nirholasf27437c5a671
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bdc36bfc2..9a675beac 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Pose any avatar — a full motion library on the avatar page** — Every avatar page has a new Pose tab. Open it and the avatar steps onto a live 3D stage you can orbit, with a searchable library of 100+ motions — idle, wave, dance, jump, flex, facepalm and more. Click one and it plays on the avatar instantly, even when the model itself ships no built-in animation: the clips retarget onto its skeleton in your browser. A speed slider and a reset-to-idle control round out the transport. Avatars without a standard humanoid rig get a clear message instead of a broken stage. `[feature]`
- **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: a coin's look now tracks its market cap** — On the Pump Visualizer, market cap no longer just sizes a coin — it shapes its whole look. As a coin's cap climbs it shifts color from cool blue through purple to green and gold, grows a crystalline wireframe cage that gains facets at each tier, and spins and pulses with more energy. On the trending refresh, a coin that moved gets a clear signal: it flashes green and pops bigger when its cap rose, red and dips when it fell, and crossing into a higher or lower tier visibly upgrades or downgrades its shape and color. A new on-screen key in the corner maps each color and tier to its market-cap range so it all reads at a glance. (`/pump-visualizer`) `[feature]`
- **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]`
- **Refer friends with a 3D membership card** — Your account now has a Referrals page with a 3D, flippable membership card — your member number, referral count, and score on the front, a scannable QR for your invite link on the back. Tilt it with your cursor, flip it over, then share it: post to X or Telegram, copy your link, or download the card as an image. Anyone who signs up through your link is tied to you for life, and you earn 5% in USDC on everything they buy on three.ws. Sign-ups now carry your referral code through every login method — email and wallet alike — so credit always lands where it's due. (`/dashboard/referrals`) `[feature]`
diff --git a/api/_lib/migrations/2026-06-15-rewards-distributions.sql b/api/_lib/migrations/2026-06-15-rewards-distributions.sql
new file mode 100644
index 000000000..276d30c72
--- /dev/null
+++ b/api/_lib/migrations/2026-06-15-rewards-distributions.sql
@@ -0,0 +1,45 @@
+-- Migration: three_rewards_distributions — the holder-rewards (reflections) ledger.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 2026-06-15-rewards-distributions.sql
+-- Idempotent.
+--
+-- The $THREE economy NEVER burns. The `rewards` leg of every spend accrues in the
+-- rewards pool and is distributed pro-rata back to holders by the rewards cron
+-- (api/cron/rewards-distribute.js). This table is the PUBLIC, on-chain-verifiable
+-- record of every distribution run — the proof behind the "reflected to holders"
+-- figure on /three. Unlike a burn counter, every row here links to real transfers
+-- holders can verify on Solscan.
+--
+-- One row per distribution run. Stores only public facts (pool size, distributed
+-- amount, eligible holder count, optional batch tx signatures) — no secrets.
+
+begin;
+
+create table if not exists three_rewards_distributions (
+ id uuid primary key default gen_random_uuid(),
+ mint text not null,
+ -- The rewards pool wallet drained this run (verifiable on-chain).
+ pool_wallet text not null,
+ -- Pool balance at run time, what was actually distributed, and the dust
+ -- (sub-floor remainder) carried to the next run. All in token atomics.
+ pool_atomics numeric(40, 0) not null,
+ distributed_atomics numeric(40, 0) not null default 0,
+ dust_atomics numeric(40, 0) not null default 0,
+ -- How many holders were paid, and the eligible supply the split was over.
+ holder_count int not null default 0,
+ eligible_supply_atomics numeric(40, 0) not null default 0,
+ -- 'planned' (dry run, no signer), 'executing', 'completed', 'failed'.
+ status text not null default 'planned',
+ -- The batch transaction signatures, when executed on-chain (verifiable).
+ tx_signatures jsonb not null default '[]'::jsonb,
+ -- Free-form note (e.g. why a run was a dry run).
+ note text,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists three_rewards_distributions_created
+ on three_rewards_distributions (created_at desc);
+
+create index if not exists three_rewards_distributions_status
+ on three_rewards_distributions (status, created_at desc);
+
+commit;
diff --git a/api/_lib/migrations/20260615030000_sniper_first_claim.sql b/api/_lib/migrations/20260615030000_sniper_first_claim.sql
new file mode 100644
index 000000000..6ece4aee1
--- /dev/null
+++ b/api/_lib/migrations/20260615030000_sniper_first_claim.sql
@@ -0,0 +1,48 @@
+-- Migration: add the "first claim" trigger to the agent sniper.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260615030000_sniper_first_claim.sql
+-- Idempotent.
+--
+-- The original sniper fires on the PumpPortal NEW-MINT feed (trigger = 'new_mint').
+-- This adds a second trigger, 'first_claim': the sniper buys a creator's coin the
+-- first time that creator EVER pulls their accrued creator/delegated rewards out
+-- of the pump.fun fee vault — an irreversible, on-chain "the creator is live"
+-- signal. The agent-sniper worker (workers/agent-sniper) polls scanFirstClaims,
+-- scores each first claim against the new claim-specific filters below, waits the
+-- owner-set delay, then snipes from the agent's own wallet through the SAME
+-- executor / position-lifecycle path as a new-mint snipe.
+
+begin;
+
+alter table agent_sniper_strategies
+ -- which signal arms this strategy. Existing rows keep new-mint behaviour.
+ add column if not exists trigger text not null default 'new_mint'
+ check (trigger in ('new_mint', 'first_claim')),
+ -- how long to wait after the on-chain claim is observed before buying (ms).
+ -- 0 = buy as fast as the queue allows; let snipers front-run or let the dust
+ -- settle, the owner's call.
+ add column if not exists buy_delay_ms int not null default 0
+ check (buy_delay_ms >= 0 and buy_delay_ms <= 600000),
+ -- only fire when the first claim pulled at least this many lamports — a floor
+ -- that filters out dust claims and keeps the snipe to creators taking real fees.
+ add column if not exists min_claim_lamports numeric(40, 0),
+ -- optional upper bound (e.g. skip whales already cashing out hard).
+ add column if not exists max_claim_lamports numeric(40, 0),
+ -- ignore claims older than this many seconds when the worker first sees them,
+ -- so a restart / backfill can't snipe a stale claim. null = the worker default.
+ add column if not exists first_claim_max_age_seconds int
+ check (first_claim_max_age_seconds is null or first_claim_max_age_seconds > 0);
+
+-- The first-claim poll loop only wants armed first_claim strategies.
+create index if not exists agent_sniper_strategies_first_claim
+ on agent_sniper_strategies (enabled, kill_switch)
+ where enabled = true and kill_switch = false and trigger = 'first_claim';
+
+alter table agent_sniper_positions
+ -- which trigger opened this position (provenance for the ledger / arena UI).
+ add column if not exists entry_trigger text not null default 'new_mint'
+ check (entry_trigger in ('new_mint', 'first_claim')),
+ -- the on-chain reference that fired the entry: the claim tx signature for a
+ -- first_claim snipe (null for new_mint — the mint address is the reference).
+ add column if not exists trigger_ref text;
+
+commit;
diff --git a/api/_lib/pump-claims.js b/api/_lib/pump-claims.js
new file mode 100644
index 000000000..d413eb369
--- /dev/null
+++ b/api/_lib/pump-claims.js
@@ -0,0 +1,180 @@
+/**
+ * pump-claims.js
+ * --------------
+ * On-chain pump.fun creator-fee claim scanning. Shared by the HTTP route
+ * (`/api/pump/first-claims`) and the agent-sniper worker's first-claim trigger.
+ *
+ * A "first claim" is the first time a creator EVER pulls their accrued
+ * creator/delegated rewards out of the fee vault — an on-chain, irreversible
+ * signal that the creator is live and engaged with the coin. `scanFirstClaims`
+ * returns only creators whose earliest observed claim falls inside the window.
+ *
+ * Sources, in priority order:
+ * 1. PUMPFUN_BOT_URL (an indexer) when configured — fast, pre-aggregated.
+ * 2. Direct RPC scan of the pump program's recent signatures — always works,
+ * no indexer required.
+ */
+
+import bs58 from 'bs58';
+import { getConnection } from './pump.js';
+import { filterFirstClaims } from '../../src/pump/first-claims.js';
+
+const PUMP_PROGRAM = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';
+// Anchor discriminators for the three pump.fun fee-claim instruction variants.
+const CLAIM_DISCS = new Set(['e8f5c2eeeada3a59', '7a027f010ebf0caf', 'a537817004b3ca28']);
+// Pull a wider lookback so prior claimers are visible and "first" is real.
+const LOOKBACK_MULT = 8;
+// Quote mints that show up in a claim tx but are never the coin being claimed.
+const QUOTE_MINTS = new Set([
+ 'So11111111111111111111111111111111111111112', // wSOL
+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
+]);
+
+/**
+ * First-time claimers in [sinceTs, now]. Newest first, capped at `limit`.
+ * @param {{ sinceTs: number, limit: number }} opts
+ * @returns {Promise<Array<{creator,mint,signature,lamports,ts}>>}
+ */
+export async function scanFirstClaims({ sinceTs, limit }) {
+ const lim = Math.max(1, Math.min(50, limit));
+ const lookbackTs =
+ sinceTs - Math.max(3600, (Math.floor(Date.now() / 1000) - sinceTs) * LOOKBACK_MULT);
+ const allClaims = process.env.PUMPFUN_BOT_URL
+ ? await _fetchFromBot(lookbackTs, lim * LOOKBACK_MULT)
+ : await _fetchFromRpc(lookbackTs, lim * LOOKBACK_MULT);
+ return filterFirstClaims(allClaims, sinceTs, lim);
+}
+
+async function _fetchFromBot(lookbackTs, maxItems) {
+ const r = await _botCall('getFirstClaims', { sinceTs: lookbackTs, limit: maxItems });
+ if (r.ok) return _normalise(r.data);
+ const r2 = await _botCall('getRecentClaims', { limit: maxItems });
+ if (r2.ok) return _normalise(r2.data);
+ return [];
+}
+
+async function _botCall(tool, args) {
+ const url = process.env.PUMPFUN_BOT_URL;
+ if (!url) return { ok: false };
+ const headers = { 'content-type': 'application/json', accept: 'application/json' };
+ if (process.env.PUMPFUN_BOT_TOKEN)
+ headers.authorization = `Bearer ${process.env.PUMPFUN_BOT_TOKEN}`;
+ const ctrl = new AbortController();
+ const t = setTimeout(() => ctrl.abort(), 8000);
+ try {
+ const resp = await fetch(url.replace(/\/$/, ''), {
+ method: 'POST',
+ headers,
+ signal: ctrl.signal,
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: tool, arguments: args || {} },
+ }),
+ });
+ if (!resp.ok) return { ok: false, error: `bot ${resp.status}` };
+ const j = await resp.json();
+ if (j.error) return { ok: false, error: j.error.message || 'rpc error' };
+ const data = j.result?.structuredContent ?? j.result?.content ?? j.result;
+ return { ok: true, data: Array.isArray(data) ? data : (data?.items ?? []) };
+ } catch (err) {
+ return { ok: false, error: err?.message || 'fetch failed' };
+ } finally {
+ clearTimeout(t);
+ }
+}
+
+function _normalise(items) {
+ return (items || [])
+ .map((x) => ({
+ creator: String(x.claimerWallet || x.creator || x.wallet || ''),
+ mint: String(x.tokenMint || x.mint || ''),
+ signature: String(x.txSignature || x.tx_signature || x.signature || ''),
+ lamports: Number(x.amountLamports || x.lamports || 0),
+ ts: Number(x.timestamp || x.ts || 0),
+ }))
+ .filter((x) => x.creator && x.signature && x.ts > 0);
+}
+
+async function _fetchFromRpc(lookbackTs, maxItems) {
+ try {
+ const connection = getConnection({ network: 'mainnet' });
+ const { PublicKey } = await import('@solana/web3.js');
+ const sigs = await connection.getSignaturesForAddress(new PublicKey(PUMP_PROGRAM), {
+ limit: 200,
+ });
+ const inWindow = sigs.filter((s) => s.blockTime != null && s.blockTime >= lookbackTs && !s.err);
+ if (!inWindow.length) return [];
+ const toFetch = inWindow.slice(0, Math.min(30, maxItems * 2));
+ const settled = await Promise.allSettled(
+ toFetch.map((s) =>
+ connection.getParsedTransaction(s.signature, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ }),
+ ),
+ );
+ const claims = [];
+ for (let i = 0; i < settled.length; i++) {
+ if (settled[i].status !== 'fulfilled' || !settled[i].value) continue;
+ const claim = _parseClaim(settled[i].value, toFetch[i].signature, toFetch[i].blockTime ?? 0);
+ if (claim) claims.push(claim);
+ }
+ return claims;
+ } catch {
+ return [];
+ }
+}
+
+function _parseClaim(tx, signature, ts) {
+ if (tx?.meta?.err) return null;
+ const ixs = tx?.transaction?.message?.instructions ?? [];
+ const accountKeys = tx?.transaction?.message?.accountKeys ?? [];
+ const pre = tx?.meta?.preBalances ?? [],
+ post = tx?.meta?.postBalances ?? [];
+ for (const ix of ixs) {
+ if (!ix.data || typeof ix.data !== 'string') continue;
+ const progKey = accountKeys[ix.programIdIndex];
+ const progId = progKey?.pubkey?.toString?.() ?? String(progKey ?? '');
+ if (progId !== PUMP_PROGRAM) continue;
+ let bytes;
+ try {
+ bytes = bs58.decode(ix.data);
+ } catch {
+ continue;
+ }
+ if (bytes.length < 8) continue;
+ const disc = Buffer.from(bytes.subarray(0, 8)).toString('hex');
+ if (!CLAIM_DISCS.has(disc)) continue;
+ const creator = accountKeys[0]?.pubkey?.toString?.() ?? String(accountKeys[0] ?? '');
+ if (!creator) continue;
+ let lamports = 0;
+ for (let i = 0; i < accountKeys.length; i++) {
+ const delta = (post[i] ?? 0) - (pre[i] ?? 0);
+ if (delta > lamports) lamports = delta;
+ }
+ let mint = '';
+ if (disc === 'a537817004b3ca28' && bytes.length >= 48) {
+ try {
+ mint = bs58.encode(bytes.slice(16, 48));
+ } catch {}
+ }
+ // Fallback: the coin's mint appears in the tx token balances. Skip the
+ // quote mints (wSOL/USDC) — the snipe target is the coin, not the quote.
+ if (!mint) mint = _mintFromBalances(tx) || '';
+ return { creator, mint, signature, lamports, ts };
+ }
+ return null;
+}
+
+function _mintFromBalances(tx) {
+ const balances = [
+ ...(tx?.meta?.postTokenBalances ?? []),
+ ...(tx?.meta?.preTokenBalances ?? []),
+ ];
+ for (const b of balances) {
+ if (b?.mint && !QUOTE_MINTS.has(b.mint)) return b.mint;
+ }
+ return null;
+}
diff --git a/api/_lib/token/index.js b/api/_lib/token/index.js
index 47037ba71..b01822111 100644
--- a/api/_lib/token/index.js
+++ b/api/_lib/token/index.js
@@ -11,5 +11,14 @@
export * from './config.js';
export * from './price.js';
export { issueQuote, verifyQuote } from './quote.js';
-export { verifyOnChain, settlePayment, verifyAndSettlePayment, listPayments, creatorEarnings, economyStats } from './payments.js';
+export {
+ verifyOnChain,
+ settlePayment,
+ verifyAndSettlePayment,
+ listPayments,
+ creatorEarnings,
+ economyStats,
+ recordRewardsDistribution,
+ listRewardsDistributions,
+} from './payments.js';
export { computeRewardsDistribution } from './rewards.js';
diff --git a/api/_lib/token/payments.js b/api/_lib/token/payments.js
index 976a3f1a1..9d4b152a6 100644
--- a/api/_lib/token/payments.js
+++ b/api/_lib/token/payments.js
@@ -350,3 +350,78 @@ export async function economyStats({ sinceDays = null } = {}) {
decimals: head.decimals ?? null,
};
}
+
+// ── Holder-rewards (reflections) distribution ledger ──────────────────────────
+// The public, verifiable record of every distribution run. This is what lets
+// /three show a real "reflected to holders" number with history — the deflation-
+// free answer to a burn counter. No secrets stored; every row is on-chain facts.
+
+/**
+ * Record a distribution run. `status` is 'planned' for a dry run (no signer) or
+ * 'completed'/'failed' once executed. Returns the new row's id + created_at.
+ */
+export async function recordRewardsDistribution({
+ mint,
+ poolWallet,
+ poolAtomics,
+ distributedAtomics = 0n,
+ dustAtomics = 0n,
+ holderCount = 0,
+ eligibleSupplyAtomics = 0n,
+ status = 'planned',
+ txSignatures = [],
+ note = null,
+}) {
+ const [row] = await sql`
+ insert into three_rewards_distributions
+ (mint, pool_wallet, pool_atomics, distributed_atomics, dust_atomics,
+ holder_count, eligible_supply_atomics, status, tx_signatures, note)
+ values
+ (${mint}, ${poolWallet}, ${String(poolAtomics)}, ${String(distributedAtomics)},
+ ${String(dustAtomics)}, ${Math.max(0, Math.floor(holderCount))},
+ ${String(eligibleSupplyAtomics)}, ${status},
+ ${JSON.stringify(txSignatures)}::jsonb, ${note})
+ returning id, created_at
+ `;
+ return { id: row.id, created_at: row.created_at };
+}
+
+/**
+ * Public history of distributions + the cumulative reflected total. `completed`
+ * runs count toward the headline; `planned` (dry) runs are shown but excluded
+ * from the reflected total so the number only ever reflects real on-chain payouts.
+ * @returns {Promise<{ total_reflected_atomics: string, run_count: number, items: object[] }>}
+ */
+export async function listRewardsDistributions({ limit = 20 } = {}) {
+ const cap = Math.min(Math.max(Number(limit) || 20, 1), 100);
+ const rows = await sql`
+ select id, mint, pool_wallet, pool_atomics, distributed_atomics, dust_atomics,
+ holder_count, eligible_supply_atomics, status, tx_signatures, note, created_at
+ from three_rewards_distributions
+ order by created_at desc
+ limit ${cap}
+ `;
+ const [{ total = '0', n = 0 } = {}] = await sql`
+ select coalesce(sum(distributed_atomics), 0)::text as total, count(*) as n
+ from three_rewards_distributions
+ where status = 'completed'
+ `;
+ return {
+ total_reflected_atomics: String(total),
+ run_count: Number(n),
+ items: rows.map((r) => ({
+ id: r.id,
+ mint: r.mint,
+ pool_wallet: r.pool_wallet,
+ pool_atomics: String(r.pool_atomics),
+ distributed_atomics: String(r.distributed_atomics),
+ dust_atomics: String(r.dust_atomics),
+ holder_count: Number(r.holder_count),
+ eligible_supply_atomics: String(r.eligible_supply_atomics),
+ status: r.status,
+ tx_signatures: r.tx_signatures,
+ note: r.note,
+ created_at: r.created_at,
+ })),
+ };
+}
diff --git a/api/cron/rewards-distribute.js b/api/cron/rewards-distribute.js
index 8f9c8c34d..4b8294798 100644
--- a/api/cron/rewards-distribute.js
+++ b/api/cron/rewards-distribute.js
@@ -23,6 +23,7 @@ import { TOKEN_MINT, ATOMICS_PER_TOKEN, treasuryWalletOrNull, rewardsWalletOrNul
import { fetchHolderBalances } from '../_lib/coin/holders.js';
import { getBalances } from '../_lib/balances.js';
import { computeRewardsDistribution } from '../_lib/token/rewards.js';
+import { recordRewardsDistribution } from '../_lib/token/payments.js';
function requireCron(req, res) {
const secret = process.env.CRON_SECRET || env.CRON_SECRET;
@@ -87,14 +88,38 @@ export default wrap(async (req, res) => {
// Distribution requires a funded signer; without it this run is an authoritative
// dry run (the plan is exact and auditable). Executing is the only step gated.
const distributorConfigured = Boolean(process.env.REWARDS_DISTRIBUTOR_SECRET);
+ const note = distributorConfigured
+ ? 'executor pending funded-distributor verification'
+ : 'REWARDS_DISTRIBUTOR_SECRET not configured — dry run only';
+
+ // Record the run so /three can show a real, verifiable distribution history.
+ // Status 'planned' (dry run) is logged but excluded from the reflected total —
+ // only 'completed' on-chain runs count toward "reflected to holders". A logging
+ // failure must never fail the cron, so it's best-effort.
+ let recordId = null;
+ try {
+ const rec = await recordRewardsDistribution({
+ mint: TOKEN_MINT,
+ poolWallet: rewardsWallet,
+ poolAtomics,
+ distributedAtomics: plan.distributed,
+ dustAtomics: plan.dust,
+ holderCount: plan.payouts.length,
+ eligibleSupplyAtomics: plan.eligibleSupply,
+ status: 'planned',
+ note,
+ });
+ recordId = rec.id;
+ } catch (err) {
+ console.error('[rewards-distribute] failed to record run', err?.message || err);
+ }
return json(res, 200, {
+ distribution_id: recordId,
ok: true,
executed: false,
dry_run: true,
- reason: distributorConfigured
- ? 'executor pending funded-distributor verification'
- : 'REWARDS_DISTRIBUTOR_SECRET not configured — dry run only',
+ reason: note,
mint: TOKEN_MINT,
pool_wallet: rewardsWallet,
pool_atomics: poolAtomics.toString(),
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 9b9320fb3..d4014f637 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -3717,22 +3717,7 @@ async function handleDeliverTelegram(req, res) {
// ── first-claims ──────────────────────────────────────────────────────────────
-import bs58 from 'bs58';
-import { filterFirstClaims } from '../../src/pump/first-claims.js';
-
-const PUMP_PROGRAM = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';
-const CLAIM_DISCS = new Set(['e8f5c2eeeada3a59', '7a027f010ebf0caf', 'a537817004b3ca28']);
-const LOOKBACK_MULT = 8;
-
-export async function scanFirstClaims({ sinceTs, limit }) {
- const lim = Math.max(1, Math.min(50, limit));
- const lookbackTs =
- sinceTs - Math.max(3600, (Math.floor(Date.now() / 1000) - sinceTs) * LOOKBACK_MULT);
- const allClaims = process.env.PUMPFUN_BOT_URL
- ? await _fetchFromBot(lookbackTs, lim * LOOKBACK_MULT)
- : await _fetchFromRpc(lookbackTs, lim * LOOKBACK_MULT);
- return filterFirstClaims(allClaims, sinceTs, lim);
-}
+import { scanFirstClaims } from '../_lib/pump-claims.js';
// ── recent-graduations ───────────────────────────────────────────────────────
//
@@ -3782,127 +3767,6 @@ async function handleFirstClaims(req, res) {
return json(res, 200, { items });
}
-async function _fetchFromBot(lookbackTs, maxItems) {
- const r = await _botCall('getFirstClaims', { sinceTs: lookbackTs, limit: maxItems });
- if (r.ok) return _normalise(r.data);
- const r2 = await _botCall('getRecentClaims', { limit: maxItems });
- if (r2.ok) return _normalise(r2.data);
- return [];
-}
-async function _botCall(tool, args) {
- const url = process.env.PUMPFUN_BOT_URL;
- if (!url) return { ok: false };
- const headers = { 'content-type': 'application/json', accept: 'application/json' };
- if (process.env.PUMPFUN_BOT_TOKEN)
- headers.authorization = `Bearer ${process.env.PUMPFUN_BOT_TOKEN}`;
- const ctrl = new AbortController();
- const t = setTimeout(() => ctrl.abort(), 8000);
- try {
- const resp = await fetch(url.replace(/\/$/, ''), {
- method: 'POST',
- headers,
- signal: ctrl.signal,
- body: JSON.stringify({
- jsonrpc: '2.0',
- id: 1,
- method: 'tools/call',
- params: { name: tool, arguments: args || {} },
- }),
- });
- if (!resp.ok) return { ok: false, error: `bot ${resp.status}` };
- const j = await resp.json();
- if (j.error) return { ok: false, error: j.error.message || 'rpc error' };
- const data = j.result?.structuredContent ?? j.result?.content ?? j.result;
- return { ok: true, data: Array.isArray(data) ? data : (data?.items ?? []) };
- } catch (err) {
- return { ok: false, error: err?.message || 'fetch failed' };
- } finally {
- clearTimeout(t);
- }
-}
-function _normalise(items) {
- return (items || [])
- .map((x) => ({
- creator: String(x.claimerWallet || x.creator || x.wallet || ''),
- mint: String(x.tokenMint || x.mint || ''),
- signature: String(x.txSignature || x.tx_signature || x.signature || ''),
- lamports: Number(x.amountLamports || x.lamports || 0),
- ts: Number(x.timestamp || x.ts || 0),
- }))
- .filter((x) => x.creator && x.signature && x.ts > 0);
-}
-async function _fetchFromRpc(lookbackTs, maxItems) {
- try {
- const connection = getConnection({ network: 'mainnet' });
- const { PublicKey } = await import('@solana/web3.js');
- const sigs = await connection.getSignaturesForAddress(new PublicKey(PUMP_PROGRAM), {
- limit: 200,
- });
- const inWindow = sigs.filter(
- (s) => s.blockTime != null && s.blockTime >= lookbackTs && !s.err,
- );
- if (!inWindow.length) return [];
- const toFetch = inWindow.slice(0, Math.min(30, maxItems * 2));
- const settled = await Promise.allSettled(
- toFetch.map((s) =>
- connection.getParsedTransaction(s.signature, {
- maxSupportedTransactionVersion: 0,
- commitment: 'confirmed',
- }),
- ),
- );
- const claims = [];
- for (let i = 0; i < settled.length; i++) {
- if (settled[i].status !== 'fulfilled' || !settled[i].value) continue;
- const claim = _parseClaim(
- settled[i].value,
- toFetch[i].signature,
- toFetch[i].blockTime ?? 0,
- );
- if (claim) claims.push(claim);
- }
- return claims;
- } catch {
- return [];
- }
-}
-function _parseClaim(tx, signature, ts) {
- if (tx?.meta?.err) return null;
- const ixs = tx?.transaction?.message?.instructions ?? [];
- const accountKeys = tx?.transaction?.message?.accountKeys ?? [];
- const pre = tx?.meta?.preBalances ?? [],
- post = tx?.meta?.postBalances ?? [];
- for (const ix of ixs) {
- if (!ix.data || typeof ix.data !== 'string') continue;
- const progKey = accountKeys[ix.programIdIndex];
- const progId = progKey?.pubkey?.toString?.() ?? String(progKey ?? '');
- if (progId !== PUMP_PROGRAM) continue;
- let bytes;
- try {
- bytes = bs58.decode(ix.data);
- } catch {
- continue;
- }
- if (bytes.length < 8) continue;
- const disc = Buffer.from(bytes.subarray(0, 8)).toString('hex');
- if (!CLAIM_DISCS.has(disc)) continue;
- const creator = accountKeys[0]?.pubkey?.toString?.() ?? String(accountKeys[0] ?? '');
- if (!creator) continue;
- let lamports = 0;
- for (let i = 0; i < accountKeys.length; i++) {
- const delta = (post[i] ?? 0) - (pre[i] ?? 0);
- if (delta > lamports) lamports = delta;
- }
- let mint = '';
- if (disc === 'a537817004b3ca28' && bytes.length >= 48) {
- try {
- mint = bs58.encode(bytes.slice(16, 48));
- } catch {}
- }
- return { creator, mint, signature, lamports, ts };
- }
- return null;
-}
// ── vanity-keygen (SSE) ───────────────────────────────────────────────────────
diff --git a/api/sniper/strategy.js b/api/sniper/strategy.js
index 7b4467e0e..bfaceb061 100644
--- a/api/sniper/strategy.js
+++ b/api/sniper/strategy.js
@@ -32,11 +32,22 @@ const lamports = z.union([z.string(), z.number()]);
const optPct = z.union([z.string(), z.number()]).nullable().optional();
const optInt = z.union([z.string(), z.number()]).nullable().optional();
+const optLamports = z.union([z.string(), z.number()]).nullable().optional();
+
const STRATEGY_SCHEMA = z.object({
agent_id: z.string().uuid(),
network: z.enum(['mainnet', 'devnet']).default('mainnet'),
enabled: z.boolean().optional(),
kill_switch: z.boolean().optional(),
+ // trigger: what arms this strategy.
+ // new_mint — snipe new pump.fun launches off the PumpPortal feed (default).
+ // first_claim — snipe a creator's coin the first time they EVER claim rewards.
+ trigger: z.enum(['new_mint', 'first_claim']).optional(),
+ buy_delay_ms: z.union([z.string(), z.number()]).optional(),
+ // first_claim entry filters (null clears)
+ min_claim_lamports: optLamports,
+ max_claim_lamports: optLamports,
+ first_claim_max_age_seconds: optInt,
// sizing
daily_budget_lamports: lamports.optional(),
per_trade_lamports: lamports.optional(),
@@ -72,6 +83,16 @@ const intOrNull = (v) => {
const n = Math.floor(Number(v));
return Number.isFinite(n) ? n : null;
};
+const atomicOrNull = (v) => {
+ if (v == null || v === '') return null;
+ let s = String(v).trim();
+ if (!/^\d+$/.test(s)) {
+ const n = Number(s);
+ if (!Number.isFinite(n) || n < 0) return null;
+ s = String(Math.floor(n));
+ }
+ return s;
+};
const numOrNull = (v) => {
if (v == null || v === '') return null;
const n = Number(v);
@@ -133,6 +154,11 @@ async function listStrategies(req, res, userId) {
network: s.network,
enabled: s.enabled,
kill_switch: s.kill_switch,
+ trigger: s.trigger || 'new_mint',
+ buy_delay_ms: s.buy_delay_ms ?? 0,
+ min_claim_lamports: s.min_claim_lamports != null ? String(s.min_claim_lamports) : null,
+ max_claim_lamports: s.max_claim_lamports != null ? String(s.max_claim_lamports) : null,
+ first_claim_max_age_seconds: s.first_claim_max_age_seconds ?? null,
daily_budget_lamports: String(s.daily_budget_lamports),
per_trade_lamports: String(s.per_trade_lamports),
max_concurrent_positions: s.max_concurrent_positions,
@@ -184,6 +210,8 @@ async function upsertStrategy(req, res, userId) {
`;
const cur = existing || {
enabled: false, kill_switch: false,
+ trigger: 'new_mint', buy_delay_ms: 0,
+ min_claim_lamports: null, max_claim_lamports: null, first_claim_max_age_seconds: null,
daily_budget_lamports: '0', per_trade_lamports: '0',
max_concurrent_positions: 1, slippage_bps: 500, max_price_impact_pct: 10,
min_market_cap_usd: null, max_market_cap_usd: null,
@@ -196,6 +224,11 @@ async function upsertStrategy(req, res, userId) {
const next = {
enabled: p.enabled ?? cur.enabled,
kill_switch: p.kill_switch ?? cur.kill_switch,
+ trigger: p.trigger ?? cur.trigger,
+ buy_delay_ms: p.buy_delay_ms != null ? clampInt(p.buy_delay_ms, 0, 600000, 0) : cur.buy_delay_ms,
+ min_claim_lamports: 'min_claim_lamports' in p ? atomicOrNull(p.min_claim_lamports) : (cur.min_claim_lamports != null ? String(cur.min_claim_lamports) : null),
+ max_claim_lamports: 'max_claim_lamports' in p ? atomicOrNull(p.max_claim_lamports) : (cur.max_claim_lamports != null ? String(cur.max_claim_lamports) : null),
+ first_claim_max_age_seconds: 'first_claim_max_age_seconds' in p ? (p.first_claim_max_age_seconds == null ? null : clampInt(p.first_claim_max_age_seconds, 1, 86400, 300)) : cur.first_claim_max_age_seconds,
daily_budget_lamports: p.daily_budget_lamports != null ? atomicStr(p.daily_budget_lamports) : String(cur.daily_budget_lamports),
per_trade_lamports: p.per_trade_lamports != null ? atomicStr(p.per_trade_lamports) : String(cur.per_trade_lamports),
max_concurrent_positions: p.max_concurrent_positions != null ? clampInt(p.max_concurrent_positions, 1, 50, 1) : cur.max_concurrent_positions,
@@ -224,10 +257,15 @@ async function upsertStrategy(req, res, userId) {
if (next.enabled && BigInt(next.per_trade_lamports) > BigInt(next.daily_budget_lamports)) {
return error(res, 400, 'bad_request', 'per_trade_lamports cannot exceed daily_budget_lamports');
}
+ if (next.min_claim_lamports != null && next.max_claim_lamports != null &&
+ BigInt(next.min_claim_lamports) > BigInt(next.max_claim_lamports)) {
+ return error(res, 400, 'bad_request', 'min_claim_lamports cannot exceed max_claim_lamports');
+ }
const [row] = await sql`
insert into agent_sniper_strategies
(agent_id, user_id, network, enabled, kill_switch,
+ trigger, buy_delay_ms, min_claim_lamports, max_claim_lamports, first_claim_max_age_seconds,
daily_budget_lamports, per_trade_lamports, max_concurrent_positions,
slippage_bps, max_price_impact_pct,
min_market_cap_usd, max_market_cap_usd, min_creator_graduated, max_creator_launches,
@@ -235,6 +273,7 @@ async function upsertStrategy(req, res, userId) {
take_profit_pct, stop_loss_pct, trailing_stop_pct, max_hold_seconds, updated_at)
values
(${p.agent_id}, ${userId}, ${p.network}, ${next.enabled}, ${next.kill_switch},
+ ${next.trigger}, ${next.buy_delay_ms}, ${next.min_claim_lamports}, ${next.max_claim_lamports}, ${next.first_claim_max_age_seconds},
${next.daily_budget_lamports}, ${next.per_trade_lamports}, ${next.max_concurrent_positions},
${next.slippage_bps}, ${next.max_price_impact_pct},
${next.min_market_cap_usd}, ${next.max_market_cap_usd}, ${next.min_creator_graduated}, ${next.max_creator_launches},
@@ -243,6 +282,11 @@ async function upsertStrategy(req, res, userId) {
on conflict (agent_id, network) do update set
enabled = excluded.enabled,
kill_switch = excluded.kill_switch,
+ trigger = excluded.trigger,
+ buy_delay_ms = excluded.buy_delay_ms,
+ min_claim_lamports = excluded.min_claim_lamports,
+ max_claim_lamports = excluded.max_claim_lamports,
+ first_claim_max_age_seconds = excluded.first_claim_max_age_seconds,
daily_budget_lamports = excluded.daily_budget_lamports,
per_trade_lamports = excluded.per_trade_lamports,
max_concurrent_positions = excluded.max_concurrent_positions,
@@ -269,6 +313,11 @@ async function upsertStrategy(req, res, userId) {
network: row.network,
enabled: row.enabled,
kill_switch: row.kill_switch,
+ trigger: row.trigger || 'new_mint',
+ buy_delay_ms: row.buy_delay_ms ?? 0,
+ min_claim_lamports: row.min_claim_lamports != null ? String(row.min_claim_lamports) : null,
+ max_claim_lamports: row.max_claim_lamports != null ? String(row.max_claim_lamports) : null,
+ first_claim_max_age_seconds: row.first_claim_max_age_seconds ?? null,
daily_budget_lamports: String(row.daily_budget_lamports),
per_trade_lamports: String(row.per_trade_lamports),
max_concurrent_positions: row.max_concurrent_positions,
diff --git a/api/three/[action].js b/api/three/[action].js
index cdc67cee5..9a8c27335 100644
--- a/api/three/[action].js
+++ b/api/three/[action].js
@@ -25,10 +25,26 @@ import { parse } from '../_lib/validate.js';
import { publicCatalog } from '../_lib/pricing/catalog.js';
import { requireThreePayment } from '../_lib/pricing/charge-three.js';
import { holderDiscountBps, resolveUserTier, signTierPass, TIERS } from '../_lib/three-tier.js';
-import { creatorEarnings, economyStats } from '../_lib/token/index.js';
+import { creatorEarnings, economyStats, listRewardsDistributions } from '../_lib/token/index.js';
import { priceName, isValidLabel, RARITY_TIERS } from '../_lib/pricing/name-rarity.js';
import { quoteTokenForUsd } from '../_lib/token/price.js';
-import { publicConfig } from '../_lib/token/config.js';
+import { publicConfig, TOKEN_MINT, ATOMICS_PER_TOKEN } from '../_lib/token/config.js';
+import { getBalances } from '../_lib/balances.js';
+
+// Live on-chain $THREE balance (atomics) of a platform wallet, for verifiable
+// stats. Returns 0n on any failure — a balance hiccup must never 500 the public
+// dashboard. The explorer link lets anyone confirm the figure themselves.
+async function liveWalletAtomics(address) {
+ if (!address) return 0n;
+ try {
+ const balances = await getBalances({ chain: 'solana', address });
+ const entry = (balances?.tokens ?? []).find((t) => t.mint === TOKEN_MINT);
+ return BigInt(Math.floor((entry?.amount || 0) * Number(ATOMICS_PER_TOKEN)));
+ } catch {
+ return 0n;
+ }
+}
+const solscan = (addr) => (addr ? `https://solscan.io/account/${addr}` : null);
const SOLANA_ADDRESS = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'invalid Solana address');
@@ -198,8 +214,10 @@ async function handleNameQuote(req, res) {
}
// ── GET /api/three/stats ───────────────────────────────────────────────────────
-// Public economy dashboard data: settled volume + the per-role flow (treasury,
-// rewards, seller) over a window. Powers the /three economy page and /three-live.
+// Public, VERIFIABLE economy dashboard data. Beyond settled volume + the per-role
+// flow, it surfaces the LIVE on-chain balances of the treasury and rewards wallets
+// with Solscan links, plus the real reflected-to-holders history. "Don't trust,
+// verify" — every headline number traces to an address anyone can inspect.
async function handleStats(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
@@ -209,15 +227,50 @@ async function handleStats(req, res) {
const url = new URL(req.url, 'http://x');
const sinceDays = url.searchParams.get('since_days');
- const stats = await economyStats({ sinceDays: sinceDays != null ? Number(sinceDays) : null });
const cfg = publicConfig();
+
+ // Fan out the independent reads concurrently: ledger aggregates, live wallet
+ // balances, and the distribution history. Each degrades independently.
+ const [stats, treasuryAtomics, rewardsAtomics, distributions] = await Promise.all([
+ economyStats({ sinceDays: sinceDays != null ? Number(sinceDays) : null }),
+ liveWalletAtomics(cfg.treasury),
+ liveWalletAtomics(cfg.rewards_wallet),
+ listRewardsDistributions({ limit: 10 }).catch(() => ({
+ total_reflected_atomics: '0',
+ run_count: 0,
+ items: [],
+ })),
+ ]);
+
return json(res, 200, {
...stats,
token: { mint: cfg.mint, symbol: cfg.symbol, decimals: cfg.decimals },
- treasury_configured: cfg.treasury_configured,
- rewards_configured: cfg.rewards_configured,
- // Make the no-burn policy explicit in the public data so the dashboard can
- // state it plainly: every spend reflects to holders / funds the treasury.
+ // Verifiable on-chain state: live balances + the addresses + explorer links.
+ // This is the answer to a competitor's "trust us, we burned some" — here are
+ // the wallets; check them yourself.
+ onchain: {
+ treasury: {
+ address: cfg.treasury,
+ configured: cfg.treasury_configured,
+ balance_atomics: treasuryAtomics.toString(),
+ explorer: solscan(cfg.treasury),
+ },
+ rewards_pool: {
+ address: cfg.rewards_wallet,
+ configured: cfg.rewards_configured,
+ balance_atomics: rewardsAtomics.toString(),
+ explorer: solscan(cfg.rewards_wallet),
+ },
+ mint_explorer: solscan(cfg.mint),
+ },
+ // Real reflections, not a burn counter: cumulative $THREE returned to holders
+ // across completed distribution runs, with recent run history.
+ reflected: {
+ total_atomics: distributions.total_reflected_atomics,
+ run_count: distributions.run_count,
+ recent: distributions.items,
+ },
+ // The platform never burns supply. Stated plainly in the public data.
burns: false,
});
}
diff --git a/data/changelog.json b/data/changelog.json
index 0eeb53ad6..2229f4984 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$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": "Pump Visualizer: a coin's look now tracks its market cap",
+ "summary": "On the Pump Visualizer, market cap no longer just sizes a coin — it shapes its whole look. As a coin's cap climbs it shifts color from cool blue through purple to green and gold, grows a crystalline wireframe cage that gains facets at each tier, and spins and pulses with more energy. On the trending refresh, a coin that moved gets a clear signal: it flashes green and pops bigger when its cap rose, red and dips when it fell, and crossing into a higher or lower tier visibly upgrades or downgrades its shape and color. A new on-screen key in the corner maps each color and tier to its market-cap range so it all reads at a glance.",
+ "tags": ["feature"],
+ "link": "/pump-visualizer"
+ },
{
"date": "2026-06-15",
"title": "Four distinct dancers, now waiting at their poles",
diff --git a/docs/roadmap/pumpfun-trading.md b/docs/roadmap/pumpfun-trading.md
new file mode 100644
index 000000000..e7aa7981c
--- /dev/null
+++ b/docs/roadmap/pumpfun-trading.md
@@ -0,0 +1,532 @@
+# Pump.fun Trading — Product Plan & Prompt Library
+
+**Status:** planning · **Owner:** TBD · **Last updated:** 2026-06-15
+
+> Scope lock: this document is *only* about pump.fun trading, deploying, and the
+> copy-trade / earn-when-copied economy around it. Everything else (forge,
+> avatars-as-art, world, naming) is out of scope here except where it directly
+> makes trading more fun or more viral.
+
+---
+
+## 0. TL;DR
+
+We already have the hard parts of a pump.fun trading stack: a live sniper worker,
+a strategy DSL with backtest/validate/run, a positions ledger with realized PnL +
+trailing stops, on-chain reputation, SIWS auth, PumpPortal + Helius feeds, the
+pump trade/launch SDKs, and $THREE pay-per-use rails.
+
+What we do **not** have is the *product*: the thing a degen opens at 3am, the
+thing they screenshot, the thing that makes the trader they copied richer so that
+trader shills us for free.
+
+The bet: **turn proven traders (human or agent) into creators who earn a cut of
+the profits they generate for their followers, wrap the whole thing in a 3D
+avatar personality layer nobody else has, and make every win a shareable
+artifact with a referral hook baked in.**
+
+The flywheel:
+
+```
+ great agents/traders → provable on-chain track record → followers copy them
+ ↑ │
+ │ ▼
+ leaders earn perf-fees ← followers profit & stay ← copied trades execute
+ ↑ │
+ └────────── shareable PnL cards + referral $THREE ◀──────────┘
+```
+
+Every loop spins the next: leaders earn → recruit followers; followers win →
+share cards; cards carry referral links → new users; new users need someone to
+copy → demand for leaders. $THREE is the settlement layer and the throttle.
+
+---
+
+## 1. Who is the user, and what are they trying to do
+
+Three personas. Build for all three; they feed each other.
+
+### 1.1 The Degen (the follower / the masses)
+Wants to make money on pump.fun without staring at charts for 18 hours. Today
+they ape into whatever's trending and get dumped on. They don't have edge.
+**Our promise:** "Pick a proven agent. Set a budget. Go to sleep. Wake up to
+trades you'd never have caught." One-tap copy. Hard spend caps. Their own
+non-custodial wallet — we never hold funds.
+
+### 1.2 The Alpha (the leader / the creator)
+A sharp trader or a well-tuned agent that actually prints. Today their edge is
+worth nothing beyond their own bag — they post screenshots for clout. **Our
+promise:** "Get copied, get paid. Your track record is on-chain and unfakeable.
+The more people you make money, the more you earn." Performance fees + a public
+rank + a fan base.
+
+### 1.3 The Builder (the agent author / power user)
+Wants to build/tune a trading agent — a sniper, a graduation-hunter, a
+contrarian. Today they'd write a Trojan/BullX config in a vacuum. **Our
+promise:** "Compose a strategy, backtest it on real history, paper-trade to a
+provable record, then open it for copy and earn from every follower." Strategy
+DSL + backtest + marketplace.
+
+---
+
+## 2. Why we win (the moat nobody else has)
+
+Competitors: Photon, BullX, Trojan, GMGN, Axiom, Bloom, Maestro, Pepeboost.
+They are fast, sterile, identical Telegram/terminal UIs. Copy-trading exists
+(GMGN, BullX) but it's "mirror a raw wallet" — no reasoning, no personality, no
+creator economy, no provable identity.
+
+Our five differentiators:
+
+1. **Agents that explain themselves.** Not "wallet 0xabc bought" — *"$TICKER:
+ curve 68% to graduation, 3 of last 5 buys are fresh wallets, creator has 2
+ prior graduations, dev holds 4%. Entering 0.5 SOL, TP +60% / SL −25%."* Copy
+ reasoning, not just trades. This is the single biggest trust unlock.
+2. **3D avatar personality layer.** Your trader has a face, a voice, a vibe. It
+ celebrates a 5x, sweats a drawdown, trash-talks a rival agent. We already
+ drive avatars from the live feed (`pump-fun-skills/reactive`). Nobody else
+ has entertainment. Entertainment is what gets shared.
+3. **Earn-when-copied creator economy.** Performance fees flow to leaders.
+ This makes leaders *recruit for us*. None of the terminals pay their
+ alpha-providers.
+4. **Provable, on-chain track record.** PnL attested on-chain
+ (`solana_attestations`, reputation endpoint). Can't fake screenshots.
+ "Verified +340% / 90d, skin-in-game 12 SOL" beats a Photon screenshot every
+ time.
+5. **$THREE-native economy.** Fees, discounts, tournament prize pools, leader
+ payouts route through $THREE. Holders get fee discounts and revenue share.
+ The token is the product's bloodstream, not a sidecar.
+
+---
+
+## 3. The product surfaces (what we actually build)
+
+Each surface notes the existing infra it sits on so we build, not re-build.
+
+### 3.1 The Arena — live agent trading leaderboard (the front door)
+A public, real-time leaderboard of trading agents ranked by **verified** PnL,
+win rate, Sharpe-ish consistency, max drawdown, and follower AUM. Filter by
+timeframe (24h / 7d / 30d / all), strategy type, and risk level. Each row is a
+live card: avatar, current open positions, today's PnL ticking in real time,
+"Copy" button, follower count, fee rate.
+
+- *Builds on:* `agent_sniper_positions` (PnL), `api/x402/agent-reputation.js`,
+ `api/cosmetics/leaderboard.js` (computation pattern), SSE
+ `api/pump/trades-stream.js`.
+- *The hook:* this is the page that gets bookmarked. Make it gorgeous and live.
+
+### 3.2 The Agent Profile — a trader's home page
+Public page per agent: 3D avatar front and center, verified track record
+(equity curve, all-time PnL, best/worst trades, current holdings), strategy
+description in plain language, fee rate, followers, total profit generated for
+followers ("has made followers +$142k"), and a one-tap **Copy** flow. Trade log
+streams live with reasoning attached to each trade.
+
+- *Builds on:* `src/agent-home-pumpfun.js`, `api/pump/portfolio.js`,
+ `api/pump/dashboard.js`, agent identity system.
+
+### 3.3 Copy-Trade — the money mechanic (detailed in §4)
+One tap from any leaderboard row or profile. Pick budget, per-trade cap, daily
+cap, copy filters (only buys above $X mcap, ignore positions over Y SOL).
+Non-custodial: follower's own wallet via delegated session key with hard caps.
+
+- *Builds on:* `agent-spend-policy.js`, `solana-agent-sdk` session signing,
+ `workers/agent-sniper/`, `agent-payments-sdk`.
+
+### 3.4 The Studio — build/tune your own trading agent
+Pick a persona (Sniper / Swing / Graduation Hunter / Contrarian / Custom),
+configure entry/exit rules via the strategy DSL, **backtest on real history**,
+**paper-trade** to build a provable record, then flip to live, then open for
+copy. This is how we manufacture supply of leaders.
+
+- *Builds on:* `api/pump/strategy-backtest.js`, `strategy-validate.js`,
+ `strategy-run.js`, `agent_sniper_strategies` schema, `examples/skills/
+ pump-fun-strategy/`.
+
+### 3.5 Launchpad — agents that deploy coins
+An agent (or user) launches a coin with one tap, optionally with creator-fee
+sharing to followers/holders, then can trade/buyback/distribute autonomously.
+
+- *Builds on:* `pump-fun-skills/create-coin`, `api/pump/launch-*`, `coin-fees`,
+ `autopilot.js`, `src/agent-skills-pumpfun-autonomous.js`. Already strong —
+ mostly needs UI polish and wiring into Arena/profile.
+
+### 3.6 The Feed — TikTok for trades (virality engine, §6)
+A vertical, swipeable feed of notable trades: "$AGENT just 7x'd $TICKER",
+avatar reaction clip, the reasoning, the PnL card, a Copy button, a referral
+link. Public, no login needed to browse. This is the top-of-funnel.
+
+### 3.7 Tournaments / Seasons (§6)
+Recurring competitions with $THREE prize pools. Equal starting capital, fixed
+window, public leaderboard, avatars battling. Fantasy-league energy.
+
+### 3.8 Native distribution: Telegram + X bots
+Meet traders where they live. A Telegram bot that posts your agent's trades and
+lets you copy from chat; an X auto-poster for big wins (PnL card + link).
+
+- *Builds on:* `api/pump/deliver-telegram.js`, alert system, PnL card renderer.
+
+---
+
+## 4. The money: copy-trade + earn-when-copied (designed concretely)
+
+This is the answer to your "person being copy-traded earns a fee?" — **yes, and
+it's the whole flywheel.** Here's the concrete design.
+
+### 4.1 Custody model (non-custodial, phased)
+- **Phase 1 — Delegated mirror.** Follower keeps funds in their own wallet and
+ grants the copy-engine a **session key with hard caps** (max per trade, max
+ daily, max total, allowlist = pump.fun program only, auto-expiry). The engine
+ mirrors the leader's trades into the follower's wallet. We never custody.
+ Uses `agent-spend-policy.js` + session signing already in `solana-agent-sdk`.
+- **Phase 2 — Copy vault (optional, later).** An on-chain program-controlled
+ vault followers deposit into; leader directs; performance fee skimmed
+ on-chain at withdrawal against a high-water mark. More powerful (pooled size,
+ cleaner accounting) but needs an audited program. Defer until Phase 1 proves
+ demand.
+
+### 4.2 Performance fee mechanics
+- Leader sets a **performance fee** (suggested default **15%**, capped at, say,
+ 30%). Fee is charged **only on realized profit**, **only above a per-follower
+ high-water mark** (no double-charging the same gains). This is the industry-
+ correct model and it's fair — leaders eat nothing when followers lose.
+- Optional small **flat copy subscription** (e.g. a few $THREE/week) as an
+ anti-spam floor, waivable by holders. Default off; perf-fee-only is cleaner
+ for launch.
+- **Settlement:** fee computed on each profitable exit; accrued; swept
+ periodically. Charged in the trade's quote asset (SOL/USDC) or auto-converted
+ to $THREE. Built on `charge-three.js` two-phase CHARGE→SETTLE and
+ `agent_revenue_events`.
+
+### 4.3 The split (where each fee goes)
+On a follower's realized profit above high-water mark, the performance fee
+splits roughly:
+
+| Recipient | Share | Why |
+|---|---|---|
+| **Leader** | 70% | The alpha. Their reason to recruit followers. |
+| **Platform treasury** | 20% | Funds dev, buys back $THREE, seeds prize pools. |
+| **Referrer** | 10% | Whoever brought the follower (or the leader). Viral fuel. |
+
+(Tune later. The point is leaders earn the lion's share, the platform sustains,
+and referrers are paid — every dollar of profit funds the next loop.)
+Built on `api/_lib/token/config.js` split-policies + `referrals.js`.
+
+### 4.4 Skin-in-the-game requirement (trust + anti-rug)
+To be copyable, a leader must have **their own capital deployed alongside
+followers**, provable on-chain, displayed on their profile ("12 SOL skin in
+game"). This aligns incentives — a leader can't pump-and-dump followers without
+eating it themselves. Enforced by reading the leader's own wallet positions
+against the trades they broadcast. Huge trust signal; nobody else does it.
+
+### 4.5 Guardrails (protect the follower)
+- Per-trade / daily / total spend caps (hard, on-chain via session key).
+- Max position concentration, min liquidity / mcap filters, max slippage,
+ honeypot/sell-tax checks before mirroring a buy.
+- Auto-pause copy if leader drawdown exceeds follower's set threshold.
+- "Front-run protection": cap how much a follower copies relative to leader size
+ so a tiny leader can't be gamed.
+- One-tap "stop copying + sell all" panic button.
+- *Builds on:* `pump-alert-eval.js`, `scorer.js`, `agent-spend-policy.js`.
+
+---
+
+## 5. Provable track record (the trust layer)
+
+Screenshots are dead. We win on **unfakeable** records.
+
+- Every agent trade is attested: signature, mint, entry/exit, realized PnL,
+ timestamp → `pump_agent_trades` + `solana_attestations`.
+- The reputation endpoint (`api/x402/agent-reputation.js`) already returns a
+ paid snapshot; extend it with trading-specific metrics: verified PnL,
+ win rate, profit-generated-for-followers, max drawdown, days active, skin in
+ game, # graduations launched.
+- Surface a **"Verified" badge** that links to the on-chain proof. A leader's
+ claimed +340% is one click from the chain.
+- **Anti-gaming:** rank by *risk-adjusted* and *follower-outcome* metrics, not
+ raw PnL, so an agent can't farm rank with one lucky 100x on dust. Weight
+ "profit actually delivered to followers" heavily — that's the metric that
+ matters and the one that's hardest to fake.
+
+---
+
+## 6. Virality — the social effect (this is the assignment)
+
+Distribution is the product. Bake the loop into every win.
+
+### 6.1 The shareable PnL card (the atomic viral unit)
+Auto-generate a beautiful image on every notable exit: avatar, ticker, multiple
+(7.2x), entry→exit, time held, "copied by 214 traders", three.ws watermark, and
+a **referral link**. One tap to post to X/Telegram. Every win becomes an ad we
+didn't pay for, with attribution that pays the sharer.
+
+### 6.2 The Feed (§3.6)
+Endless swipe of wins + reasoning + Copy buttons. Browsable logged-out. This is
+how a cold visitor gets hooked in 30 seconds.
+
+### 6.3 Tournaments & Seasons
+- Weekly/monthly. Equal starting (paper or capped real) capital. $THREE prize
+ pool (seeded by treasury + entry fees). Public bracket, live avatar reactions.
+- **Agent battles:** two agents head-to-head, same capital, fixed window,
+ spectators cheer/predict. Livestream-able with the 3D layer. Pure content.
+- Winners get rank, badges, prize $THREE, and a flood of new followers.
+
+### 6.4 Referral economy
+Already have `referrals.js`. Wire it everywhere: every PnL card, every profile,
+every Copy invite carries a ref code. Referrer earns a slice of perf-fees (§4.3)
+*for as long as the referred user trades* — recurring, not one-shot. That's what
+makes people actually shill.
+
+### 6.5 Personalities & rivalries
+Give agents names, voices, beef. "DegenDestroyer vs ValueVulture, this week's
+grudge match." Leaderboards with attitude. Avatars that talk. This is the
+texture that makes screenshots fun and the brand sticky.
+
+### 6.6 Status & collectibles
+Top-rank badges, season trophies, rare avatar cosmetics for winners (ties into
+existing cosmetics economy). Flexing is retention.
+
+---
+
+## 7. $THREE integration (the economy)
+
+- **Fee discounts** for $THREE holders on perf-fees / copy subs (existing holder
+ tiers).
+- **Prize pools** denominated in $THREE.
+- **Leader payouts / referral rewards** settleable in $THREE.
+- **Treasury buyback:** platform's 20% fee cut buys $THREE → price support →
+ holders win → flywheel for the token, not just the product.
+- **Gating:** premium strategy slots, higher copy caps, priority execution for
+ holders / higher tiers.
+- *Builds on:* `pricing/catalog.js`, `charge-three.js`, `token/config.js`,
+ holder tiers, referrals.
+
+---
+
+## 8. Build order (phased, ship-something-every-week)
+
+**Phase 0 — Foundations already done (audit & harden).** Sniper worker,
+strategy DSL, positions ledger, feeds, reputation, payment rails exist. Verify
+each end-to-end with a funded devnet/mainnet signer. Close gaps.
+
+**Phase 1 — The Arena + Agent Profile (front door, read-only).** Public live
+leaderboard + agent profiles with verified track record, equity curves, live
+trade log with reasoning. No copy yet. Goal: a page worth bookmarking and
+sharing. *Highest leverage to start — it's the showcase that makes everything
+else make sense, and it's mostly assembly of existing data.*
+
+**Phase 2 — Copy-Trade v1 (delegated mirror) + performance fees.** One-tap copy,
+session-key custody with hard caps, high-water-mark perf-fee, the 70/20/10
+split, skin-in-game display, guardrails. This is the money moment.
+
+**Phase 3 — The Studio.** Persona templates + DSL config + backtest + paper-
+trade-to-provable-record + open-for-copy. Manufactures leader supply.
+
+**Phase 4 — Virality engine.** PnL cards, the Feed, referral wiring everywhere,
+Telegram/X bots.
+
+**Phase 5 — Tournaments / Seasons / Agent battles.** The recurring content
+machine + $THREE prize pools.
+
+**Phase 6 — Copy vault (on-chain pooled), advanced strategy marketplace,
+cross-leader portfolios ("index of top 5 agents").**
+
+---
+
+## 9. Risks & honest constraints
+
+- **Funded signer is the recurring blocker** (see memory: pump devnet smoke,
+ self-registration — authority wallets sit at 0 SOL). Live copy-trade needs a
+ funded mainnet path. Resolve custody/funding before Phase 2 ships for real.
+- **Non-custodial copy is genuinely hard.** Session keys with hard caps are the
+ right Phase 1 answer; do not hand-wave it. No custody of user funds without a
+ deliberate, audited decision.
+- **Regulatory surface.** Perf-fees + pooled vaults look like asset management.
+ Keep Phase 1 non-custodial, user-signs-everything, "tool not advice" framing,
+ clear disclaimers. Get the framing right early.
+- **pump.fun is adversarial.** Honeypots, sell-tax, bundled launches, MEV. The
+ scorer must screen hard before any mirrored buy. Jito MEV protection is
+ already wired in the swap skill — use it.
+- **$THREE-only rule.** Every example/fixture/UI string uses $THREE or a clearly
+ synthetic placeholder (`$TICKER`, `<mint>`, `THREEsynthetic1111…`). Never a
+ real third-party mint anywhere.
+
+---
+
+## 10. Prompt library
+
+These are production-shaped system prompts for the trading agents. They
+reference the **real** tools in this repo (MCP read tools in
+`src/pump/mcp-tools.js`; action skills in `pump-fun-skills/`). Personas share
+the core; only the strategy block changes.
+
+### 10.1 Core Trader (base system prompt)
+
+```
+You are a pump.fun trading agent on three.ws. You trade Solana memecoins on the
+pump.fun bonding curve and graduated AMM pools. You manage real capital from a
+single wallet with hard spend caps you must never exceed.
+
+PRIME DIRECTIVE
+Preserve capital first, compound second. A trade you skip costs nothing; a bad
+trade you take costs real money. When uncertain, do not trade.
+
+TOOLS AVAILABLE
+Read (free, use generously before any trade):
+ get_new_tokens, get_trending_tokens, get_graduated_tokens, get_king_of_the_hill
+ get_token_details, get_bonding_curve, get_token_trades, get_token_holders
+ get_creator_profile, search_tokens, pumpfun_quote_swap
+Act (spends real funds — only after the checklist passes):
+ pumpfun_swap (buy/sell on curve or AMM)
+ pumpfun_create_coin (launch, only if instructed)
+
+HARD RULES (never violate)
+- Never exceed: per-trade cap, daily cap, total cap, max slippage. These are
+ injected each run as POLICY. If an action would breach POLICY, refuse it.
+- Never buy without: a fresh get_bonding_curve read, a get_token_holders read
+ (reject if top holder or dev > concentration limit), and a liquidity check.
+- Never buy a token failing the honeypot/sell-tax screen.
+- Always set an exit plan (take-profit, stop-loss, max-hold) at entry and honor
+ it. No "diamond hands" improvisation.
+- Size by conviction × risk, never by FOMO. Most candidates are a pass.
+
+PRE-TRADE CHECKLIST (must pass all before pumpfun_swap buy)
+1. Curve/liquidity: graduation %, real SOL reserves, is it AMM or curve?
+2. Holders: top-10 concentration, dev holding %, fresh-wallet ratio of buyers.
+3. Creator: prior launches, prior graduations, rug history (get_creator_profile).
+4. Momentum: recent trade velocity and buy/sell pressure (get_token_trades).
+5. Socials/legitimacy per POLICY (require_socials?).
+6. Quote: pumpfun_quote_swap — confirm price impact within POLICY.
+
+OUTPUT FORMAT (every decision, for the copy-feed and for followers)
+Return a short, plain-language rationale a human can copy with confidence:
+ DECISION: BUY | SELL | PASS | HOLD
+ TOKEN: $TICKER (<mint>)
+ SIZE: <amount + asset> (or n/a)
+ ENTRY/EXIT PLAN: TP +X% / SL -Y% / max-hold Zm
+ WHY: 1-3 sentences citing the specific data points above.
+ CONFIDENCE: low | medium | high
+Never invent data. Cite only what the tools returned. If a tool fails, say so
+and default to PASS.
+
+PERSONA & STRATEGY: see the strategy block below.
+```
+
+### 10.2 Strategy blocks (swap in under the core)
+
+**Sniper** — catches new launches early.
+```
+STRATEGY: Sniper. Hunt brand-new launches (get_new_tokens) within minutes of
+mint. Edge = speed + creator/holder screening. Enter small and fast on launches
+with: known creator with >=1 prior graduation OR strong fresh momentum, dev
+holding under limit, socials present. TP aggressive (+50–150%), SL tight (-25%),
+max-hold short (minutes to low hours). Cut losers instantly; this is a volume
+game where a few winners pay for many small stops. Pass on anything you can't
+screen in time.
+```
+
+**Graduation Hunter** — plays the curve→AMM transition.
+```
+STRATEGY: Graduation Hunter. Target tokens 60–90% up the bonding curve
+(get_bonding_curve) with accelerating buy pressure and healthy holder spread.
+Thesis: graduation to AMM is a liquidity + attention event. Enter on the
+approach, scale out into/just after graduation. TP +40–80%, SL -20%, exit by
+graduation +N minutes regardless. Avoid tokens stalled below 50% for a long
+time — dead curves don't graduate.
+```
+
+**Swing** — holds graduated, liquid names.
+```
+STRATEGY: Swing. Only trade graduated AMM tokens with real liquidity and
+sustained volume. Use trade history and holder trends for entries on pullbacks
+within an uptrend. Wider stops (-30%), larger targets (+60–200%), max-hold
+hours-to-days. Fewer, higher-conviction trades. No illiquid curve tokens.
+```
+
+**Contrarian / Mean-Revert** — fades extremes.
+```
+STRATEGY: Contrarian. Look for capitulation on tokens with intact fundamentals
+(strong holder base, creator with graduations) — sharp dump on no bad news,
+seller exhaustion in trade flow. Buy fear, sell into the bounce. TP +30–60%,
+SL -20% (respect it — value traps are real on pump.fun). Skip anything where the
+dump is the creator/dev selling (get_token_holders + get_creator_profile).
+```
+
+**Copy-Leader** — a curated, conservative leader optimized to be *copied*.
+```
+STRATEGY: Copy-Leader. You are publicly copied; your job is to make FOLLOWERS
+money with risk they can stomach, not to maximize your own variance. Bias to
+liquid, screenable tokens. Position sizes scale cleanly so small followers can
+mirror you. Avoid trades that can't be safely copied (ultra-low liquidity, where
+your own size would move the price against followers). Communicate every trade's
+reasoning clearly — followers are trusting you. Drawdown discipline above all;
+one rug erases a hundred good calls in followers' eyes.
+```
+
+### 10.3 Research Analyst (scoring sub-agent, no trading)
+
+```
+You score a single pump.fun token for trade-worthiness. You do NOT trade. You
+return a structured verdict another agent acts on.
+
+Given a mint, gather: get_token_details, get_bonding_curve, get_token_holders,
+get_token_trades, get_creator_profile. Then return JSON:
+{
+ "mint": "<mint>",
+ "ticker": "$TICKER",
+ "score": 0-100,
+ "verdict": "strong" | "watch" | "avoid",
+ "signals": {
+ "graduation_pct": <num>, "liquidity_sol": <num>,
+ "top10_concentration_pct": <num>, "dev_holding_pct": <num>,
+ "buy_sell_ratio": <num>, "creator_graduations": <int>,
+ "fresh_wallet_ratio": <num>, "honeypot_risk": "low|med|high"
+ },
+ "rationale": "2-3 sentences, cite the numbers",
+ "red_flags": ["..."],
+ "suggested_entry": { "size_pct_of_budget": <num>, "tp_pct": <num>, "sl_pct": <num>, "max_hold_min": <num> }
+}
+Be skeptical. Default to "avoid" when data is missing or contradictory. Never
+fabricate a number — omit it and lower the score instead.
+```
+
+### 10.4 Avatar Narrator (the personality layer, entertainment)
+
+```
+You are the voice of a pump.fun trading agent's 3D avatar. After each trade
+decision, emit a SHORT, in-character line (<=12 words) plus a gesture/emote tag
+for the avatar. Stay literal about the trade; be entertaining about the delivery.
+Never give financial advice; you are narrating, not recommending.
+Format: { "say": "...", "gesture": "celebrate|shrug|sweat|point|wave", "emote": "..." }
+Examples (synthetic tokens only):
+ BUY → { "say": "Sniped $TICKER at 64% curve. Let's ride.", "gesture": "point", "emote": "focused" }
+ SELL win → { "say": "Out at 4.2x. Thank you, degens.", "gesture": "celebrate", "emote": "grin" }
+ STOP loss → { "say": "Stopped out -20%. Live to trade again.", "gesture": "shrug", "emote": "calm" }
+Tone per persona (sniper=cocky, swing=measured, contrarian=dry). Never reference
+any coin other than the one being traded or $THREE.
+```
+
+### 10.5 Risk Officer (independent veto, runs before every live buy)
+
+```
+You are an independent risk check that runs AFTER the trader decides BUY and
+BEFORE funds move. You can only APPROVE or VETO. Re-derive the trade against
+POLICY and the screens; do not trust the trader's summary — re-read the data.
+VETO if any: spend caps breached, slippage/price-impact over limit, holder
+concentration over limit, liquidity below floor, honeypot/sell-tax risk not
+"low", or the trade can't be cleanly copied at follower sizes (for copy-leaders).
+Return { "approve": bool, "reason": "...", "max_size_override": <amount|null> }.
+Default to VETO when uncertain. Capital preservation is your only mandate.
+```
+
+---
+
+## 11. Open product decisions (resolve before/while building)
+
+1. **Custody for copy-trade:** confirm Phase 1 = delegated session keys (rec) vs.
+ wait for an audited vault.
+2. **Default performance fee + split** (rec 15% fee, 70/20/10) — confirm or tune.
+3. **First surface to ship** (rec Arena + Profile) vs. jumping straight to copy.
+4. **Real vs. paper for v1 Arena leaders** — paper-trade to seed a credible board
+ without funded-signer risk, then graduate to real.
+5. **Mainnet funded signer path** — the recurring blocker; needs an ops decision.
diff --git a/pages/pump-visualizer.html b/pages/pump-visualizer.html
index 4a6926ba2..ed9cd2369 100644
--- a/pages/pump-visualizer.html
+++ b/pages/pump-visualizer.html
@@ -401,7 +401,8 @@
border-radius: 6px;
}
.vz-detail .links { display: flex; flex-wrap: wrap; gap: 6px; }
- .vz-detail .links a {
+ .vz-detail .links a,
+ .vz-detail .links button {
display: inline-flex; align-items: center; gap: 4px;
padding: 6px 10px; font-size: 12px;
border-radius: 6px;
@@ -409,12 +410,23 @@
color: var(--vz-text);
text-decoration: none;
background: rgba(255, 255, 255, 0.08);
- transition: background 0.15s;
- }
- .vz-detail .links a:hover { background: var(--accent-soft); }
- .vz-detail .links a.primary {
+ font: inherit; line-height: 1; cursor: pointer;
+ transition: background 0.15s, transform 0.12s, box-shadow 0.15s;
+ }
+ .vz-detail .links a:hover,
+ .vz-detail .links button:hover { background: var(--accent-soft); }
+ .vz-detail .links a:focus-visible,
+ .vz-detail .links button:focus-visible { outline: 2px solid var(--vz-accent); outline-offset: 2px; }
+ .vz-detail .links a.primary,
+ .vz-detail .links button.primary {
background: var(--vz-accent); color: #fff; border-color: var(--vz-accent);
+ font-weight: 600;
}
+ .vz-detail .links button.primary:hover {
+ background: var(--vz-accent); transform: translateY(-1px);
+ box-shadow: 0 0 18px rgba(255, 255, 255, 0.35);
+ }
+ .vz-detail .links button.primary:disabled { opacity: 0.6; cursor: default; transform: none; box-shadow: none; }
.vz-detail .live-badge {
display: inline-flex; align-items: center; gap: 6px;
padding: 3px 8px; font-size: 10px; letter-spacing: 0.06em;
@@ -539,6 +551,49 @@
padding: 18px 8px;
}
+ /* ── Market-cap tier key (bottom-right) ───────── */
+ .vz-ramp {
+ bottom: 16px;
+ right: 16px;
+ background: var(--vz-panel);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 10px;
+ padding: 10px 12px;
+ width: 172px;
+ font-family: var(--font-mono);
+ font-size: 11px;
+ }
+ .vz-ramp .head {
+ color: var(--vz-muted);
+ font-size: 10px; letter-spacing: 0.1em;
+ text-transform: uppercase;
+ padding-bottom: 6px; margin-bottom: 6px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ }
+ .vz-ramp .tier {
+ display: flex; align-items: center; gap: 8px;
+ padding: 3px 0;
+ color: var(--vz-muted);
+ }
+ .vz-ramp .tier .sw {
+ width: 10px; height: 10px; border-radius: 3px;
+ flex-shrink: 0;
+ }
+ .vz-ramp .tier .nm { color: var(--vz-text); }
+ .vz-ramp .tier .th {
+ margin-left: auto;
+ font-variant-numeric: tabular-nums;
+ }
+ .vz-ramp .move {
+ display: flex; gap: 12px;
+ margin-top: 8px; padding-top: 8px;
+ border-top: 1px solid rgba(255, 255, 255, 0.06);
+ color: var(--vz-muted);
+ }
+ .vz-ramp .move b { font-weight: 600; }
+ .vz-ramp .move .up b { color: var(--vz-green); }
+ .vz-ramp .move .down b { color: var(--vz-red); }
+
/* ── Intro / loading overlay ──────────────────── */
.vz-intro {
position: absolute;
@@ -618,6 +673,7 @@
}
@media (max-width: 720px) {
.vz-hint { display: none; }
+ .vz-ramp { display: none; }
.vz-legend { width: 200px; max-height: 180px; bottom: 12px; left: 12px; }
.vz-detail { width: 100%; }
.vz-status .stat { display: none; }
@@ -694,6 +750,16 @@
<ol id="vz-legend-list"></ol>
</aside>
+ <aside class="vz-overlay vz-ramp" id="vz-ramp" aria-label="Market-cap visual key" hidden>
+ <div class="head">Market cap → look</div>
+ <div id="vz-ramp-tiers"></div>
+ <div class="move">
+ <span class="up">▲ <b>up</b></span>
+ <span class="down">▼ <b>down</b></span>
+ <span style="margin-left:auto;color:var(--vz-muted)">on refresh</span>
+ </div>
+ </aside>
+
<aside class="vz-overlay vz-detail" id="vz-detail" aria-hidden="true">
<button class="close" type="button" id="vz-detail-close" aria-label="Close details">×</button>
<div class="head">
@@ -752,6 +818,28 @@
const FEED_LIVE_MIN_LOG = Math.log10(4_000); // $4k → smallest sphere
const FEED_LIVE_MAX_LOG = Math.log10(500_000); // $500k+ → biggest sphere
+ // ── market-cap tiers ─────────────────────────────────────────────
+ // Market cap drives a coin's entire look — not just its size. As a coin's
+ // cap climbs it shifts color (cool → hot), grows a crystalline wireframe
+ // cage with more facets, and spins/pulses with more energy. On a trending
+ // refresh, a coin that crossed into a higher tier visibly upgrades; one
+ // that fell downgrades — paired with the green/red move flash below.
+ const MCAP_TIERS = [
+ { name: 'Seed', min: 0, color: 0x3b82f6, emissive: 0x1d4ed8, cage: null, spin: 0.04, pulse: 0.10, pulseRate: 0.0020 },
+ { name: 'Rising', min: 30_000, color: 0x6366f1, emissive: 0x4338ca, cage: { detail: 0, scale: 1.42, color: 0x818cf8 }, spin: 0.10, pulse: 0.16, pulseRate: 0.0030 },
+ { name: 'Hot', min: 120_000, color: 0xa855f7, emissive: 0x7e22ce, cage: { detail: 1, scale: 1.45, color: 0xc084fc }, spin: 0.18, pulse: 0.24, pulseRate: 0.0042 },
+ { name: 'Breakout', min: 600_000, color: 0x34d399, emissive: 0x059669, cage: { detail: 2, scale: 1.48, color: 0x6ee7b7 }, spin: 0.30, pulse: 0.32, pulseRate: 0.0055 },
+ { name: 'Mega', min: 2_500_000, color: 0xfbbf24, emissive: 0xd97706, cage: { detail: 3, scale: 1.52, color: 0xfcd34d }, spin: 0.46, pulse: 0.42, pulseRate: 0.0070 },
+ ];
+ function tierForMcap(usd) {
+ const n = Number(usd) || 0;
+ let tier = MCAP_TIERS[0], index = 0;
+ for (let i = 0; i < MCAP_TIERS.length; i++) {
+ if (n >= MCAP_TIERS[i].min) { tier = MCAP_TIERS[i]; index = i; }
+ }
+ return { ...tier, index };
+ }
+
const host = document.getElementById('vz-canvas-host');
const statusEl = document.getElementById('vz-status');
const statusText = document.getElementById('vz-status-text');
@@ -970,22 +1058,44 @@
return token?.is_migration ? 0x34d399 : 0xf87171;
}
+ // Crystalline wireframe cage around higher-cap spheres. Facet count grows
+ // with the tier so "shape" reads as a function of market cap. Returned as
+ // a child of the sphere so it inherits position + spawn/hover scale; it
+ // spins on its own axis in the animation loop.
+ function buildTierCage(tier, radius) {
+ if (!tier.cage) return null;
+ const { detail, scale, color } = tier.cage;
+ const base = detail <= 0
+ ? new THREE.OctahedronGeometry(radius * scale, 0)
+ : new THREE.IcosahedronGeometry(radius * scale, Math.min(detail - 1, 2));
+ const wire = new THREE.WireframeGeometry(base);
+ base.dispose();
+ const mat = new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.55, depthWrite: false });
+ return new THREE.LineSegments(wire, mat);
+ }
+
function buildTokenMesh(token, position, radius) {
const fallback = fallbackTexture(token.symbol, token.mint);
const isLive = !!token.is_currently_live;
const glow = liveGlowHex(token);
+ const tier = tierForMcap(token.usd_market_cap);
const material = new THREE.MeshStandardMaterial({
map: fallback,
roughness: 0.45,
metalness: 0.25,
- emissive: isLive ? new THREE.Color(glow) : new THREE.Color(0x000000),
- emissiveIntensity: isLive ? 0.25 : 0,
+ // Live state owns the glow color (fresh = red, migrated = green);
+ // otherwise the market-cap tier tints the emissive.
+ emissive: isLive ? new THREE.Color(glow) : new THREE.Color(tier.emissive),
+ emissiveIntensity: isLive ? 0.25 : tier.pulse * 0.5,
});
const geometry = new THREE.SphereGeometry(radius, 28, 28);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(position);
mesh.scale.setScalar(0.001); // grow in during spawn animation
+ const cage = buildTierCage(tier, radius);
+ if (cage) mesh.add(cage); // child → follows the sphere's transform
+
// Selection / hover ring (hidden by default)
const ringGeo = new THREE.RingGeometry(radius * 1.18, radius * 1.32, 48);
const ringMat = new THREE.MeshBasicMaterial({
@@ -1012,7 +1122,7 @@
});
}
- return { mesh, ring, isLive };
+ return { mesh, ring, isLive, tier, cage };
}
function placeTokens(tokens) {
@@ -1025,13 +1135,15 @@
while (tokensGroup.children.length) {
const child = tokensGroup.children[0];
tokensGroup.remove(child);
- const isSprite = child.isSprite;
+ // Traverse so a sphere's tier-cage child is disposed alongside it.
// Sprites share a single geometry across instances — don't dispose it.
- if (!isSprite && child.geometry) child.geometry.dispose();
- if (child.material) {
- if (child.material.map) child.material.map.dispose();
- child.material.dispose();
- }
+ child.traverse((node) => {
+ if (node.geometry && !node.isSprite) node.geometry.dispose();
+ if (node.material) {
+ if (node.material.map) node.material.map.dispose();
+ node.material.dispose();
+ }
+ });
}
tokenMeshes.length = 0;
@@ -1053,7 +1165,7 @@
const p = points[i];
const position = new THREE.Vector3(p.x * shellR, p.y * shellR, p.z * shellR);
- const { mesh, ring, isLive } = buildTokenMesh(token, position, radius);
+ const { mesh, ring, isLive, tier, cage } = buildTokenMesh(token, position, radius);
tokensGroup.add(mesh);
tokensGroup.add(ring);
const prevMcap = previousMcaps.get(token.mint);
@@ -1067,9 +1179,11 @@
baseScale: 1,
radius,
isLive,
+ tier, cage,
spawnAt: spawnStart + i * 22, // ms — stagger reveals
spawned: false,
hoverScale: 1,
+ surge: 1,
visible: true,
label: null, // sprite, attached lazily for top-N
labelOffset: radius + 1.6,
@@ -1300,8 +1414,13 @@
const linksEl = document.getElementById('vz-detail-links');
linksEl.innerHTML = '';
if (token.mint) {
- // Primary action keeps the user inside three.ws — the full 3D coin page.
- linksEl.appendChild(linkNode(`/coin3d?mint=${encodeURIComponent(token.mint)}`, 'Open in 3D →', { primary: true, internal: true }));
+ // Primary action is the real on-chain buy — ape the coin without ever
+ // leaving the visualizer. The trade modal (src/game/coin-buy.js) builds
+ // the unsigned tx server-side, the connected Solana wallet signs it, and
+ // it settles through the same-origin RPC proxy. Lazy-loaded on click so
+ // the heavy Solana/pump SDKs never weigh down the visualizer bundle.
+ linksEl.appendChild(buyButtonNode(token));
+ linksEl.appendChild(linkNode(`/coin3d?mint=${encodeURIComponent(token.mint)}`, 'Open in 3D →', { internal: true }));
linksEl.appendChild(linkNode(`https://pump.fun/coin/${token.mint}`, 'Pump.fun ↗'));
linksEl.appendChild(linkNode(`https://solscan.io/token/${token.mint}`, 'Solscan ↗'));
}
@@ -1326,6 +1445,49 @@
return a;
}
+ // Primary "Buy" CTA for the detail panel. Opens the native on-chain trade
+ // modal for the selected coin — a real bonding-curve / AMM buy through the
+ // connected Solana wallet, not a redirect off-site. The heavy Solana + pump
+ // SDKs that power the modal are pulled in only on the first click.
+ let _tradeModuleP = null;
+ function buyButtonNode(token) {
+ const sym = token.symbol ? '$' + String(token.symbol).toUpperCase() : '';
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'primary';
+ btn.textContent = sym ? `Buy ${sym}` : 'Buy coin';
+ btn.setAttribute('aria-label', sym ? `Buy ${sym}` : 'Buy this coin');
+ btn.addEventListener('click', () => openTradeForToken(token, btn));
+ return btn;
+ }
+
+ async function openTradeForToken(token, btn) {
+ if (!token?.mint) return;
+ const restore = btn ? btn.textContent : null;
+ if (btn) { btn.disabled = true; btn.textContent = 'Loading…'; }
+ try {
+ if (!_tradeModuleP) _tradeModuleP = import('/src/game/coin-buy.js');
+ const { openBuyModal } = await _tradeModuleP;
+ openBuyModal({
+ mint: token.mint,
+ name: token.name || token.symbol || 'coin',
+ symbol: token.symbol || '',
+ image: proxiedImg(token.image_uri, token.mint || token.symbol) || '',
+ });
+ } catch (err) {
+ // Never strand the user on a dead button — surface the failure and let
+ // them retry, or fall back to the full coin page where they can also buy.
+ _tradeModuleP = null;
+ console.error('[pump-visualizer] trade modal failed to load', err);
+ if (btn) {
+ btn.textContent = 'Retry buy';
+ btn.disabled = false;
+ }
+ return;
+ }
+ if (btn) { btn.disabled = false; btn.textContent = restore; }
+ }
+
// ── formatters ───────────────────────────────────────────────
function formatMcap(v) {
const n = Number(v);
@@ -1520,7 +1682,21 @@
// Hover scale ease.
const wantHover = (entry === hovered || entry === selected) ? 1.18 : 1;
entry.hoverScale += (wantHover - entry.hoverScale) * 0.18;
- entry.mesh.scale.setScalar(entry.hoverScale);
+
+ // Market-cap tier motion — self-rotation plus an independently
+ // spinning cage, energy scaling with the tier. Bigger cap = livelier.
+ if (entry.tier) {
+ entry.mesh.rotation.y += entry.tier.spin * 0.01;
+ if (entry.cage) {
+ entry.cage.rotation.y -= entry.tier.spin * 0.014;
+ entry.cage.rotation.x += entry.tier.spin * 0.006;
+ }
+ }
+
+ // Move surge: the diff-flash pops this >1 when the cap rose between
+ // refreshes, <1 when it fell; here it eases back to rest each frame.
+ entry.surge += (1 - entry.surge) * 0.12;
+ entry.mesh.scale.setScalar(entry.hoverScale * entry.surge);
// Persistent tint by refresh-to-refresh delta — subtle wash on top of texture.
if (entry.deltaPct !== 0 && entry.mesh.material) {
@@ -1532,7 +1708,9 @@
}
}
- // Diff-flash: brief emissive burst right after refresh shows movement.
+ // Diff-flash: a refresh moved this coin's cap. Burst emissive green
+ // (up) or red (down), pop/dip the scale, and flare the cage — the
+ // "as it goes up / down" signal layered over the steady tier look.
if (entry.flashAt && time >= entry.flashAt) {
const fdt = time - entry.flashAt;
if (fdt < FLASH_DURATION_MS) {
@@ -1542,10 +1720,13 @@
const flashColor = positive ? new THREE.Color(0x34d399) : new THREE.Color(0xf87171);
entry.mesh.material.emissive.copy(flashColor);
entry.mesh.material.emissiveIntensity = burst;
+ entry.surge = 1 + (positive ? 1 : -1) * 0.14 * k;
+ if (entry.cage) entry.cage.material.opacity = Math.min(1, 0.55 + burst * 0.4);
} else {
entry.flashAt = 0;
- entry.mesh.material.emissive.copy(entry.isLive ? new THREE.Color(liveGlowHex(entry.data)) : new THREE.Color(0x000000));
- entry.mesh.material.emissiveIntensity = entry.isLive ? 0.25 : 0;
+ entry.mesh.material.emissive.copy(entry.isLive ? new THREE.Color(liveGlowHex(entry.data)) : new THREE.Color(entry.tier ? entry.tier.emissive : 0x000000));
+ entry.mesh.material.emissiveIntensity = entry.isLive ? 0.25 : (entry.tier ? entry.tier.pulse : 0);
+ if (entry.cage) entry.cage.material.opacity = 0.55;
}
}
@@ -1557,8 +1738,13 @@
entry.ring.material.opacity = 0.35 + pulse * 0.35;
}
entry.ring.scale.setScalar(entry.hoverScale * (1 + pulse * 0.06));
- } else if (entry !== selected) {
- entry.ring.scale.setScalar(entry.hoverScale);
+ } else {
+ // Non-live: breathe the emissive at the tier's own pace + intensity.
+ if (!entry.flashAt && entry.tier) {
+ const tp = 0.5 + 0.5 * Math.sin(time * entry.tier.pulseRate + entry.spawnAt * 0.0011);
+ entry.mesh.material.emissiveIntensity = entry.tier.pulse * (0.55 + tp * 0.9);
+ }
+ if (entry !== selected) entry.ring.scale.setScalar(entry.hoverScale);
}
// Sonar rings — emit a new one every ~1.4s while live; expand & fade existing.
@@ -1843,16 +2029,18 @@
const shellR = SPHERE_RADIUS * (0.80 + Math.random() * 0.22);
const position = new THREE.Vector3(p.x * shellR, p.y * shellR, p.z * shellR);
const radius = feedRadius(token.usd_market_cap);
- const { mesh, ring } = buildTokenMesh(token, position, radius);
+ const { mesh, ring, tier, cage } = buildTokenMesh(token, position, radius);
tokensGroup.add(mesh);
tokensGroup.add(ring);
const entry = {
mesh, ring, data: token,
baseScale: 1, radius,
isLive: true,
+ tier, cage,
spawnAt: performance.now(),
spawned: false,
hoverScale: 1,
+ surge: 1,
visible: true,
label: null,
labelOffset: radius + 1.6,
@@ -1899,6 +2087,11 @@
sr.material.dispose();
}
entry.sonarRings.length = 0;
+ if (entry.cage) {
+ entry.cage.geometry.dispose();
+ entry.cage.material.dispose();
+ entry.cage = null;
+ }
if (entry.mesh.geometry) entry.mesh.geometry.dispose();
if (entry.mesh.material) {
if (entry.mesh.material.map) entry.mesh.material.map.dispose();
@@ -1982,6 +2175,7 @@
if (!firstLoad) return;
firstLoad = false;
controlsEl.hidden = false;
+ rampEl.hidden = false;
introEl.classList.add('is-hidden');
setTimeout(() => { try { introEl.remove(); } catch {} }, 900);
startIntroFlyIn();
@@ -2152,6 +2346,7 @@
statusEl.dataset.state = 'ready';
refreshBtn.disabled = false;
controlsEl.hidden = false;
+ rampEl.hidden = false;
if (firstLoad) {
firstLoad = false;
@@ -2201,6 +2396,33 @@
}
});
+ // Market-cap tier key — built once from the same ladder the scene uses.
+ const rampEl = document.getElementById('vz-ramp');
+ (function buildTierRamp() {
+ const host = document.getElementById('vz-ramp-tiers');
+ const hex = (n) => '#' + n.toString(16).padStart(6, '0');
+ const fmt = (v) => formatMcap(v).replace('.0', '');
+ MCAP_TIERS.forEach((t, i) => {
+ const next = MCAP_TIERS[i + 1];
+ const row = document.createElement('div');
+ row.className = 'tier';
+ const sw = document.createElement('span');
+ sw.className = 'sw';
+ sw.style.background = hex(t.color);
+ sw.style.boxShadow = `0 0 8px ${hex(t.color)}`;
+ const nm = document.createElement('span');
+ nm.className = 'nm';
+ nm.textContent = t.name;
+ const th = document.createElement('span');
+ th.className = 'th';
+ if (t.min === 0) th.textContent = '< ' + fmt(next.min);
+ else if (next) th.textContent = fmt(t.min) + '–' + fmt(next.min);
+ else th.textContent = fmt(t.min) + '+';
+ row.append(sw, nm, th);
+ host.appendChild(row);
+ });
+ })();
+
// Boot in live-firehose mode.
enterFeedMode();
</script>
diff --git a/public/changelog.json b/public/changelog.json
index 85d3c5a5f..c411a44a6 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-15T20:59:54.552Z",
+ "generated_at": "2026-06-15T21:28:35.385Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -221,6 +221,16 @@
"fix"
]
},
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "Pump Visualizer: a coin's look now tracks its market cap",
+ "summary": "On the Pump Visualizer, market cap no longer just sizes a coin — it shapes its whole look. As a coin's cap climbs it shifts color from cool blue through purple to green and gold, grows a crystalline wireframe cage that gains facets at each tier, and spins and pulses with more energy. On the trending refresh, a coin that moved gets a clear signal: it flashes green and pops bigger when its cap rose, red and dips when it fell, and crossing into a higher or lower tier visibly upgrades or downgrades its shape and color. A new on-screen key in the corner maps each color and tier to its market-cap range so it all reads at a glance.",
+ "link": "/pump-visualizer",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-15",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index c097a533b..267f6504a 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -174,6 +174,14 @@
<category>improvement</category>
<description>The Pump Live showcase (three.ws/pump-live) — where a 3D agent reacts to brand-new pump.fun launches in real time — is now fully wired. Every new coin appears with its real artwork and a live USD market cap, instead of a generic avatar and a rough estimate. A new stats bar tracks tokens launched, initial-buy volume, and time since the last launch as events stream in. Before the first launch arrives you get a tidy loading skeleton instead of a blank panel; if the upstream stream drops, the feed reconnects on its own with a backoff and, if it stays down, shows a clear message with a Retry button. Token images are resolved and served through three.ws, so they always load cleanly and never trip browser security errors, and the page keeps streaming even on devices that can't run the 3D view.</description>
</item>
+ <item>
+ <title>Pump Visualizer: a coin's look now tracks its market cap</title>
+ <link>https://three.ws/pump-visualizer</link>
+ <guid isPermaLink="false">2026-06-15:Pump Visualizer: a coin's look now tracks its market cap</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>On the Pump Visualizer, market cap no longer just sizes a coin — it shapes its whole look. As a coin's cap climbs it shifts color from cool blue through purple to green and gold, grows a crystalline wireframe cage that gains facets at each tier, and spins and pulses with more energy. On the trending refresh, a coin that moved gets a clear signal: it flashes green and pops bigger when its cap rose, red and dips when it fell, and crossing into a higher or lower tier visibly upgrades or downgrades its shape and color. A new on-screen key in the corner maps each color and tier to its market-cap range so it all reads at a glance.</description>
+ </item>
<item>
<title>Pump Visualizer’s Trending view fixed — spheres now sized by real market cap</title>
<link>https://three.ws/pump-visualizer</link>
diff --git a/public/features.json b/public/features.json
index fd65e5796..1f3b993a6 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-15T20:59:54.541Z",
+ "generated_at": "2026-06-15T21:28:34.755Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/club-entrance.js b/src/club-entrance.js
index bcddb673c..5d9c5d095 100644
--- a/src/club-entrance.js
+++ b/src/club-entrance.js
@@ -59,11 +59,7 @@ const CAM_DIST = 3.6;
const CAM_HEIGHT = 1.55;
const HEAD_Y = 1.2;
-// Walk-through timeline (seconds), once the cover settles.
-const LEAVE = 1.3; // walk forward through the alley door
-const ENTER = 0.6; // fade the interior in
-const WALK = 4.4; // walk forward through the interior
-const ARRIVE = 0.9; // fade out, revealing the pole stage
+const ARRIVE = 0.9; // final fade (seconds) that reveals the pole stage
const isTouch = typeof window !== 'undefined' &&
('ontouchstart' in window || (navigator.maxTouchPoints || 0) > 0);
@@ -138,39 +134,54 @@ async function start(canvasEl) {
const loader = gltfLoader(renderer);
- // Walk the gallery tour + the avatar first; prefetch the alley and the
- // interior so each transition lands without waiting on a download.
- const [tourGltf, avatarGltf, manifest] = await Promise.all([
- loader.loadAsync(TOUR_URL),
+ // The journey, in order. You free-walk every one of these — no auto-walk.
+ // `cover` marks the venue whose door takes the cover charge (the outside
+ // alley); the rest just lead you to the next place. `door` anchors the exit
+ // to a modelled doorway (+ seals it) where one exists; interiors exit down
+ // their longest dimension. The last venue hands off to the strip club stage.
+ const SEQUENCE = [
+ { url: ALLEYWAY_URL, cover: true, door: true }, // outside — pay the cover here
+ { url: TOUR_URL, cover: false, door: false }, // gallery hall
+ { url: CLUBHOUSE_URL, cover: false, door: false }, // club interior → the poles
+ ];
+
+ // Land in the alley + the avatar first; prefetch the rest so each place is
+ // ready the moment you walk into it.
+ const [firstGltf, avatarGltf, manifest] = await Promise.all([
+ loader.loadAsync(SEQUENCE[0].url),
loader.loadAsync(AVATAR_URL),
fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => (r.ok ? r.json() : [])).catch(() => []),
]);
- const clubhousePromise = loader.loadAsync(CLUBHOUSE_URL);
- let alleyGltf = null;
- loader.loadAsync(ALLEYWAY_URL)
- .then((g) => { alleyGltf = g; })
- .catch((err) => { log.warn('[club-entrance] alley load failed', err); alleyGltf = 'error'; });
+ const loaded = SEQUENCE.map(() => null); // index-aligned gltf cache
+ loaded[0] = firstGltf;
+ for (let i = 1; i < SEQUENCE.length; i++) {
+ const idx = i;
+ loader.loadAsync(SEQUENCE[idx].url)
+ .then((g) => { loaded[idx] = g; })
+ .catch((err) => { log.warn(`[club-entrance] venue ${idx} load failed`, err); loaded[idx] = 'error'; });
+ }
// ── Environment ──────────────────────────────────────────────────────────
- // `cover` flags the venue whose door opens the cover card (the alley); the
- // tour's exit just advances you to the alley. Door-anchoring + the sealing
- // occluder only apply to the alley — the tour exits down its long axis.
+ let venueIndex = 0;
+ let paid = false;
let currentCover = false;
let env = null, doorAnchor = null, path = null, occluder = null;
- mountApproach(tourGltf.scene, { cover: false, useDoorAnchor: false });
+ mountVenue(0);
- function mountApproach(root, { cover, useDoorAnchor }) {
+ function mountVenue(i) {
+ const v = SEQUENCE[i];
if (occluder) { scene.remove(occluder); disposeObject(occluder); occluder = null; }
if (env) { disposeObject(env.root); scene.remove(env.root); }
- env = mountEnvironment(scene, root);
+ env = mountEnvironment(scene, loaded[i].scene);
// Anchor to the modelled door so the prompt + neon frame land on the real
- // doorway; the tour skips this and exits down its longest dimension.
- doorAnchor = useDoorAnchor ? findDoorAnchor(env.root) : null;
+ // doorway; interiors skip this and exit down their longest dimension.
+ doorAnchor = v.door ? findDoorAnchor(env.root) : null;
path = walkPath(env.box, doorAnchor);
// Seal the doorway so the lit interior never reads from outside.
occluder = doorAnchor ? buildDoorOccluder(doorAnchor, path.dir) : null;
if (occluder) scene.add(occluder);
- currentCover = cover;
+ currentCover = v.cover && !paid;
+ venueIndex = i;
}
// ── Avatar ─────────────────────────────────────────────────────────────
@@ -196,7 +207,6 @@ async function start(canvasEl) {
let camYaw = Math.atan2(path.dir.x, path.dir.z); // start looking down the alley toward the door
let camPitch = 0.12;
let inputEnabled = true;
- let autoWalk = false; // forced forward motion during the walk-through
// The pavement surface sits above the environment's y=0 origin, so stand the
// avatar on the sampled floor rather than the box bottom (feet-through-floor).
@@ -312,20 +322,27 @@ async function start(canvasEl) {
showHint(true);
showJoystick(isTouch);
- // Hint + prompt copy depend on the venue: the tour says "walk to the end",
- // the alley says "enter".
+ // Hint + prompt copy track where you are in the journey: the alley door takes
+ // the cover, the final place opens the stage, the rest just lead onward.
+ const isFinalVenue = () => venueIndex >= SEQUENCE.length - 1;
+ function doorLabel() {
+ if (currentCover) return 'Enter the club';
+ if (isFinalVenue()) return 'Enter the stage';
+ return 'Keep going';
+ }
function setHint() {
if (!hintEl) return;
- const tail = currentCover ? 'press E at the door' : 'walk to the end of the gallery';
- const tailTouch = currentCover ? 'walk to the door to enter' : 'walk to the end of the gallery';
+ const tail = currentCover ? 'walk to the door to enter'
+ : isFinalVenue() ? 'walk to the doors at the end' : 'walk to the far end to keep going';
hintEl.textContent = isTouch
- ? `Drag to move and look · ${tailTouch}`
+ ? `Drag to move and look · ${tail}`
: `WASD / arrows to move · drag to look · ${tail}`;
}
function setPromptLabel() {
if (!promptEl) return;
- promptEl.innerHTML = `${currentCover ? 'Enter the club' : 'Continue'} <kbd>E</kbd>`;
- promptEl.setAttribute('aria-label', currentCover ? 'Enter the club' : 'Continue into the alley');
+ const label = doorLabel();
+ promptEl.innerHTML = `${label} <kbd>E</kbd>`;
+ promptEl.setAttribute('aria-label', label);
}
let nearDoor = false;
@@ -336,29 +353,30 @@ async function start(canvasEl) {
showHint(false);
showJoystick(false);
if (currentCover) {
- // Hand off to the cover-charge card.
+ // Hand off to the cover-charge card; we resume on admit (onPaid).
window.dispatchEvent(new CustomEvent('club:enter-door'));
} else {
- // End of the gallery — walk on into the alley.
- advanceApproach();
+ advance();
}
}
- function advanceApproach() {
+ // Move on: the final place reveals the strip club (the pole stage); any other
+ // place fades out and the next one fades in for you to keep walking.
+ function advance() {
nearDoor = false;
- setPhase('toAlleyOut');
+ setPhase(isFinalVenue() ? 'arriving' : 'swapOut');
}
// Backed out of the cover card without paying — resume walking the alley.
window.addEventListener('club:leave-door', () => {
- if (phase !== 'alley') return;
+ if (phase !== 'walk') return;
inputEnabled = true;
showHint(true);
showJoystick(isTouch);
});
// ── State + render loop ──────────────────────────────────────────────────
- let phase = 'tour'; // tour → toAlleyOut → toAlleyIn → alley → leaving → swapping → entering → walking → arriving → done
+ let phase = 'walk'; // walk (any place) → swapOut → swapIn → walk … → arriving → done
let phaseStart = performance.now();
let raf = 0;
let last = performance.now();
@@ -372,11 +390,10 @@ async function start(canvasEl) {
last = now;
const elapsed = (now - phaseStart) / 1000;
- // Movement input (manual in the alley, forced during the walk-through).
+ // Movement is always yours — keyboard or joystick, in every place. We
+ // never walk the avatar for you.
let ix = 0, iz = 0;
- if (autoWalk) {
- iz = 1;
- } else if (inputEnabled) {
+ if (inputEnabled) {
if (keys.has('w') || keys.has('arrowup')) iz += 1;
if (keys.has('s') || keys.has('arrowdown')) iz -= 1;
if (keys.has('a') || keys.has('arrowleft')) ix -= 1;
@@ -391,7 +408,7 @@ async function start(canvasEl) {
key.position.set(rig.position.x, 5, rig.position.z + 1);
key.target.position.copy(rig.position).setY(1);
- if (phase === 'tour' || phase === 'alley') {
+ if (phase === 'walk') {
const d = Math.hypot(rig.position.x - path.door.x, rig.position.z - path.door.z);
const inRange = d < DOOR_RANGE;
if (inRange !== nearDoor) {
@@ -404,29 +421,31 @@ async function start(canvasEl) {
}
switch (phase) {
- case 'toAlleyOut': {
- // Fade the tour out, swap in the alley, then fade back in.
+ case 'swapOut': {
+ // Fade the current place out, mount the next, then fade it in.
const k = Math.min(1, elapsed / 0.6);
canvasEl.style.opacity = String(1 - k);
- if (k >= 1 && alleyGltf) {
- if (alleyGltf === 'error') {
- // Alley never loaded — skip straight to the cover card.
- setPhase('alley');
- window.dispatchEvent(new CustomEvent('club:enter-door'));
- } else {
- mountApproach(alleyGltf.scene, { cover: true, useDoorAnchor: true });
+ if (k >= 1) {
+ const next = loaded[venueIndex + 1];
+ if (next && next !== 'error') {
+ mountVenue(venueIndex + 1);
placeSpawn();
setHint();
- setPhase('toAlleyIn');
+ setPhase('swapIn');
+ } else if (next === 'error') {
+ // A place failed to load — don't strand the visitor; reveal
+ // the stage rather than hang on a black frame.
+ setPhase('arriving');
}
+ // else: still downloading — hold the fade until it resolves.
}
break;
}
- case 'toAlleyIn': {
+ case 'swapIn': {
const k = Math.min(1, elapsed / 0.5);
canvasEl.style.opacity = String(k);
if (k >= 1) {
- setPhase('alley');
+ setPhase('walk');
inputEnabled = true;
nearDoor = false;
showHint(true);
@@ -434,22 +453,8 @@ async function start(canvasEl) {
}
break;
}
- case 'leaving': {
- const k = Math.min(1, elapsed / LEAVE);
- canvasEl.style.opacity = String(1 - k);
- if (k >= 1) doSwap();
- break;
- }
- case 'entering': {
- const k = Math.min(1, elapsed / ENTER);
- canvasEl.style.opacity = String(k);
- if (k >= 1) setPhase('walking');
- break;
- }
- case 'walking':
- if (elapsed >= WALK) setPhase('arriving');
- break;
case 'arriving': {
+ // Final hand-off: fade out to reveal the strip club (src/club.js).
const k = Math.min(1, elapsed / ARRIVE);
canvasEl.style.opacity = String(1 - k);
if (k >= 1) return dispose();
@@ -504,38 +509,17 @@ async function start(canvasEl) {
camera.lookAt(target);
}
- function beginWalk() {
- if (phase !== 'alley') return;
- inputEnabled = false;
- autoWalk = true;
+ // Cover settled — the door is now just a doorway. Keep walking: fade out the
+ // alley and into the next place. (Input is already disabled from tryEnter.)
+ function onPaid() {
+ if (phase !== 'walk') return;
+ paid = true;
+ currentCover = false;
showPrompt(false); showHint(false); showJoystick(false);
- setPhase('leaving');
- }
- onAdmit = beginWalk;
- if (admitted) beginWalk();
-
- async function doSwap() {
- setPhase('swapping');
- canvasEl.style.opacity = '0';
- let clubScene = null;
- try {
- clubScene = (await clubhousePromise).scene;
- } catch (err) {
- log.warn('[club-entrance] club house load failed', err);
- return dispose();
- }
- scene.remove(doorMarker.group);
- disposeObject(doorMarker.group);
- if (occluder) { scene.remove(occluder); disposeObject(occluder); occluder = null; }
- doorGlow.intensity = 0;
- disposeObject(env.root);
- scene.remove(env.root);
- env = mountEnvironment(scene, clubScene);
- doorAnchor = findDoorAnchor(env.root);
- path = walkPath(env.box, doorAnchor);
- placeSpawn();
- setPhase('entering');
+ advance();
}
+ onAdmit = onPaid;
+ if (admitted) onPaid();
function onResize() {
renderer.setSize(window.innerWidth, window.innerHeight, false);
diff --git a/src/game/coin-buy.css b/src/game/coin-buy.css
new file mode 100644
index 000000000..1bbcdfd55
--- /dev/null
+++ b/src/game/coin-buy.css
@@ -0,0 +1,180 @@
+/* Native pump.fun trade modal — styles for the openBuyModal widget in
+ coin-buy.js. Imported by that module so the modal carries its own styles to
+ any surface that opens it (the /play world, the pump.fun visualizer, …),
+ not just pages that already load coincommunities.css.
+
+ The design tokens below are scoped to the modal root so the file is fully
+ self-contained: on /play they shadow the identical :root tokens from
+ coincommunities.css (same values, no visual change); on every other page
+ they are the sole definition, so the modal renders correctly standalone. */
+
+.cc-buy-overlay {
+ --cc-bg2: #101010;
+ --cc-panel-solid: #0c0c0c;
+ --cc-edge: rgba(255, 255, 255, 0.12);
+ --cc-edge-hi: rgba(255, 255, 255, 0.55);
+ --cc-text: #f5f5f6;
+ --cc-dim: #8c8c92;
+ --cc-faint: #5a5a60;
+ --cc-accent: #ffffff;
+ --cc-ink: #060607;
+ --cc-live: #ffffff;
+ --cc-shadow: 0 16px 50px rgba(0, 0, 0, 0.7);
+ --cc-glow: 0 0 14px rgba(255, 255, 255, 0.35);
+ --cc-radius: 4px;
+ --cc-radius-sm: 2px;
+}
+
+/* ── Native buy modal ───────────────────────────────────────────────────── */
+.cc-buy-overlay {
+ position: fixed; inset: 0; z-index: 80;
+ display: flex; align-items: center; justify-content: center; padding: 20px;
+ background: rgba(4, 4, 6, 0.66); backdrop-filter: blur(6px);
+ opacity: 0; transition: opacity 0.18s ease;
+}
+.cc-buy-overlay.cc-on { opacity: 1; }
+.cc-buy-card {
+ width: 100%; max-width: 380px;
+ background: var(--cc-panel-solid); border: 1px solid var(--cc-edge);
+ border-radius: var(--cc-radius); box-shadow: var(--cc-shadow);
+ padding: 18px; transform: translateY(10px) scale(0.99);
+ transition: transform 0.18s ease;
+}
+.cc-buy-overlay.cc-on .cc-buy-card { transform: translateY(0) scale(1); }
+.cc-buy-head { display: flex; align-items: center; gap: 11px; margin-bottom: 16px; }
+.cc-buy-img {
+ width: 40px; height: 40px; border-radius: var(--cc-radius-sm); object-fit: cover;
+ background: var(--cc-bg2); flex: none;
+}
+.cc-buy-img-ph { display: flex; align-items: center; justify-content: center; color: var(--cc-faint); font-size: 22px; }
+.cc-buy-titles { flex: 1; min-width: 0; }
+.cc-buy-name { font-weight: 800; font-size: 15px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.cc-buy-sub { display: flex; align-items: center; gap: 8px; margin-top: 2px; flex-wrap: wrap; }
+.cc-buy-sym { color: var(--cc-dim); font-size: 12px; }
+
+/* Lifecycle stage pill — a graduated coin must read as unmistakably different
+ from one still on the bonding curve. */
+.cc-buy-stage {
+ display: inline-flex; align-items: center; gap: 4px;
+ padding: 2px 8px; border-radius: 999px;
+ font-size: 10.5px; font-weight: 700; letter-spacing: 0.02em;
+ white-space: nowrap; border: 1px solid transparent;
+ transition: background 0.18s ease, border-color 0.18s ease, color 0.18s ease;
+}
+.cc-buy-stage[hidden] { display: none; }
+.cc-buy-stage-curve {
+ color: #d8c08a; background: rgba(216, 192, 138, 0.10); border-color: rgba(216, 192, 138, 0.32);
+}
+.cc-buy-stage-grad {
+ color: var(--cc-ink); background: var(--cc-accent); border-color: var(--cc-accent);
+ box-shadow: var(--cc-glow);
+}
+.cc-buy-x {
+ flex: none; width: 28px; height: 28px; border-radius: var(--cc-radius-sm);
+ background: none; border: 1px solid var(--cc-edge); color: var(--cc-dim);
+ cursor: pointer; font-size: 13px; line-height: 1; transition: border-color 0.12s ease, color 0.12s ease;
+}
+.cc-buy-x:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }
+
+/* Buy / Sell direction toggle. */
+.cc-buy-tabs {
+ display: flex; gap: 4px; margin-bottom: 16px; padding: 3px;
+ background: var(--cc-bg2); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+}
+.cc-buy-tab {
+ flex: 1; padding: 8px 0; background: none; border: 1px solid transparent;
+ border-radius: var(--cc-radius-sm); color: var(--cc-dim);
+ font-size: 13px; font-weight: 800; letter-spacing: 0.03em; cursor: pointer;
+ transition: color 0.12s ease, background 0.12s ease, border-color 0.12s ease;
+}
+.cc-buy-tab:hover { color: var(--cc-text); }
+.cc-buy-tab.cc-on { background: rgba(255, 255, 255, 0.08); border-color: var(--cc-edge-hi); color: var(--cc-text); }
+.cc-buy-tab:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+
+.cc-buy-field { display: block; }
+.cc-buy-field-label { display: block; color: var(--cc-dim); font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; margin-bottom: 7px; }
+.cc-buy-amount-wrap {
+ display: flex; align-items: center; gap: 8px;
+ background: var(--cc-bg2); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+ padding: 12px 14px; transition: border-color 0.12s ease;
+}
+.cc-buy-amount-wrap:focus-within { border-color: var(--cc-edge-hi); }
+.cc-buy-amount {
+ flex: 1; min-width: 0; background: none; border: none; outline: none;
+ color: var(--cc-text); font-size: 22px; font-weight: 800; font-variant-numeric: tabular-nums;
+}
+.cc-buy-amount::-webkit-outer-spin-button, .cc-buy-amount::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
+.cc-buy-amount { -moz-appearance: textfield; }
+.cc-buy-unit { color: var(--cc-dim); font-weight: 700; font-size: 14px; letter-spacing: 0.04em; }
+
+.cc-buy-presets { display: flex; gap: 7px; margin-top: 9px; }
+.cc-buy-preset {
+ flex: 1; padding: 8px 0; background: var(--cc-bg2); border: 1px solid var(--cc-edge);
+ border-radius: var(--cc-radius); color: var(--cc-dim); font-size: 12px; font-weight: 700;
+ cursor: pointer; transition: border-color 0.12s ease, color 0.12s ease, background 0.12s ease;
+}
+.cc-buy-preset:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }
+.cc-buy-preset.cc-on { background: rgba(255, 255, 255, 0.08); border-color: var(--cc-edge-hi); color: var(--cc-text); }
+
+/* Wallet balance / holdings line under the amount (USDC buys + all sells). */
+.cc-buy-bal {
+ display: flex; align-items: center; gap: 4px; margin-top: 10px;
+ color: var(--cc-dim); font-size: 12px; font-variant-numeric: tabular-nums;
+}
+.cc-buy-bal[hidden] { display: none; }
+.cc-buy-bal-warn { color: #d8c08a; }
+.cc-buy-bal-sep { color: var(--cc-faint); }
+
+.cc-buy-quote {
+ margin-top: 13px; min-height: 18px; font-size: 13px; color: var(--cc-text);
+ font-variant-numeric: tabular-nums; line-height: 1.4;
+}
+.cc-buy-quote-out { font-weight: 700; }
+.cc-buy-quote-impact { color: var(--cc-dim); }
+.cc-buy-quote-warn { color: #d8c08a; }
+.cc-buy-quote.cc-buy-quote-warn { font-size: 12px; }
+
+.cc-buy-slip { display: flex; align-items: center; gap: 7px; margin-top: 14px; }
+.cc-buy-slip-label { color: var(--cc-dim); font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; margin-right: auto; }
+.cc-buy-slip-btn {
+ padding: 5px 10px; background: var(--cc-bg2); border: 1px solid var(--cc-edge);
+ border-radius: var(--cc-radius-sm); color: var(--cc-dim); font-size: 12px; font-weight: 600;
+ font-variant-numeric: tabular-nums; cursor: pointer; transition: border-color 0.12s ease, color 0.12s ease;
+}
+.cc-buy-slip-btn:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }
+.cc-buy-slip-btn.cc-on { border-color: var(--cc-edge-hi); color: var(--cc-text); background: rgba(255, 255, 255, 0.06); }
+
+.cc-buy-wallet {
+ display: flex; align-items: center; gap: 7px; margin-top: 15px;
+ color: var(--cc-dim); font-size: 12px; font-variant-numeric: tabular-nums;
+}
+.cc-buy-wallet-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--cc-live); box-shadow: var(--cc-glow); flex: none; }
+.cc-buy-wallet-off { color: var(--cc-faint); }
+
+.cc-buy-cta {
+ width: 100%; margin-top: 14px; padding: 14px;
+ background: var(--cc-accent); color: var(--cc-ink);
+ border: 1px solid var(--cc-accent); border-radius: var(--cc-radius);
+ font-weight: 800; font-size: 14px; letter-spacing: 0.03em; cursor: pointer;
+ box-shadow: var(--cc-glow); transition: transform 0.12s ease, box-shadow 0.12s ease, opacity 0.12s ease;
+}
+.cc-buy-cta:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 0 22px rgba(255, 255, 255, 0.55); }
+.cc-buy-cta:active:not(:disabled) { transform: translateY(1px); }
+.cc-buy-cta:disabled { opacity: 0.45; cursor: default; box-shadow: none; }
+.cc-buy-cta:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+
+.cc-buy-status {
+ margin-top: 12px; font-size: 12.5px; line-height: 1.45; text-align: center;
+ color: var(--cc-dim); word-break: break-word;
+}
+.cc-buy-status[data-kind="ok"] { color: var(--cc-text); }
+.cc-buy-status[data-kind="err"] { color: #d88a8a; }
+.cc-buy-status a { color: inherit; text-decoration: underline; }
+.cc-buy-link { background: none; border: none; padding: 0; color: var(--cc-text); text-decoration: underline; cursor: pointer; font: inherit; }
+
+.cc-buy-pumplink {
+ display: block; margin-top: 14px; text-align: center;
+ color: var(--cc-dim); font-size: 12px; text-decoration: none;
+ transition: color 0.12s ease;
+}
+.cc-buy-pumplink:hover { color: var(--cc-text); }
diff --git a/src/game/coin-buy.js b/src/game/coin-buy.js
index ccbedab73..5ef5177bc 100644
--- a/src/game/coin-buy.js
+++ b/src/game/coin-buy.js
@@ -18,6 +18,7 @@
// SDK and @solana/web3.js are themselves imported on demand inside here, so the
// modal opens instantly and prices in the background.
+import './coin-buy.css';
import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';
const WSOL = 'So11111111111111111111111111111111111111112';
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index 74a5405de..8bd622ece 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -1026,159 +1026,10 @@ html, body {
#cc-toast[data-kind="warn"] { border-color: rgba(216, 192, 138, 0.5); }
#cc-toast[data-kind="success"] { border-color: rgba(138, 216, 168, 0.5); }
-/* ── Native buy modal ───────────────────────────────────────────────────── */
-.cc-buy-overlay {
- position: fixed; inset: 0; z-index: 80;
- display: flex; align-items: center; justify-content: center; padding: 20px;
- background: rgba(4, 4, 6, 0.66); backdrop-filter: blur(6px);
- opacity: 0; transition: opacity 0.18s ease;
-}
-.cc-buy-overlay.cc-on { opacity: 1; }
-.cc-buy-card {
- width: 100%; max-width: 380px;
- background: var(--cc-panel-solid); border: 1px solid var(--cc-edge);
- border-radius: var(--cc-radius); box-shadow: var(--cc-shadow);
- padding: 18px; transform: translateY(10px) scale(0.99);
- transition: transform 0.18s ease;
-}
-.cc-buy-overlay.cc-on .cc-buy-card { transform: translateY(0) scale(1); }
-.cc-buy-head { display: flex; align-items: center; gap: 11px; margin-bottom: 16px; }
-.cc-buy-img {
- width: 40px; height: 40px; border-radius: var(--cc-radius-sm); object-fit: cover;
- background: var(--cc-bg2); flex: none;
-}
-.cc-buy-img-ph { display: flex; align-items: center; justify-content: center; color: var(--cc-faint); font-size: 22px; }
-.cc-buy-titles { flex: 1; min-width: 0; }
-.cc-buy-name { font-weight: 800; font-size: 15px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.cc-buy-sub { display: flex; align-items: center; gap: 8px; margin-top: 2px; flex-wrap: wrap; }
-.cc-buy-sym { color: var(--cc-dim); font-size: 12px; }
-
-/* Lifecycle stage pill — a graduated coin must read as unmistakably different
- from one still on the bonding curve. */
-.cc-buy-stage {
- display: inline-flex; align-items: center; gap: 4px;
- padding: 2px 8px; border-radius: 999px;
- font-size: 10.5px; font-weight: 700; letter-spacing: 0.02em;
- white-space: nowrap; border: 1px solid transparent;
- transition: background 0.18s ease, border-color 0.18s ease, color 0.18s ease;
-}
-.cc-buy-stage[hidden] { display: none; }
-.cc-buy-stage-curve {
- color: #d8c08a; background: rgba(216, 192, 138, 0.10); border-color: rgba(216, 192, 138, 0.32);
-}
-.cc-buy-stage-grad {
- color: var(--cc-ink); background: var(--cc-accent); border-color: var(--cc-accent);
- box-shadow: var(--cc-glow);
-}
-.cc-buy-x {
- flex: none; width: 28px; height: 28px; border-radius: var(--cc-radius-sm);
- background: none; border: 1px solid var(--cc-edge); color: var(--cc-dim);
- cursor: pointer; font-size: 13px; line-height: 1; transition: border-color 0.12s ease, color 0.12s ease;
-}
-.cc-buy-x:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }
-
-/* Buy / Sell direction toggle. */
-.cc-buy-tabs {
- display: flex; gap: 4px; margin-bottom: 16px; padding: 3px;
- background: var(--cc-bg2); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
-}
-.cc-buy-tab {
- flex: 1; padding: 8px 0; background: none; border: 1px solid transparent;
- border-radius: var(--cc-radius-sm); color: var(--cc-dim);
- font-size: 13px; font-weight: 800; letter-spacing: 0.03em; cursor: pointer;
- transition: color 0.12s ease, background 0.12s ease, border-color 0.12s ease;
-}
-.cc-buy-tab:hover { color: var(--cc-text); }
-.cc-buy-tab.cc-on { background: rgba(255, 255, 255, 0.08); border-color: var(--cc-edge-hi); color: var(--cc-text); }
-.cc-buy-tab:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
-
-.cc-buy-field { display: block; }
-.cc-buy-field-label { display: block; color: var(--cc-dim); font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; margin-bottom: 7px; }
-.cc-buy-amount-wrap {
- display: flex; align-items: center; gap: 8px;
- background: var(--cc-bg2); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
- padding: 12px 14px; transition: border-color 0.12s ease;
-}
-.cc-buy-amount-wrap:focus-within { border-color: var(--cc-edge-hi); }
-.cc-buy-amount {
- flex: 1; min-width: 0; background: none; border: none; outline: none;
- color: var(--cc-text); font-size: 22px; font-weight: 800; font-variant-numeric: tabular-nums;
-}
-.cc-buy-amount::-webkit-outer-spin-button, .cc-buy-amount::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
-.cc-buy-amount { -moz-appearance: textfield; }
-.cc-buy-unit { color: var(--cc-dim); font-weight: 700; font-size: 14px; letter-spacing: 0.04em; }
-
-.cc-buy-presets { display: flex; gap: 7px; margin-top: 9px; }
-.cc-buy-preset {
- flex: 1; padding: 8px 0; background: var(--cc-bg2); border: 1px solid var(--cc-edge);
- border-radius: var(--cc-radius); color: var(--cc-dim); font-size: 12px; font-weight: 700;
- cursor: pointer; transition: border-color 0.12s ease, color 0.12s ease, background 0.12s ease;
-}
-.cc-buy-preset:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }
-.cc-buy-preset.cc-on { background: rgba(255, 255, 255, 0.08); border-color: var(--cc-edge-hi); color: var(--cc-text); }
-
-/* Wallet balance / holdings line under the amount (USDC buys + all sells). */
-.cc-buy-bal {
- display: flex; align-items: center; gap: 4px; margin-top: 10px;
- color: var(--cc-dim); font-size: 12px; font-variant-numeric: tabular-nums;
-}
-.cc-buy-bal[hidden] { display: none; }
-.cc-buy-bal-warn { color: #d8c08a; }
-.cc-buy-bal-sep { color: var(--cc-faint); }
-
-.cc-buy-quote {
- margin-top: 13px; min-height: 18px; font-size: 13px; color: var(--cc-text);
- font-variant-numeric: tabular-nums; line-height: 1.4;
-}
-.cc-buy-quote-out { font-weight: 700; }
-.cc-buy-quote-impact { color: var(--cc-dim); }
-.cc-buy-quote-warn { color: #d8c08a; }
-.cc-buy-quote.cc-buy-quote-warn { font-size: 12px; }
-
-.cc-buy-slip { display: flex; align-items: center; gap: 7px; margin-top: 14px; }
-.cc-buy-slip-label { color: var(--cc-dim); font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; margin-right: auto; }
-.cc-buy-slip-btn {
- padding: 5px 10px; background: var(--cc-bg2); border: 1px solid var(--cc-edge);
- border-radius: var(--cc-radius-sm); color: var(--cc-dim); font-size: 12px; font-weight: 600;
- font-variant-numeric: tabular-nums; cursor: pointer; transition: border-color 0.12s ease, color 0.12s ease;
-}
-.cc-buy-slip-btn:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); }
-.cc-buy-slip-btn.cc-on { border-color: var(--cc-edge-hi); color: var(--cc-text); background: rgba(255, 255, 255, 0.06); }
-
-.cc-buy-wallet {
- display: flex; align-items: center; gap: 7px; margin-top: 15px;
- color: var(--cc-dim); font-size: 12px; font-variant-numeric: tabular-nums;
-}
-.cc-buy-wallet-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--cc-live); box-shadow: var(--cc-glow); flex: none; }
-.cc-buy-wallet-off { color: var(--cc-faint); }
-
-.cc-buy-cta {
- width: 100%; margin-top: 14px; padding: 14px;
- background: var(--cc-accent); color: var(--cc-ink);
- border: 1px solid var(--cc-accent); border-radius: var(--cc-radius);
- font-weight: 800; font-size: 14px; letter-spacing: 0.03em; cursor: pointer;
- box-shadow: var(--cc-glow); transition: transform 0.12s ease, box-shadow 0.12s ease, opacity 0.12s ease;
-}
-.cc-buy-cta:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 0 22px rgba(255, 255, 255, 0.55); }
-.cc-buy-cta:active:not(:disabled) { transform: translateY(1px); }
-.cc-buy-cta:disabled { opacity: 0.45; cursor: default; box-shadow: none; }
-.cc-buy-cta:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
-
-.cc-buy-status {
- margin-top: 12px; font-size: 12.5px; line-height: 1.45; text-align: center;
- color: var(--cc-dim); word-break: break-word;
-}
-.cc-buy-status[data-kind="ok"] { color: var(--cc-text); }
-.cc-buy-status[data-kind="err"] { color: #d88a8a; }
-.cc-buy-status a { color: inherit; text-decoration: underline; }
-.cc-buy-link { background: none; border: none; padding: 0; color: var(--cc-text); text-decoration: underline; cursor: pointer; font: inherit; }
-
-.cc-buy-pumplink {
- display: block; margin-top: 14px; text-align: center;
- color: var(--cc-dim); font-size: 12px; text-decoration: none;
- transition: color 0.12s ease;
-}
-.cc-buy-pumplink:hover { color: var(--cc-text); }
+/* The native buy/sell modal (.cc-buy-overlay and descendants) ships its own
+ styles via src/game/coin-buy.css, imported by coin-buy.js when the modal is
+ opened — so it carries itself to any surface (the /play world, the pump.fun
+ visualizer, …), not only pages that load this stylesheet. */
@media (max-width: 640px) {
.cc-buy-btn-text { display: none; }
diff --git a/src/glb-canonicalize.js b/src/glb-canonicalize.js
index 8d9e24963..ba9e8e891 100644
--- a/src/glb-canonicalize.js
+++ b/src/glb-canonicalize.js
@@ -3,12 +3,14 @@
// pre-baked Mixamo animation library play on any rig variant.
//
// Handled name variants:
-// • Mixamo: `mixamorig:LeftArm`, `mixamorig1:LeftArm`, `mixamorigLeftArm`
-// • Blender: `Armature_LeftArm`, `Armature/LeftArm`
-// • Rigify: `DEF-LeftArm`, `ORG-LeftArm`, `MCH-LeftArm`
-// • snake_case: `left_arm`, `Left_Arm`
-// • kebab-case: `left-arm`
-// • lowercase: `leftarm`, `lefthand`
+// • Mixamo: `mixamorig:LeftArm`, `mixamorig1:LeftArm`, `mixamorigLeftArm`
+// • Blender: `Armature_LeftArm`, `Armature/LeftArm`
+// • Rigify: `DEF-LeftArm`, `ORG-LeftArm`, `MCH-LeftArm`
+// • CharacterStudio: `CH_Hips`, `CH_LeftUpLeg` (CH_ prefix stripped)
+// • Unreal mannequin: `pelvis`, `clavicle_l`, `upperarm_l`, `thigh_l`, `calf_l`, … (alias map)
+// • snake_case: `left_arm`, `Left_Arm`
+// • kebab-case: `left-arm`
+// • lowercase: `leftarm`, `lefthand`
//
// VRM-style names (`J_Bip_L_UpperArm`) and skeletons that aren't humanoid
// (quadrupeds, custom rigs) deliberately fall through unchanged — there's no
@@ -52,6 +54,24 @@ const LOOKUP = (() => {
return m;
})();
+// Unreal Engine mannequin skeleton → canonical aliases. UE names the same
+// joints `pelvis`, `clavicle_l`, `upperarm_l`, `thigh_l`, `calf_l`, `ball_l`,
+// … which share no spelling with the canonical/Mixamo set. Keyed by the same
+// separator-stripped lowercase form `_lookupBone` produces (`clavicle_l` →
+// `claviclel`). The spine chain (`spine_01/02/03`) is deliberately OMITTED:
+// its stripped form `spine02` collides with Mixamo's `Spine` + `_02` de-dup
+// suffix, which canonicalizeBoneName already resolves to `Spine`. The torso
+// then rides on `Hips` while every limb, foot, and the neck retarget cleanly —
+// well above the 8-bone floor a readable performance needs.
+const UNREAL_ALIASES = new Map(Object.entries({
+ pelvis: 'Hips',
+ neck01: 'Neck',
+ claviclel: 'LeftShoulder', upperarml: 'LeftArm', lowerarml: 'LeftForeArm', handl: 'LeftHand',
+ clavicler: 'RightShoulder', upperarmr: 'RightArm', lowerarmr: 'RightForeArm', handr: 'RightHand',
+ thighl: 'LeftUpLeg', calfl: 'LeftLeg', footl: 'LeftFoot', balll: 'LeftToeBase',
+ thighr: 'RightUpLeg', calfr: 'RightLeg', footr: 'RightFoot', ballr: 'RightToeBase',
+}));
+
/**
* Reduce a bone name to its canonical three.ws form, or null if it doesn't
* correspond to a recognised humanoid bone.
@@ -83,10 +103,14 @@ function _lookupBone(name) {
s = s.replace(/^mixamorig\d*[_:]?/i, '');
s = s.replace(/^Armature[_/]?/i, '');
s = s.replace(/^(DEF|ORG|MCH)[-_]/i, '');
+ // CharacterStudio exports prefix every joint `CH_` (`CH_Hips`, `CH_LeftUpLeg`),
+ // whose stems are otherwise canonical — strip it like any other vendor prefix.
+ s = s.replace(/^CH[_:]/i, '');
// Collapse separators so `Left_Arm`, `left-arm`, `left arm`, `LeftArm` all
// reach the same lookup key.
const key = s.replace(/[-_\s]+/g, '').toLowerCase();
- return LOOKUP.get(key) ?? null;
+ // Canonical/Mixamo/Rigify spellings first, then the Unreal-mannequin aliases.
+ return LOOKUP.get(key) ?? UNREAL_ALIASES.get(key) ?? null;
}
/**
diff --git a/src/three-economy.js b/src/three-economy.js
index b05a66102..98b856c2c 100644
--- a/src/three-economy.js
+++ b/src/three-economy.js
@@ -37,6 +37,10 @@ const atomicsToTokens = (atomics, decimals = 6) => {
return 0;
}
};
+const shortAddr = (a) => {
+ const s = String(a || '');
+ return s.length > 9 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;
+};
async function getJSON(path, opts = {}) {
const r = await fetch(path, { credentials: 'include', ...opts });
@@ -108,6 +112,18 @@ function injectStyles() {
@keyframes ec-sh { 0%{background-position:200% 0} 100%{background-position:-200% 0} }
.ec-err { border:1px solid #3a1f1f; background:#1a0e0e; color:#ff9b9b; border-radius:12px; padding:16px; font-size:13.5px; }
.ec-muted { color:#8a8a93; }
+ .ec-wallets { grid-template-columns:repeat(auto-fit,minmax(240px,1fr)); }
+ .ec-wallet { display:block; border:1px solid #1c1c22; border-radius:14px; padding:18px; background:linear-gradient(180deg,#101015,#0c0c10); transition:border-color .15s,transform .12s; }
+ a.ec-wallet:hover { border-color:#7ee787; transform:translateY(-2px); }
+ .ec-wallet .wlabel { font-size:12.5px; color:#8a8a93; }
+ .ec-wallet .wbal { font-size:24px; font-weight:800; letter-spacing:-0.02em; margin:4px 0 6px; }
+ .ec-wallet .waddr { font-family:ui-monospace,Menlo,monospace; font-size:11.5px; color:#7ee787; }
+ .ec-reflect-head { display:flex; flex-direction:column; gap:2px; }
+ .ec-reflect-head .v { font-size:30px; font-weight:850; letter-spacing:-0.02em; color:#7ee787; }
+ .ec-reflect-head .k { color:#8a8a93; font-size:13.5px; }
+ .ec-reflect-list { margin-top:14px; border:1px solid #1a1a20; border-radius:12px; overflow:hidden; }
+ .ec-reflect-row { display:flex; justify-content:space-between; gap:12px; padding:11px 14px; font-size:13px; border-bottom:1px solid #15151a; }
+ .ec-reflect-row:last-child { border-bottom:none; }
@media (prefers-reduced-motion: reduce){ .ec-skel{ animation:none } .ec-btn:hover,.ec-tier:hover{ transform:none } }
`;
const el = document.createElement('style');
@@ -149,6 +165,51 @@ function statsHTML(stats) {
.join('')}</div>`;
}
+// Verifiable on-chain panel — the wallets anyone can inspect. This is the answer
+// to "trust us, we burned some": here are the addresses, check them yourself.
+function onchainHTML(stats) {
+ const dec = stats?.token?.decimals ?? 6;
+ const sym = stats?.token?.symbol ?? '$THREE';
+ const oc = stats?.onchain || {};
+ const wallet = (w, label) => {
+ if (!w?.address) {
+ return `<div class="ec-wallet"><div class="wlabel">${esc(label)}</div><div class="wbal ec-muted">not configured</div></div>`;
+ }
+ const bal = fmtCompact(atomicsToTokens(w.balance_atomics ?? '0', dec));
+ return `<a class="ec-wallet" href="${esc(w.explorer)}" target="_blank" rel="noopener">
+ <div class="wlabel">${esc(label)}</div>
+ <div class="wbal">${esc(bal)} ${esc(sym)}</div>
+ <div class="waddr">${esc(shortAddr(w.address))} · verify on Solscan ↗</div>
+ </a>`;
+ };
+ return `<div class="ec-grid ec-wallets">
+ ${wallet(oc.treasury, 'Treasury → buybacks')}
+ ${wallet(oc.rewards_pool, 'Holder rewards pool')}
+ </div>`;
+}
+
+// Reflected-to-holders panel — real $THREE returned to holders, with run history.
+// Beats a static "0.5% burned" counter: this is value RETURNED, not destroyed.
+function reflectedHTML(stats) {
+ const dec = stats?.token?.decimals ?? 6;
+ const sym = stats?.token?.symbol ?? '$THREE';
+ const r = stats?.reflected || { total_atomics: '0', run_count: 0, recent: [] };
+ const total = fmtCompact(atomicsToTokens(r.total_atomics ?? '0', dec));
+ const head = `<div class="ec-reflect-head"><div class="v">${esc(total)} ${esc(sym)}</div><div class="k">returned to holders across ${r.run_count} distribution${r.run_count === 1 ? '' : 's'} — never burned</div></div>`;
+ if (!r.recent?.length) {
+ return `${head}<p class="ec-muted" style="margin-top:12px">Distributions begin once the rewards pool funds. Every run will be listed here with an on-chain transaction you can verify.</p>`;
+ }
+ const rows = r.recent
+ .map((d) => {
+ const amt = fmtCompact(atomicsToTokens(d.distributed_atomics ?? '0', dec));
+ const when = d.created_at ? new Date(d.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '';
+ const status = d.status === 'completed' ? '✓ paid' : 'planned';
+ return `<div class="ec-reflect-row"><span>${esc(when)}</span><span>${esc(amt)} ${esc(sym)} → ${d.holder_count} holders</span><span class="ec-muted">${esc(status)}</span></div>`;
+ })
+ .join('');
+ return `${head}<div class="ec-reflect-list">${rows}</div>`;
+}
+
function tiersHTML(tierData) {
const ladder = tierData?.ladder || [];
const currentLevel = tierData?.tier?.level ?? null;
diff --git a/tests/agent-sniper-claim-scorer.test.js b/tests/agent-sniper-claim-scorer.test.js
new file mode 100644
index 000000000..009079a96
--- /dev/null
+++ b/tests/agent-sniper-claim-scorer.test.js
@@ -0,0 +1,66 @@
+import { describe, it, expect } from 'vitest';
+import { scoreClaim } from '../workers/agent-sniper/claim-scorer.js';
+
+function claim(overrides = {}) {
+ return {
+ creator: 'Creator1111111111111111111111111111111111111',
+ mint: 'THREEsynthetic1111111111111111111111111111111',
+ signature: 'sig_abc',
+ lamports: 2_000_000_000, // 2 SOL
+ ts: 1000,
+ ...overrides,
+ };
+}
+
+const ONE_SOL = 1_000_000_000;
+
+describe('scoreClaim — first-claim entry filter', () => {
+ it('skips a claim with no resolvable mint', () => {
+ const r = scoreClaim(claim({ mint: '' }), {});
+ expect(r.pass).toBe(false);
+ expect(r.reasons).toContain('no_mint');
+ });
+
+ it('passes when no claim-size filters are set', () => {
+ const r = scoreClaim(claim(), {});
+ expect(r.pass).toBe(true);
+ });
+
+ it('rejects a claim below min_claim_lamports', () => {
+ const r = scoreClaim(claim({ lamports: ONE_SOL }), { min_claim_lamports: '1500000000' });
+ expect(r.pass).toBe(false);
+ expect(r.reasons).toContain('claim_below_min');
+ });
+
+ it('rejects a claim above max_claim_lamports', () => {
+ const r = scoreClaim(claim({ lamports: 5 * ONE_SOL }), { max_claim_lamports: '3000000000' });
+ expect(r.pass).toBe(false);
+ expect(r.reasons).toContain('claim_above_max');
+ });
+
+ it('passes a claim inside [min,max]', () => {
+ const r = scoreClaim(claim({ lamports: 2 * ONE_SOL }), {
+ min_claim_lamports: '1000000000',
+ max_claim_lamports: '3000000000',
+ });
+ expect(r.pass).toBe(true);
+ expect(r.reasons.some((x) => x.startsWith('first_claim_sol:'))).toBe(true);
+ });
+
+ it('treats min exactly equal to the claim as a pass (inclusive floor)', () => {
+ const r = scoreClaim(claim({ lamports: ONE_SOL }), { min_claim_lamports: '1000000000' });
+ expect(r.pass).toBe(true);
+ });
+
+ it('handles a missing/zero lamports amount without throwing', () => {
+ const r = scoreClaim(claim({ lamports: 0 }), { min_claim_lamports: '1' });
+ expect(r.pass).toBe(false);
+ expect(r.reasons).toContain('claim_below_min');
+ });
+
+ it('ignores numeric column values coming back from postgres as decimals', () => {
+ // numeric(40,0) can arrive as a string; bigOrNull must tolerate it.
+ const r = scoreClaim(claim({ lamports: 2 * ONE_SOL }), { min_claim_lamports: '1000000000.0' });
+ expect(r.pass).toBe(true);
+ });
+});
diff --git a/tests/glb-canonicalize.test.js b/tests/glb-canonicalize.test.js
index 410ff5e16..f04b73cac 100644
--- a/tests/glb-canonicalize.test.js
+++ b/tests/glb-canonicalize.test.js
@@ -141,6 +141,45 @@ describe('canonicalizeBoneName', () => {
expect(canonicalizeBoneName('DEF-left_fore_arm')).toBe('LeftForeArm');
});
+ // CharacterStudio prefixes every joint `CH_`; the stems are otherwise
+ // canonical, so stripping the prefix makes the whole rig drivable.
+ it.each([
+ ['CH_Hips', 'Hips'],
+ ['CH_LeftUpLeg', 'LeftUpLeg'],
+ ['CH_RightFoot', 'RightFoot'],
+ ['CH_Hips_01', 'Hips'], // CH_ prefix + glTF de-dup suffix
+ ['CH_LeftLeg_03', 'LeftLeg'],
+ ])('strips the CharacterStudio CH_ prefix: %s → %s', (input, expected) => {
+ expect(canonicalizeBoneName(input)).toBe(expected);
+ });
+
+ // Unreal Engine mannequin joint names map onto canonical bones via the
+ // alias table. The `_l`/`_r` side suffix is preserved through the collapse.
+ it.each([
+ ['pelvis', 'Hips'],
+ ['pelvis_09', 'Hips'], // UE name + de-dup suffix
+ ['clavicle_l', 'LeftShoulder'],
+ ['upperarm_l', 'LeftArm'],
+ ['lowerarm_r', 'RightForeArm'],
+ ['hand_r', 'RightHand'],
+ ['thigh_l', 'LeftUpLeg'],
+ ['calf_l', 'LeftLeg'],
+ ['foot_r', 'RightFoot'],
+ ['ball_l', 'LeftToeBase'],
+ ['thigh_l_010', 'LeftUpLeg'], // UE name + de-dup suffix
+ ])('maps Unreal mannequin bones: %s → %s', (input, expected) => {
+ expect(canonicalizeBoneName(input)).toBe(expected);
+ });
+
+ // The Unreal spine chain is intentionally NOT aliased — `spine_02`'s
+ // stripped form collides with Mixamo's `Spine` + `_02` de-dup, which must
+ // keep resolving to `Spine` (asserted in the de-dup suite above). Guard it
+ // here so a future alias addition can't silently break that.
+ it('does not alias the Unreal spine chain (avoids Mixamo de-dup collision)', () => {
+ expect(canonicalizeBoneName('mixamorig:Spine_02')).toBe('Spine');
+ expect(canonicalizeBoneName('mixamorig:Spine_03')).toBe('Spine');
+ });
+
// glTF/FBX exporters (CharacterStudio, Blender, FBX2glTF) append a `_NN`
// node-de-dup index to keep names unique. These are the bone names that ship
// in real uploaded avatars — without stripping the suffix the whole animation
diff --git a/workers/agent-sniper/claim-scorer.js b/workers/agent-sniper/claim-scorer.js
new file mode 100644
index 000000000..e4f0b1572
--- /dev/null
+++ b/workers/agent-sniper/claim-scorer.js
@@ -0,0 +1,45 @@
+// agent-sniper — first-claim entry scoring. Pure, no I/O.
+//
+// Given a first-claim event (from scanFirstClaims) and a first_claim strategy
+// row, decide whether the agent should snipe the claimed coin. Mirrors
+// scorer.js for the new-mint path: returns { pass, reasons }, and `reasons`
+// always explains the verdict so the logs show WHY a claim was acted on or
+// skipped.
+
+function bigOrNull(v) {
+ if (v == null || v === '') return null;
+ try {
+ return BigInt(String(v).split('.')[0]);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * @param {{creator:string, mint:string, signature:string, lamports:number, ts:number}} claim
+ * @param {object} strat agent_sniper_strategies row (trigger = 'first_claim')
+ * @returns {{ pass: boolean, reasons: string[] }}
+ */
+export function scoreClaim(claim, strat) {
+ const reasons = [];
+
+ // A claim with no resolvable coin mint isn't snipeable — nothing to buy.
+ if (!claim.mint) return { pass: false, reasons: ['no_mint'] };
+
+ const lamports = (() => {
+ const n = Number(claim.lamports);
+ return Number.isFinite(n) && n > 0 ? BigInt(Math.floor(n)) : 0n;
+ })();
+
+ const minClaim = bigOrNull(strat.min_claim_lamports);
+ const maxClaim = bigOrNull(strat.max_claim_lamports);
+ if (minClaim != null && lamports < minClaim) {
+ return { pass: false, reasons: ['claim_below_min'] };
+ }
+ if (maxClaim != null && lamports > maxClaim) {
+ return { pass: false, reasons: ['claim_above_max'] };
+ }
+
+ reasons.push(`first_claim_sol:${(Number(lamports) / 1e9).toFixed(4)}`);
+ return { pass: true, reasons };
+}
diff --git a/workers/agent-sniper/config.js b/workers/agent-sniper/config.js
index 55b7da518..31b66d609 100644
--- a/workers/agent-sniper/config.js
+++ b/workers/agent-sniper/config.js
@@ -66,5 +66,15 @@ export function loadConfig() {
feedWatchdogMs: Math.max(30_000, num('SNIPER_FEED_WATCHDOG_MS', 180_000)),
// Confirmation timeout for a broadcast trade.
confirmTimeoutMs: Math.max(15_000, num('SNIPER_CONFIRM_TIMEOUT_MS', 60_000)),
+ // ── first-claim trigger ─────────────────────────────────────────────────
+ // How often to poll the on-chain fee-claim stream for first-ever claims.
+ claimPollMs: Math.max(10_000, num('SNIPER_CLAIM_POLL_MS', 30_000)),
+ // Window scanned each poll — must comfortably exceed the poll interval so a
+ // claim can't slip between scans.
+ claimLookbackSeconds: Math.max(60, num('SNIPER_CLAIM_LOOKBACK_S', 600)),
+ // Default freshness gate: ignore a first claim older than this when first
+ // observed (a per-strategy first_claim_max_age_seconds overrides it). Keeps
+ // a worker restart / backfill from sniping a stale claim.
+ claimMaxAgeSeconds: Math.max(30, num('SNIPER_CLAIM_MAX_AGE_S', 300)),
};
}
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index 314fea0b1..b26b81997 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -61,9 +61,11 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
// 4. idempotency lock — claim the (agent,mint,network) slot BEFORE the tx.
const claimed = await sql`
INSERT INTO agent_sniper_positions
- (strategy_id, agent_id, user_id, wallet, network, mint, symbol, name, status)
+ (strategy_id, agent_id, user_id, wallet, network, mint, symbol, name, status,
+ entry_trigger, trigger_ref)
VALUES (${strat.id}, ${strat.agent_id}, ${strat.user_id}, ${'pending'}, ${cfg.network},
- ${mint.mint}, ${mint.symbol || null}, ${mint.name || null}, 'opening')
+ ${mint.mint}, ${mint.symbol || null}, ${mint.name || null}, 'opening',
+ ${mint.entry_trigger || 'new_mint'}, ${mint.trigger_ref || null})
ON CONFLICT (agent_id, mint, network) DO NOTHING
RETURNING id
`;
diff --git a/workers/agent-sniper/first-claim-watch.js b/workers/agent-sniper/first-claim-watch.js
new file mode 100644
index 000000000..4925abeea
--- /dev/null
+++ b/workers/agent-sniper/first-claim-watch.js
@@ -0,0 +1,123 @@
+// agent-sniper — the first-claim trigger.
+//
+// A second source of snipes, parallel to the PumpPortal new-mint feed. Instead
+// of reacting to launches, this polls the on-chain pump.fun fee-claim stream and
+// fires when a creator pulls their accrued rewards for the FIRST time EVER — an
+// irreversible "the creator is live and taking real fees" signal. Each first
+// claim is scored against every armed `first_claim` strategy, held for the
+// owner-set delay, then routed through the SAME executeBuy path as a new-mint
+// snipe (same guardrails, same idempotency lock, same position lifecycle).
+//
+// Dedupe is two-layered: an in-process `seen` set skips re-scoring a claim we
+// already handled this run, and the executor's INSERT … ON CONFLICT
+// (agent, mint, network) is the durable guarantee that a coin is sniped once.
+
+import { scanFirstClaims } from '../../api/_lib/pump-claims.js';
+import { scoreClaim } from './claim-scorer.js';
+import { executeBuy } from './executor.js';
+import { cachedStrategies } from './strategy-store.js';
+import { log } from './log.js';
+
+const MAX_SEEN = 5000; // cap the dedupe set; prune oldest in bulk when exceeded.
+
+function firstClaimStrategies() {
+ return cachedStrategies().filter((s) => s.trigger === 'first_claim');
+}
+
+/**
+ * Start the first-claim poll loop. Returns a stop() that clears the interval and
+ * every pending delayed-buy timer.
+ *
+ * @param {object} o
+ * @param {object} o.cfg loadConfig() result
+ * @param {{push:Function}} o.queue bounded buy queue from index.js
+ * @param {{tryConsume:Function}} o.throttle global buy throttle from index.js
+ * @param {() => boolean} o.isHalted true when draining or the global kill is set
+ */
+export function startFirstClaimWatch({ cfg, queue, throttle, isHalted }) {
+ const seen = new Set();
+ const timers = new Set();
+ let scanning = false;
+
+ const scheduleBuy = (strat, candidate) => {
+ const delay = Math.max(0, Math.min(600_000, Number(strat.buy_delay_ms) || 0));
+ if (delay === 0) {
+ if (!isHalted()) queue.push(() => executeBuy({ cfg, strat, mint: candidate, throttle }));
+ return;
+ }
+ const timer = setTimeout(() => {
+ timers.delete(timer);
+ if (isHalted()) return;
+ log.info('first-claim buy (delayed)', {
+ agent: strat.agent_id, mint: candidate.mint, delayMs: delay,
+ });
+ queue.push(() => executeBuy({ cfg, strat, mint: candidate, throttle }));
+ }, delay);
+ if (timer.unref) timer.unref();
+ timers.add(timer);
+ };
+
+ const tick = async () => {
+ if (scanning || isHalted()) return;
+ const strategies = firstClaimStrategies();
+ if (!strategies.length) return;
+ scanning = true;
+ try {
+ const nowTs = Math.floor(Date.now() / 1000);
+ const sinceTs = nowTs - cfg.claimLookbackSeconds;
+ const items = await scanFirstClaims({ sinceTs, limit: 50 });
+ for (const item of items) {
+ if (seen.has(item.signature)) continue;
+ seen.add(item.signature);
+ const age = nowTs - (Number(item.ts) || 0);
+ for (const strat of strategies) {
+ const maxAge = Number(strat.first_claim_max_age_seconds) || cfg.claimMaxAgeSeconds;
+ if (age > maxAge) {
+ log.info('skip', { agent: strat.agent_id, mint: item.mint, reason: 'claim_stale', ageS: age });
+ continue;
+ }
+ const { pass, reasons } = scoreClaim(item, strat);
+ if (!pass) {
+ log.info('skip', { agent: strat.agent_id, mint: item.mint, reason: reasons[0] });
+ continue;
+ }
+ log.info('first-claim candidate', {
+ agent: strat.agent_id, mint: item.mint, creator: item.creator, sig: item.signature, reasons,
+ });
+ scheduleBuy(strat, {
+ mint: item.mint,
+ symbol: null,
+ name: null,
+ entry_trigger: 'first_claim',
+ trigger_ref: item.signature,
+ });
+ }
+ }
+ pruneSeen(seen);
+ } catch (err) {
+ log.error('first-claim scan failed', { err: err?.message });
+ } finally {
+ scanning = false;
+ }
+ };
+
+ const interval = setInterval(() => { tick().catch((err) => log.error('first-claim tick crashed', { err: err?.message })); }, cfg.claimPollMs);
+ if (interval.unref) interval.unref();
+ log.info('first-claim watch armed', { pollMs: cfg.claimPollMs, lookbackS: cfg.claimLookbackSeconds });
+
+ return function stop() {
+ clearInterval(interval);
+ for (const t of timers) clearTimeout(t);
+ timers.clear();
+ };
+}
+
+function pruneSeen(seen) {
+ if (seen.size <= MAX_SEEN) return;
+ const drop = seen.size - Math.floor(MAX_SEEN / 2);
+ let i = 0;
+ for (const sig of seen) {
+ seen.delete(sig);
+ if (++i >= drop) break;
+ }
+}
diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.js
index 665a58883..974992fb8 100644
--- a/workers/agent-sniper/index.js
+++ b/workers/agent-sniper/index.js
@@ -16,6 +16,7 @@ import { refreshStrategies, cachedStrategies, logStrategyLoad } from './strategy
import { scoreMint } from './scorer.js';
import { executeBuy } from './executor.js';
import { runPositionSweep } from './positions.js';
+import { startFirstClaimWatch } from './first-claim-watch.js';
// ── global buy throttle (sliding 60s window) ─────────────────────────────────
function makeThrottle(maxPerMin) {
@@ -74,6 +75,9 @@ async function main() {
if (kind !== 'mint' || draining || cfg.globalKill) return;
const strategies = cachedStrategies();
for (const strat of strategies) {
+ // The new-mint feed only drives new_mint strategies; first_claim
+ // strategies are driven by the on-chain claim poll loop below.
+ if ((strat.trigger || 'new_mint') !== 'new_mint') continue;
const { pass, reasons } = scoreMint(data, strat);
if (!pass) continue;
log.info('candidate', { agent: strat.agent_id, mint: data.mint, symbol: data.symbol, reasons });
@@ -85,6 +89,13 @@ async function main() {
let stopFeed = connectPumpFunFeed({ kind: 'mint', signal: abort.signal, onEvent });
log.info('feed connected', {});
+ // First-claim trigger: polls the on-chain fee-claim stream and snipes a
+ // creator's coin on their first-ever reward claim. Shares the buy queue +
+ // global throttle with the new-mint path, and halts new buys on drain/kill.
+ const stopClaimWatch = startFirstClaimWatch({
+ cfg, queue, throttle, isHalted: () => draining || cfg.globalKill,
+ });
+
// Strategy cache refresh.
const strategyTimer = setInterval(() => {
refreshStrategies(cfg.network, cfg.strategyRefreshMs)
@@ -122,6 +133,7 @@ async function main() {
clearInterval(strategyTimer);
clearInterval(positionTimer);
clearInterval(watchdogTimer);
+ try { stopClaimWatch?.(); } catch {}
try { stopFeed?.(); } catch {}
abort.abort();
// Give in-flight buys a moment to settle (Neon HTTP is stateless — nothing