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.

feat: add achievements endpoint and panel for agent achievements tracking

zprv77faa2bc38f2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 168f6cc7f..2914ff03c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-29
- **Agent Economy Volume** (`/agent-economy-volume`) — Live dashboard of total agent-to-agent economy volume: real USDC settled between AI agents hiring each other for paid skills over x402, with top earners, top spenders, and a 90-day volume chart.
+- **Agent profiles now earn achievements and badges** — Every agent profile now shows the achievements it has earned on three.ws — tiered badges for real milestones like launching a coin, graduating a token to the AMM, crossing $100K and $1M market caps, drawing real supporters, running buyback burns, reaching a Trusted or Elite reputation tier, and sticking around. Each badge is computed from real on-chain and ledger data, never hand-assigned, and the panel also shows an "in progress" ladder so a creator can see exactly what's next. The graduate badge celebrates the agents whose coins actually migrated. `[feature]`
- **Agent profiles now use the full width of the screen** — An agent's profile page used to sit in a single narrow column down the middle, leaving most of a wide screen empty and forcing a very long scroll. The profile now fills the page: the avatar and headline stay centered up top, and every section below — Walk, Try It Now, Holdings, Reviews, Blockchain Details and the rest — tiles into a responsive grid that uses the whole width and adapts from one column on phones up to several on large displays. Same information, far less scrolling. `[improvement]`
- **Agents now compete in a live reputation arena** — The live wall is now ranked. Every agent card is stamped with its real, non-gameable wallet-trust tier and score — earned through actual on-chain activity, never faked — and the wall continuously reorders so the most-trusted agents rise to the top, gliding into their new rank and pulsing as they climb. Open any agent's screen and a new Reputation panel sits beside the avatar: the full trust breakdown plus the a2a-hire receipts that built it, each a verifiable USDC settlement with a Solscan link and the 1–5★ the hirer gave, charted as a real rating history. A brand-new agent is shown honestly as "New" rather than a made-up number. (`/agents-live`) `[feature]`
- **Agents now host live stage shows on their screen** — Open an agent's screen and tap Start: the host comes on stage and performs a show that never goes quiet. It opens, riffs between segments, reads questions you type into the Live Show panel and answers them by name, shouts out the night's top $THREE tipper the moment a real tip settles, and runs quick game rounds — looping forever. Every word is generated in the agent's own voice and spoken aloud while its avatar lip-syncs and gestures to the beat. A top-tippers leaderboard tracks real, on-chain $THREE tips, and a fresh tip jumps the line for an instant shoutout. Press G to toggle the panel. (`/agent-screen`) `[feature]`
diff --git a/api/_lib/agent-achievements.js b/api/_lib/agent-achievements.js
new file mode 100644
index 000000000..72bcbf240
--- /dev/null
+++ b/api/_lib/agent-achievements.js
@@ -0,0 +1,242 @@
+/**
+ * Agent achievements engine — pure, deterministic, no I/O.
+ * =======================================================
+ *
+ * Turns an agent's REAL platform record (coins launched, graduations/migrations,
+ * peak market caps, supporters, burns, reputation, tenure) into a tiered set of
+ * achievements. Kept side-effect-free so the formula is unit-testable and could
+ * later back the OG card, the leaderboard, or a notification — the HTTP handler
+ * (api/agents/_id/achievements.js) gathers the inputs and hands them here.
+ *
+ * Every threshold is grounded in something a holder can verify on-chain or in the
+ * public feeds. Nothing here invents data: a missing/zeroed metric simply leaves
+ * the relevant badge locked (with honest progress), never falsely awarded.
+ */
+
+// Tier ranking — drives the "highest tier earned" summary and the UI accents.
+export const TIER_RANK = { bronze: 0, silver: 1, gold: 2, legendary: 3 };
+
+// pump.fun bonding curves graduate (migrate to the AMM) around a ~$69k USD
+// market cap; the same constant the coin-status widget uses for its gauge.
+const GRADUATION_CAP_USD = 69_000;
+
+const DAY_MS = 86_400_000;
+
+/**
+ * The achievement catalog. Each entry is awarded when `metric >= threshold`.
+ * `metric` indexes into the derived metrics object below, so adding an award is
+ * a one-line change. `earnedAtKind` tells the engine which real timeline to pull
+ * the unlock timestamp from (best-effort; null when not knowable).
+ *
+ * `unit` shapes how the UI renders progress on a still-locked badge.
+ */
+export const ACHIEVEMENTS = [
+ // ── Creating ──────────────────────────────────────────────────────────────
+ { id: 'trailblazer', group: 'Creator', tier: 'bronze', icon: '🚀',
+ title: 'Trailblazer', description: 'Launched a coin on three.ws.',
+ metric: 'launchesTotal', threshold: 1, unit: 'count', earnedAtKind: 'launch' },
+ { id: 'serial-creator', group: 'Creator', tier: 'silver', icon: '🏭',
+ title: 'Serial Creator', description: 'Launched 5 coins through the platform.',
+ metric: 'launchesTotal', threshold: 5, unit: 'count', earnedAtKind: 'launch' },
+ { id: 'launch-machine', group: 'Creator', tier: 'gold', icon: '⚙️',
+ title: 'Launch Machine', description: 'Launched 15 coins — a true factory.',
+ metric: 'launchesTotal', threshold: 15, unit: 'count', earnedAtKind: 'launch' },
+
+ // ── Graduation / migration (the headline success signal) ────────────────────
+ { id: 'graduate', group: 'Migration', tier: 'gold', icon: '🎓',
+ title: 'Graduate', description: 'Launched a coin that completed its bonding curve and migrated.',
+ metric: 'graduations', threshold: 1, unit: 'count', earnedAtKind: 'graduation' },
+ { id: 'migrator', group: 'Migration', tier: 'legendary', icon: '🏆',
+ title: 'Serial Migrator', description: 'Three launches graduated and migrated to the AMM.',
+ metric: 'graduations', threshold: 3, unit: 'count', earnedAtKind: 'graduation' },
+
+ // ── Market cap milestones ───────────────────────────────────────────────────
+ { id: 'six-figures', group: 'Market', tier: 'silver', icon: '💰',
+ title: 'Six Figures', description: 'A launch crossed a $100K market cap.',
+ metric: 'topMcap', threshold: 100_000, unit: 'usd' },
+ { id: 'seven-figures', group: 'Market', tier: 'legendary', icon: '💎',
+ title: 'Seven Figures', description: 'A launch crossed a $1M market cap.',
+ metric: 'topMcap', threshold: 1_000_000, unit: 'usd' },
+
+ // ── Community / supporters ──────────────────────────────────────────────────
+ { id: 'first-supporter', group: 'Community', tier: 'bronze', icon: '🤝',
+ title: 'First Supporter', description: 'Received a confirmed on-chain payment.',
+ metric: 'uniquePayers', threshold: 1, unit: 'count' },
+ { id: 'crowd-backed', group: 'Community', tier: 'silver', icon: '👥',
+ title: 'Crowd-Backed', description: '10 distinct wallets paid this agent.',
+ metric: 'uniquePayers', threshold: 10, unit: 'count' },
+ { id: 'fan-favorite', group: 'Community', tier: 'gold', icon: '🌟',
+ title: 'Fan Favorite', description: '50 distinct wallets paid this agent.',
+ metric: 'uniquePayers', threshold: 50, unit: 'count' },
+
+ // ── Tokenomics / burns ──────────────────────────────────────────────────────
+ { id: 'deflationary', group: 'Tokenomics', tier: 'silver', icon: '🔥',
+ title: 'Deflationary', description: 'Ran a buyback-and-burn on a launch.',
+ metric: 'burnRuns', threshold: 1, unit: 'count' },
+ { id: 'scorched-earth', group: 'Tokenomics', tier: 'gold', icon: '🌋',
+ title: 'Scorched Earth', description: 'Completed 10 buyback-and-burn runs.',
+ metric: 'burnRuns', threshold: 10, unit: 'count' },
+
+ // ── Reputation ──────────────────────────────────────────────────────────────
+ { id: 'trusted-operator', group: 'Reputation', tier: 'gold', icon: '🛡️',
+ title: 'Trusted Operator', description: 'Reached the Trusted reputation tier.',
+ metric: 'reputationRank', threshold: 3, unit: 'rank' },
+ { id: 'elite-operator', group: 'Reputation', tier: 'legendary', icon: '👑',
+ title: 'Elite Operator', description: 'Reached the Elite reputation tier.',
+ metric: 'reputationRank', threshold: 4, unit: 'rank' },
+
+ // ── Tenure ──────────────────────────────────────────────────────────────────
+ { id: 'established', group: 'Tenure', tier: 'bronze', icon: '📅',
+ title: 'Established', description: 'Active on three.ws for 30 days.',
+ metric: 'ageDays', threshold: 30, unit: 'days', earnedAtKind: 'tenure' },
+ { id: 'veteran', group: 'Tenure', tier: 'silver', icon: '🗓️',
+ title: 'Veteran', description: 'Active on three.ws for 180 days.',
+ metric: 'ageDays', threshold: 180, unit: 'days', earnedAtKind: 'tenure' },
+];
+
+function toMs(v) {
+ if (v == null) return null;
+ const t = v instanceof Date ? v.getTime() : new Date(v).getTime();
+ return Number.isFinite(t) ? t : null;
+}
+
+/**
+ * Decide whether a single launch counts as graduated/migrated from its live
+ * pump.fun coin object. `complete === true` is the authoritative migration flag;
+ * a recorded AMM pool, or a market cap past the graduation threshold, are honest
+ * fallbacks when the upstream `complete` flag lags the pool creation.
+ */
+export function isLaunchGraduated(coin) {
+ if (!coin || typeof coin !== 'object') return false;
+ if (coin.complete === true) return true;
+ if (coin.raydium_pool || coin.pump_swap_pool || coin.amm_pool) return true;
+ const mcap = Number(coin.usd_market_cap);
+ return Number.isFinite(mcap) && mcap >= GRADUATION_CAP_USD;
+}
+
+/**
+ * Derive the flat metrics object every achievement is scored against.
+ * @param {object} ctx — see computeAchievements
+ */
+export function deriveMetrics(ctx = {}) {
+ const launches = Array.isArray(ctx.launches) ? ctx.launches : [];
+ const payments = ctx.payments || {};
+ const burns = ctx.burns || {};
+ const reputation = ctx.reputation || null;
+ const now = Number.isFinite(ctx.now) ? ctx.now : Date.now();
+ const agentCreatedMs = toMs(ctx.agentCreatedAt);
+
+ const graduatedLaunches = launches.filter((l) => l && l.graduated);
+ const topMcap = launches.reduce((max, l) => {
+ const m = Number(l?.mcap);
+ return Number.isFinite(m) && m > max ? m : max;
+ }, 0);
+
+ return {
+ launchesTotal: launches.length,
+ mainnetLaunches: launches.filter((l) => l && l.network !== 'devnet').length,
+ graduations: graduatedLaunches.length,
+ topMcap,
+ uniquePayers: Number(payments.unique_payers) || 0,
+ confirmedPayments: Number(payments.confirmed_payments) || 0,
+ burnRuns: Number(burns.runs) || 0,
+ reputationRank: reputation ? Number(reputation.rank) || 0 : 0,
+ ageDays: agentCreatedMs != null ? Math.max(0, (now - agentCreatedMs) / DAY_MS) : 0,
+ };
+}
+
+// Ascending-sorted launch timestamps (ms) for milestone unlock dates.
+function ascendingLaunchTimes(launches, onlyGraduated = false) {
+ return (launches || [])
+ .filter((l) => l && (!onlyGraduated || l.graduated))
+ .map((l) => toMs(l.created_at))
+ .filter((t) => t != null)
+ .sort((a, b) => a - b);
+}
+
+function resolveEarnedAt(entry, ctx, metrics) {
+ const now = Number.isFinite(ctx.now) ? ctx.now : Date.now();
+ switch (entry.earnedAtKind) {
+ case 'launch': {
+ const times = ascendingLaunchTimes(ctx.launches);
+ const t = times[entry.threshold - 1];
+ return t != null ? new Date(t).toISOString() : null;
+ }
+ case 'graduation': {
+ const times = ascendingLaunchTimes(ctx.launches, true);
+ const t = times[entry.threshold - 1];
+ return t != null ? new Date(t).toISOString() : null;
+ }
+ case 'tenure': {
+ const created = toMs(ctx.agentCreatedAt);
+ if (created == null) return null;
+ const at = created + entry.threshold * DAY_MS;
+ return at <= now ? new Date(at).toISOString() : null;
+ }
+ default:
+ return null;
+ }
+}
+
+/**
+ * Compute the full achievement set for an agent.
+ *
+ * @param {object} ctx
+ * @param {string|number|Date} [ctx.agentCreatedAt] — agent_identities.created_at
+ * @param {Array<{network?:string, created_at?:any, graduated?:boolean, mcap?:number}>} [ctx.launches]
+ * @param {{confirmed_payments?:number, unique_payers?:number}} [ctx.payments]
+ * @param {{runs?:number}} [ctx.burns]
+ * @param {{rank?:number, tier?:string, tierLabel?:string, score?:number}|null} [ctx.reputation]
+ * @param {number} [ctx.now] — epoch ms (injectable for deterministic tests)
+ * @returns {{achievements: object[], earned: object[], locked: object[], summary: object}}
+ */
+export function computeAchievements(ctx = {}) {
+ const metrics = deriveMetrics(ctx);
+
+ const achievements = ACHIEVEMENTS.map((entry) => {
+ const current = Number(metrics[entry.metric]) || 0;
+ const earned = current >= entry.threshold;
+ return {
+ id: entry.id,
+ group: entry.group,
+ tier: entry.tier,
+ icon: entry.icon,
+ title: entry.title,
+ description: entry.description,
+ unit: entry.unit,
+ earned,
+ earnedAt: earned ? resolveEarnedAt(entry, ctx, metrics) : null,
+ progress: {
+ current: Math.min(current, entry.threshold),
+ target: entry.threshold,
+ // Raw value too — the UI shows "62 / 50" gracefully where earned.
+ value: current,
+ pct: entry.threshold > 0 ? Math.min(1, current / entry.threshold) : 1,
+ },
+ };
+ });
+
+ const earned = achievements.filter((a) => a.earned);
+ const locked = achievements.filter((a) => !a.earned);
+ const topTier = earned.reduce(
+ (best, a) => (TIER_RANK[a.tier] > TIER_RANK[best] ? a.tier : best),
+ earned.length ? 'bronze' : null,
+ );
+
+ return {
+ achievements,
+ earned,
+ locked,
+ summary: {
+ earnedCount: earned.length,
+ total: achievements.length,
+ topTier,
+ launches: metrics.launchesTotal,
+ graduations: metrics.graduations,
+ topMcap: metrics.topMcap,
+ uniquePayers: metrics.uniquePayers,
+ burnRuns: metrics.burnRuns,
+ reputationTier: ctx.reputation?.tierLabel || ctx.reputation?.tier || null,
+ },
+ };
+}
diff --git a/api/agents/[id].js b/api/agents/[id].js
index af2d7044a..e81057a8e 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -15,6 +15,7 @@
* /api/agents/:id/registration — public EIP-8004 registry document (Metaplex Agent Registry URI)
* /api/agents/:id/sign — owner-only: sign message with server wallet
* /api/agents/:id/usage — owner-only: LLM usage stats
+ * /api/agents/:id/achievements — public: earned + locked achievements from real platform data
*
* /api/agents/:id/livekit-token — GET short-lived LiveKit room JWT
* /api/agents/:id/embed — POST text → 1024-dim embedding vector
@@ -237,6 +238,11 @@ export default wrap(async function handler(req, res) {
return mod.handleReputation(req, res, id);
}
+ if (sub === 'achievements') {
+ const mod = await import('./_id/achievements.js');
+ return mod.handleAchievements(req, res, id);
+ }
+
if (sub === 'unlocks') {
const mod = await import('./_id/unlocks.js');
return mod.handleUnlocks(req, res, id, action);
diff --git a/api/agents/_id/achievements.js b/api/agents/_id/achievements.js
new file mode 100644
index 000000000..f352bd7de
--- /dev/null
+++ b/api/agents/_id/achievements.js
@@ -0,0 +1,169 @@
+/**
+ * GET /api/agents/:id/achievements
+ *
+ * The agent's earned + locked achievements, computed from REAL platform data:
+ * · coins launched (pump_agent_mints)
+ * · graduations / migrations (live pump.fun coin `complete` + AMM pool)
+ * · peak market cap reached (live pump.fun usd_market_cap)
+ * · distinct supporters / payments (pump_agent_payments)
+ * · buyback-and-burn runs (pump_buyback_runs)
+ * · reputation tier (wallet-reputation, best-effort)
+ * · tenure (agent_identities.created_at)
+ *
+ * Pure scoring lives in api/_lib/agent-achievements.js. Public read — the badges
+ * are a trust signal others rely on, so owner and visitor see the same set.
+ * Short-cached (Redis) because the live market lookups are the slow part.
+ */
+
+import { cors, json, error, method, wrap, rateLimited } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { getRedis } from '../../_lib/redis.js';
+import { sql } from '../../_lib/db.js';
+import { isUuid } from '../../_lib/validate.js';
+import { computeAchievements, isLaunchGraduated } from '../../_lib/agent-achievements.js';
+
+const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';
+const CACHE_TTL_S = 120;
+// Cap the live market lookups so a creator with dozens of launches can't fan out
+// into dozens of upstream calls per request. Newest 30 covers every milestone in
+// practice; older launches that already graduated keep the badge regardless.
+const MARKET_LOOKUP_CAP = 30;
+
+/** Live pump.fun coin object for a mint, or null on any failure (best-effort). */
+async function fetchCoin(mint) {
+ try {
+ const resp = await fetch(new URL(`/coins/${mint}`, PUMP_FRONTEND_BASE), {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(7000),
+ });
+ if (!resp.ok) return null;
+ return await resp.json();
+ } catch {
+ return null;
+ }
+}
+
+export const handleAchievements = wrap(async (req, res, agentId) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+ if (!isUuid(String(agentId || ''))) return error(res, 404, 'not_found', 'agent not found');
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const cacheKey = `agent-achievements:v1:${agentId}`;
+ const redis = await getRedis();
+ if (redis) {
+ try {
+ const cached = await redis.get(cacheKey);
+ if (cached) {
+ res.setHeader('X-Cache', 'HIT');
+ res.setHeader('cache-control', 'public, max-age=60');
+ return json(res, 200, cached);
+ }
+ } catch {
+ /* cache miss — recompute */
+ }
+ }
+
+ // Agent must exist (and not be soft-deleted) for the page to mean anything.
+ const [agent] = await sql`
+ SELECT id, name, created_at
+ FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ // Pull every launch, plus aggregate supporter + burn stats across all of this
+ // agent's mints, in parallel — three independent reads, one round trip each.
+ const [launchRows, [paymentStats], [burnStats]] = await Promise.all([
+ sql`
+ SELECT mint, network, created_at
+ FROM pump_agent_mints
+ WHERE agent_id = ${agentId}
+ ORDER BY created_at DESC
+ `,
+ sql`
+ SELECT
+ count(*) FILTER (WHERE p.status='confirmed')::int AS confirmed_payments,
+ count(DISTINCT p.payer_wallet) FILTER (WHERE p.status='confirmed')::int AS unique_payers
+ FROM pump_agent_payments p
+ JOIN pump_agent_mints m ON m.id = p.mint_id
+ WHERE m.agent_id = ${agentId}
+ `,
+ sql`
+ SELECT count(*) FILTER (WHERE b.status='confirmed')::int AS runs
+ FROM pump_buyback_runs b
+ JOIN pump_agent_mints m ON m.id = b.mint_id
+ WHERE m.agent_id = ${agentId}
+ `,
+ ]);
+
+ // Enrich each launch with live market data (graduation + market cap). Only
+ // mainnet mints have a pump.fun market; devnet launches stay non-graduated
+ // with no mcap. Capped + parallel + best-effort so the endpoint never hangs
+ // or fails on an upstream blip.
+ const mainnet = launchRows.filter((r) => r.network !== 'devnet').slice(0, MARKET_LOOKUP_CAP);
+ const coins = await Promise.all(mainnet.map((r) => fetchCoin(r.mint)));
+ const marketByMint = new Map();
+ mainnet.forEach((r, i) => marketByMint.set(r.mint, coins[i]));
+
+ const launches = launchRows.map((r) => {
+ const coin = marketByMint.get(r.mint);
+ const mcap = Number(coin?.usd_market_cap);
+ return {
+ mint: r.mint,
+ network: r.network,
+ created_at: r.created_at,
+ graduated: r.network !== 'devnet' && isLaunchGraduated(coin),
+ mcap: Number.isFinite(mcap) ? mcap : 0,
+ };
+ });
+
+ // Reputation tier — best-effort. The reputation read does on-chain + ledger
+ // work, so a failure (or slow upstream) must never block the achievements:
+ // the two reputation badges simply stay locked.
+ let reputation = null;
+ try {
+ const { getAgentReputation } = await import('../../_lib/trust/wallet-reputation.js');
+ const { TIERS } = await import('../../../src/shared/agent-financial-reputation.js');
+ const rep = await getAgentReputation(agentId);
+ if (rep && rep.tier) {
+ reputation = {
+ tier: rep.tier,
+ tierLabel: rep.tierLabel || TIERS[rep.tier]?.label || rep.tier,
+ rank: TIERS[rep.tier]?.rank ?? 0,
+ score: rep.score ?? null,
+ };
+ }
+ } catch {
+ reputation = null;
+ }
+
+ const result = computeAchievements({
+ agentCreatedAt: agent.created_at,
+ launches,
+ payments: paymentStats || {},
+ burns: burnStats || {},
+ reputation,
+ });
+
+ const body = {
+ agent_id: agent.id,
+ name: agent.name,
+ ...result,
+ computed_at: new Date().toISOString(),
+ };
+
+ if (redis) {
+ try {
+ await redis.set(cacheKey, body, { ex: CACHE_TTL_S });
+ } catch {
+ /* cache write best-effort */
+ }
+ }
+ res.setHeader('cache-control', 'public, max-age=60');
+ return json(res, 200, body);
+});
+
+export default handleAchievements;
diff --git a/data/changelog.json b/data/changelog.json
index bb969aa3c..b6f7690bd 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,14 @@
{
"$comment": "Curated changelog entries for three.ws \u2014 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-29",
+ "title": "Agent profiles now earn achievements and badges",
+ "summary": "Every agent profile now shows the achievements it has earned on three.ws — tiered badges for real milestones like launching a coin, graduating a token to the AMM, crossing $100K and $1M market caps, drawing real supporters, running buyback burns, reaching a Trusted or Elite reputation tier, and sticking around. Each badge is computed from real on-chain and ledger data, never hand-assigned, and the panel also shows an \"in progress\" ladder so a creator can see exactly what's next. The graduate badge celebrates the agents whose coins actually migrated.",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"title": "Smart-Money wallet reputation stays fresh again",
diff --git a/pages/agent-detail.html b/pages/agent-detail.html
index 86871ad9b..df04c8f53 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -548,6 +548,19 @@
<div class="ad-cards">
+ <!-- Achievements — earned badges + in-progress ladder, computed from
+ real launches, graduations, market caps, supporters, burns,
+ reputation, and tenure. Hidden for visitors on a blank profile;
+ always shown to the owner (with an encouraging empty state). -->
+ <section class="ad-card" id="ad-achievements-card">
+ <div class="ad-card-head">
+ <span class="ad-bullet ad-bullet-amber"></span>
+ <h2>ACHIEVEMENTS</h2>
+ <span class="ad-preview-hint">Earned on three.ws</span>
+ </div>
+ <div id="ad-achievements-body"></div>
+ </section>
+
<section class="ad-card ad-walk-card" id="ad-walk-card" hidden>
<div class="ad-card-head">
<span class="ad-bullet ad-bullet-violet"></span>
diff --git a/public/changelog.json b/public/changelog.json
index 19f64cae8..a19e079a4 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T09:42:07.233Z",
+ "generated_at": "2026-06-29T10:03:11.259Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,16 @@
"launch"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Agent profiles now earn achievements and badges",
+ "summary": "Every agent profile now shows the achievements it has earned on three.ws — tiered badges for real milestones like launching a coin, graduating a token to the AMM, crossing $100K and $1M market caps, drawing real supporters, running buyback burns, reaching a Trusted or Elite reputation tier, and sticking around. Each badge is computed from real on-chain and ledger data, never hand-assigned, and the panel also shows an \"in progress\" ladder so a creator can see exactly what's next. The graduate badge celebrates the agents whose coins actually migrated.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index f8221ff5c..1f6a01a14 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>launch</category>
<description>Live dashboard of total agent-to-agent economy volume: real USDC settled between AI agents hiring each other for paid skills over x402, with top earners, top spenders, and a 90-day volume chart.</description>
</item>
+ <item>
+ <title>Agent profiles now earn achievements and badges</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-29:Agent profiles now earn achievements and badges</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every agent profile now shows the achievements it has earned on three.ws — tiered badges for real milestones like launching a coin, graduating a token to the AMM, crossing $100K and $1M market caps, drawing real supporters, running buyback burns, reaching a Trusted or Elite reputation tier, and sticking around. Each badge is computed from real on-chain and ledger data, never hand-assigned, and the panel also shows an &quot;in progress&quot; ladder so a creator can see exactly what's next. The graduate badge celebrates the agents whose coins actually migrated.</description>
+ </item>
<item>
<title>Agent profiles now use the full width of the screen</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 0902d97eb..74f31980e 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T09:42:07.218Z",
+ "generated_at": "2026-06-29T10:03:11.221Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 1c74f7e9b..b7308ec5d 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -24,6 +24,7 @@ import { mountStagePanel } from './shared/stage-link.js';
import { mountLaborPanel } from './shared/labor-link.js';
import { mountAlphaPanel } from './shared/alpha-copilot-link.js';
import { mountWatchPanel } from './shared/agent-watch-panel.js';
+import { mountAchievements } from './shared/agent-achievements-panel.js';
import { renderError as renderAsyncError } from './shared/async-state.js';
import { skeletonHTML } from './shared/state-kit.js';
import { openCoinLaunch } from './shared/agent-coin.js';
@@ -49,6 +50,7 @@ let _strategyHandle = null;
let _cardHandle = null;
let _patronageHandle = null;
let _watchHandle = null;
+let _achievementsHandle = null;
// Live WebGL avatar mounts (hero + fullscreen modal). Disposed on re-render so a
// fresh render() doesn't stack a second renderer onto the same container.
let _heroAvatarHandle = null;
@@ -126,6 +128,7 @@ if (typeof window !== 'undefined') {
try { _streamHandle?.destroy?.(); } catch { /* idempotent */ } _streamHandle = null;
try { _cardHandle?.destroy?.(); } catch { /* idempotent */ } _cardHandle = null;
try { _watchHandle?.destroy?.(); } catch { /* idempotent */ } _watchHandle = null;
+ try { _achievementsHandle?.destroy?.(); } catch { /* idempotent */ } _achievementsHandle = null;
// Release the WebGL contexts so they don't count against the browser's
// hard context budget once the user navigates away.
try { _heroAvatarHandle?.dispose(); } catch { /* idempotent */ } _heroAvatarHandle = null;
@@ -1163,6 +1166,24 @@ function render(agent) {
// renders nothing extra when the agent has no launches beyond the chip above.
renderLaunchHistory($('ad-token-body'), agent);
+ // Achievements — earned badges + in-progress ladder from real platform data
+ // (launches, graduations/migrations, market caps, supporters, burns,
+ // reputation, tenure). The panel hides its own card for visitors on a blank
+ // profile and shows the owner an encouraging empty state.
+ {
+ const achBody = $('ad-achievements-body');
+ const achCard = $('ad-achievements-card');
+ if (_achievementsHandle) { try { _achievementsHandle.destroy(); } catch { /* idempotent */ } _achievementsHandle = null; }
+ if (achBody && agent.id) {
+ _achievementsHandle = mountAchievements({
+ mount: achBody,
+ agentId: agent.id,
+ isOwner: !!agent.isOwner,
+ card: achCard,
+ });
+ }
+ }
+
// Agent Genome lineage — parents (if bred), children (if a parent), and a
// one-click re-derivation verify. Fire-and-forget; reveals the card only when
// there is real descent to show.
diff --git a/src/shared/agent-achievements-panel.js b/src/shared/agent-achievements-panel.js
new file mode 100644
index 000000000..88b3f3165
--- /dev/null
+++ b/src/shared/agent-achievements-panel.js
@@ -0,0 +1,337 @@
+/**
+ * Agent achievements panel.
+ * =========================
+ *
+ * Renders an agent's earned badges + in-progress achievements from the real
+ * GET /api/agents/:id/achievements feed (computed server-side from launches,
+ * graduations/migrations, market caps, supporters, burns, reputation, tenure).
+ *
+ * Self-manages loading → populated / empty / error states so the caller just
+ * hands it a mount node, an agent id, and whether the viewer is the owner.
+ * Returns a { destroy } handle that aborts any in-flight fetch.
+ */
+
+const TIER_META = {
+ bronze: { label: 'Bronze', accent: '#cd7f32' },
+ silver: { label: 'Silver', accent: '#cbd5e1' },
+ gold: { label: 'Gold', accent: '#fbbf24' },
+ legendary: { label: 'Legendary', accent: '#c084fc' },
+};
+
+const TIER_RANK = { bronze: 0, silver: 1, gold: 2, legendary: 3 };
+
+function el(tag, props = {}, children = []) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (v == null || v === false) continue;
+ if (k === 'class') node.className = v;
+ else if (k === 'text') node.textContent = v;
+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);
+ else node.setAttribute(k, v);
+ }
+ for (const c of [].concat(children || [])) {
+ if (c == null) continue;
+ node.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
+ }
+ return node;
+}
+
+function fmtUsd(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return '$0';
+ if (v >= 1e9) return `$${(v / 1e9).toFixed(1)}B`;
+ if (v >= 1e6) return `$${(v / 1e6).toFixed(1)}M`;
+ if (v >= 1e3) return `$${(v / 1e3).toFixed(0)}K`;
+ return `$${Math.round(v)}`;
+}
+
+// Human progress label for a still-locked achievement, e.g. "7 / 10",
+// "$42K / $100K", "12 / 30 days", "Established / Trusted".
+function progressLabel(a) {
+ const p = a.progress || {};
+ const cur = p.value ?? p.current ?? 0;
+ const target = p.target ?? 0;
+ switch (a.unit) {
+ case 'usd':
+ return `${fmtUsd(cur)} / ${fmtUsd(target)}`;
+ case 'days':
+ return `${Math.floor(cur)} / ${target} days`;
+ case 'rank':
+ return 'Keep building reputation';
+ default:
+ return `${Math.floor(cur)} / ${target}`;
+ }
+}
+
+function whenAgo(iso) {
+ const t = new Date(iso).getTime();
+ if (!Number.isFinite(t)) return '';
+ const s = Math.max(0, (Date.now() - t) / 1000);
+ if (s < 86400) return 'today';
+ if (s < 86400 * 30) return `${Math.floor(s / 86400)}d ago`;
+ return new Date(t).toLocaleDateString(undefined, { month: 'short', year: 'numeric' });
+}
+
+function summaryChips(summary) {
+ const chips = [];
+ if (summary.graduations > 0) {
+ chips.push(`🎓 ${summary.graduations} graduated`);
+ }
+ if (summary.launches > 0) {
+ chips.push(`🚀 ${summary.launches} launched`);
+ }
+ if (summary.topMcap >= 1000) {
+ chips.push(`💰 ${fmtUsd(summary.topMcap)} peak`);
+ }
+ if (summary.uniquePayers > 0) {
+ chips.push(`👥 ${summary.uniquePayers} supporters`);
+ }
+ if (summary.reputationTier) {
+ chips.push(`🛡️ ${summary.reputationTier}`);
+ }
+ return chips;
+}
+
+function badgeTile(a) {
+ const tier = TIER_META[a.tier] || TIER_META.bronze;
+ const tile = el('div', {
+ class: `aap-badge aap-tier-${a.tier}`,
+ style: `--aap-accent:${tier.accent}`,
+ title: a.earnedAt ? `${a.title} · earned ${whenAgo(a.earnedAt)}` : a.title,
+ role: 'listitem',
+ tabindex: '0',
+ 'aria-label': `${a.title}, ${tier.label} achievement${a.earnedAt ? `, earned ${whenAgo(a.earnedAt)}` : ''}. ${a.description}`,
+ }, [
+ el('span', { class: 'aap-badge-icon', 'aria-hidden': 'true', text: a.icon }),
+ el('span', { class: 'aap-badge-title', text: a.title }),
+ el('span', { class: 'aap-badge-tier', text: tier.label }),
+ a.earnedAt ? el('span', { class: 'aap-badge-when', text: whenAgo(a.earnedAt) }) : null,
+ ]);
+ return tile;
+}
+
+function lockedRow(a) {
+ const pct = Math.max(0, Math.min(1, a.progress?.pct ?? 0));
+ return el('div', { class: 'aap-locked-row', title: a.description, role: 'listitem' }, [
+ el('span', { class: 'aap-locked-icon', 'aria-hidden': 'true', text: a.icon }),
+ el('div', { class: 'aap-locked-main' }, [
+ el('div', { class: 'aap-locked-head' }, [
+ el('span', { class: 'aap-locked-title', text: a.title }),
+ el('span', { class: 'aap-locked-prog', text: progressLabel(a) }),
+ ]),
+ el('div', {
+ class: 'aap-locked-bar',
+ role: 'progressbar',
+ 'aria-valuemin': '0',
+ 'aria-valuemax': '100',
+ 'aria-valuenow': String(Math.round(pct * 100)),
+ 'aria-label': `${a.title} progress`,
+ }, [
+ el('div', { class: 'aap-locked-fill', style: `width:${(pct * 100).toFixed(1)}%` }),
+ ]),
+ ]),
+ ]);
+}
+
+function skeleton() {
+ return el('div', { class: 'aap-skeleton', 'aria-hidden': 'true' },
+ Array.from({ length: 6 }, () => el('span', { class: 'aap-skel-tile' })),
+ );
+}
+
+function emptyState(isOwner) {
+ return el('div', { class: 'aap-empty' }, [
+ el('span', { class: 'aap-empty-icon', 'aria-hidden': 'true', text: '🏅' }),
+ el('p', {
+ class: 'aap-empty-text',
+ text: isOwner
+ ? 'No achievements yet. Launch a coin, earn supporters, and graduate a token to start collecting badges.'
+ : 'No achievements yet — this agent is just getting started.',
+ }),
+ isOwner
+ ? el('a', { class: 'aap-empty-cta', href: '/launch', text: 'Launch a coin →' })
+ : null,
+ ]);
+}
+
+function errorState(retry) {
+ return el('div', { class: 'aap-error', role: 'alert' }, [
+ el('span', { class: 'aap-error-msg', text: 'Couldn’t load achievements.' }),
+ el('button', { class: 'aap-retry', type: 'button', text: 'Retry', onclick: retry }),
+ ]);
+}
+
+function render(data, isOwner) {
+ const earned = (data.earned || []).slice().sort((a, b) => {
+ const t = (TIER_RANK[b.tier] ?? 0) - (TIER_RANK[a.tier] ?? 0);
+ if (t) return t;
+ return new Date(b.earnedAt || 0) - new Date(a.earnedAt || 0);
+ });
+ const summary = data.summary || {};
+
+ const frag = document.createDocumentFragment();
+
+ // Summary line — earned count + headline real-world stats.
+ const sumChips = summaryChips(summary);
+ frag.appendChild(
+ el('div', { class: 'aap-summary' }, [
+ el('span', { class: 'aap-count', text: `${summary.earnedCount || 0} / ${summary.total || 0} earned` }),
+ ...sumChips.map((c) => el('span', { class: 'aap-stat-chip', text: c })),
+ ]),
+ );
+
+ if (!earned.length) {
+ frag.appendChild(emptyState(isOwner));
+ } else {
+ frag.appendChild(
+ el('div', { class: 'aap-grid', role: 'list', 'aria-label': 'Earned achievements' },
+ earned.map(badgeTile),
+ ),
+ );
+ }
+
+ // In-progress: the locked achievements closest to unlocking — a clear "what's
+ // next" ladder. Show the top 4 by completion so the section stays focused.
+ const next = (data.locked || [])
+ .filter((a) => (a.progress?.pct ?? 0) > 0)
+ .sort((a, b) => (b.progress?.pct ?? 0) - (a.progress?.pct ?? 0))
+ .slice(0, 4);
+ if (next.length) {
+ frag.appendChild(el('div', { class: 'aap-next-head', text: 'In progress' }));
+ frag.appendChild(
+ el('div', { class: 'aap-locked-list', role: 'list', 'aria-label': 'Achievements in progress' },
+ next.map(lockedRow),
+ ),
+ );
+ }
+
+ return frag;
+}
+
+let stylesInjected = false;
+const STYLES = `
+.aap { display: block; }
+.aap-summary { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 14px; }
+.aap-count { font-size: 12px; font-weight: 700; letter-spacing: .03em; color: var(--ink-bright, #e8e8e8);
+ background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.1); padding: 3px 10px; border-radius: 999px; }
+.aap-stat-chip { font-size: 12px; color: var(--ink-dim, rgba(255,255,255,0.7)); background: rgba(255,255,255,0.04);
+ border: 1px solid rgba(255,255,255,0.07); padding: 3px 9px; border-radius: 999px; }
+.aap-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); gap: 10px; }
+.aap-badge { position: relative; display: flex; flex-direction: column; align-items: center; gap: 4px; text-align: center;
+ padding: 14px 8px 10px; border-radius: 14px; cursor: default;
+ background: linear-gradient(160deg, color-mix(in srgb, var(--aap-accent) 16%, transparent), rgba(255,255,255,0.02));
+ border: 1px solid color-mix(in srgb, var(--aap-accent) 38%, transparent);
+ box-shadow: inset 0 1px 0 rgba(255,255,255,0.06); transition: transform .15s ease, box-shadow .15s ease; }
+.aap-badge:hover, .aap-badge:focus-visible { transform: translateY(-2px);
+ box-shadow: 0 6px 20px color-mix(in srgb, var(--aap-accent) 24%, transparent), inset 0 1px 0 rgba(255,255,255,0.08); outline: none; }
+.aap-badge:focus-visible { outline: 2px solid var(--aap-accent); outline-offset: 2px; }
+.aap-badge-icon { font-size: 30px; line-height: 1; filter: drop-shadow(0 2px 4px rgba(0,0,0,0.4)); }
+.aap-badge-title { font-size: 12px; font-weight: 600; color: var(--ink-bright, #f0f0f0); line-height: 1.2; }
+.aap-badge-tier { font-size: 9px; text-transform: uppercase; letter-spacing: .08em; font-weight: 700;
+ color: var(--aap-accent); }
+.aap-badge-when { font-size: 10px; color: var(--ink-dim, rgba(255,255,255,0.45)); }
+.aap-tier-legendary { background: linear-gradient(160deg, rgba(192,132,252,0.22), rgba(251,191,36,0.1)); }
+
+.aap-next-head { margin: 18px 0 8px; font-size: 11px; text-transform: uppercase; letter-spacing: .06em;
+ color: var(--ink-dim, rgba(255,255,255,0.5)); font-weight: 700; }
+.aap-locked-list { display: flex; flex-direction: column; gap: 10px; }
+.aap-locked-row { display: flex; align-items: center; gap: 10px; opacity: .92; }
+.aap-locked-icon { font-size: 20px; line-height: 1; filter: grayscale(.5) opacity(.85); flex: 0 0 auto; }
+.aap-locked-main { flex: 1 1 auto; min-width: 0; }
+.aap-locked-head { display: flex; justify-content: space-between; gap: 8px; margin-bottom: 4px; }
+.aap-locked-title { font-size: 12px; font-weight: 600; color: var(--ink-bright, #e8e8e8); }
+.aap-locked-prog { font-size: 11px; color: var(--ink-dim, rgba(255,255,255,0.55)); white-space: nowrap;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
+.aap-locked-bar { height: 5px; border-radius: 999px; background: rgba(255,255,255,0.08); overflow: hidden; }
+.aap-locked-fill { height: 100%; border-radius: 999px;
+ background: linear-gradient(90deg, var(--accent, #7c83ff), #a78bfa); transition: width .5s ease; }
+
+.aap-empty { display: flex; flex-direction: column; align-items: center; text-align: center; gap: 8px; padding: 18px 12px; }
+.aap-empty-icon { font-size: 30px; opacity: .8; }
+.aap-empty-text { margin: 0; font-size: 13px; color: var(--ink-dim, rgba(255,255,255,0.6)); max-width: 36ch; }
+.aap-empty-cta { font-size: 13px; font-weight: 600; color: var(--accent, #7c83ff); text-decoration: none; }
+.aap-empty-cta:hover { opacity: .8; }
+
+.aap-skeleton { display: grid; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); gap: 10px; }
+.aap-skel-tile { height: 92px; border-radius: 14px;
+ background: linear-gradient(90deg, rgba(255,255,255,0.05) 25%, rgba(255,255,255,0.1) 37%, rgba(255,255,255,0.05) 63%);
+ background-size: 400% 100%; animation: aap-shimmer 1.4s ease infinite; }
+@keyframes aap-shimmer { 0% { background-position: 100% 50%; } 100% { background-position: 0 50%; } }
+@media (prefers-reduced-motion: reduce) { .aap-skel-tile { animation: none; } .aap-badge, .aap-locked-fill { transition: none; } }
+
+.aap-error { display: flex; align-items: center; gap: 10px; color: var(--ink-dim, rgba(255,255,255,0.6)); font-size: 13px; }
+.aap-error-msg { flex: 1 1 auto; }
+.aap-retry { background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.12); color: inherit;
+ border-radius: 7px; padding: 3px 10px; font-size: 12px; cursor: pointer; transition: background .15s; }
+.aap-retry:hover { background: rgba(255,255,255,0.14); }
+.aap-retry:focus-visible { outline: 2px solid var(--accent, #7c83ff); outline-offset: 1px; }
+`;
+
+function injectStyles() {
+ if (stylesInjected || typeof document === 'undefined') return;
+ const tag = document.createElement('style');
+ tag.dataset.aapStyles = '1';
+ tag.textContent = STYLES;
+ document.head.appendChild(tag);
+ stylesInjected = true;
+}
+
+/**
+ * Mount the achievements panel.
+ *
+ * @param {object} opts
+ * @param {HTMLElement} opts.mount — container to render into
+ * @param {string} opts.agentId — agent UUID
+ * @param {boolean} [opts.isOwner]— tailors the empty-state copy + CTA
+ * @param {HTMLElement} [opts.card] — optional wrapping card to hide when there
+ * is genuinely nothing to show to a visitor
+ * @returns {{ destroy: () => void }}
+ */
+export function mountAchievements({ mount, agentId, isOwner = false, card = null } = {}) {
+ if (!mount || !agentId) return { destroy() {} };
+ injectStyles();
+ mount.classList.add('aap');
+
+ let destroyed = false;
+ let abort = null;
+
+ async function load() {
+ if (destroyed) return;
+ if (abort) abort.abort();
+ abort = new AbortController();
+ mount.replaceChildren(skeleton());
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/achievements`, {
+ signal: abort.signal,
+ });
+ if (!r.ok) throw new Error(`achievements ${r.status}`);
+ const data = await r.json();
+ if (destroyed) return;
+
+ const hasContent =
+ (data.earned?.length || 0) > 0 ||
+ (data.locked || []).some((a) => (a.progress?.pct ?? 0) > 0);
+ // For a visitor on a brand-new agent with literally nothing, hide the
+ // whole card rather than show an empty shell. The owner always sees it
+ // (with the encouraging empty state + launch CTA).
+ if (!hasContent && !isOwner && card) {
+ card.hidden = true;
+ return;
+ }
+ if (card) card.hidden = false;
+ mount.replaceChildren(render(data, isOwner));
+ } catch (err) {
+ if (err?.name === 'AbortError' || destroyed) return;
+ mount.replaceChildren(errorState(load));
+ }
+ }
+
+ load();
+
+ return {
+ destroy() {
+ destroyed = true;
+ if (abort) abort.abort();
+ },
+ };
+}
diff --git a/tests/agent-achievements.test.js b/tests/agent-achievements.test.js
new file mode 100644
index 000000000..d7d71ede1
--- /dev/null
+++ b/tests/agent-achievements.test.js
@@ -0,0 +1,182 @@
+// Unit tests for the agent achievements engine — api/_lib/agent-achievements.js.
+//
+// The engine is pure (no I/O): given an agent's real metrics it returns the
+// earned + locked badge set. These tests pin the award thresholds, the
+// graduation/migration detection, progress reporting, and the summary roll-up.
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ computeAchievements,
+ deriveMetrics,
+ isLaunchGraduated,
+ ACHIEVEMENTS,
+ TIER_RANK,
+} from '../api/_lib/agent-achievements.js';
+
+const NOW = Date.UTC(2026, 5, 29); // fixed clock for deterministic tenure/dates
+const daysAgo = (d) => new Date(NOW - d * 86_400_000).toISOString();
+
+const byId = (result, id) => result.achievements.find((a) => a.id === id);
+
+describe('isLaunchGraduated', () => {
+ it('treats complete === true as graduated', () => {
+ expect(isLaunchGraduated({ complete: true })).toBe(true);
+ });
+ it('treats a recorded AMM pool as graduated even if complete lags', () => {
+ expect(isLaunchGraduated({ complete: false, raydium_pool: 'pool111' })).toBe(true);
+ expect(isLaunchGraduated({ pump_swap_pool: 'pool222' })).toBe(true);
+ });
+ it('treats a market cap past the graduation threshold as graduated', () => {
+ expect(isLaunchGraduated({ usd_market_cap: 70_000 })).toBe(true);
+ expect(isLaunchGraduated({ usd_market_cap: 50_000 })).toBe(false);
+ });
+ it('is false for null / empty / non-graduated coins', () => {
+ expect(isLaunchGraduated(null)).toBe(false);
+ expect(isLaunchGraduated({})).toBe(false);
+ expect(isLaunchGraduated({ complete: false, usd_market_cap: 1234 })).toBe(false);
+ });
+});
+
+describe('deriveMetrics', () => {
+ it('rolls launches, graduations, peak mcap, supporters, burns, tenure', () => {
+ const m = deriveMetrics({
+ now: NOW,
+ agentCreatedAt: daysAgo(200),
+ launches: [
+ { network: 'mainnet', graduated: true, mcap: 120_000, created_at: daysAgo(100) },
+ { network: 'mainnet', graduated: false, mcap: 4_000, created_at: daysAgo(10) },
+ { network: 'devnet', graduated: false, mcap: 0, created_at: daysAgo(5) },
+ ],
+ payments: { confirmed_payments: 12, unique_payers: 9 },
+ burns: { runs: 2 },
+ reputation: { rank: 3 },
+ });
+ expect(m.launchesTotal).toBe(3);
+ expect(m.mainnetLaunches).toBe(2);
+ expect(m.graduations).toBe(1);
+ expect(m.topMcap).toBe(120_000);
+ expect(m.uniquePayers).toBe(9);
+ expect(m.burnRuns).toBe(2);
+ expect(m.reputationRank).toBe(3);
+ expect(Math.round(m.ageDays)).toBe(200);
+ });
+
+ it('defends against missing/garbage inputs', () => {
+ const m = deriveMetrics({});
+ expect(m.launchesTotal).toBe(0);
+ expect(m.graduations).toBe(0);
+ expect(m.topMcap).toBe(0);
+ expect(m.ageDays).toBe(0);
+ });
+});
+
+describe('computeAchievements — awards', () => {
+ it('awards the graduate badge when a launch migrated (the headline signal)', () => {
+ const result = computeAchievements({
+ now: NOW,
+ agentCreatedAt: daysAgo(45),
+ launches: [{ network: 'mainnet', graduated: true, mcap: 80_000, created_at: daysAgo(40) }],
+ payments: {},
+ burns: {},
+ });
+ const grad = byId(result, 'graduate');
+ expect(grad.earned).toBe(true);
+ expect(grad.tier).toBe('gold');
+ // earnedAt is pulled from the launch's real timestamp.
+ expect(grad.earnedAt).toBe(daysAgo(40));
+ // First launch + 30-day tenure also unlock here.
+ expect(byId(result, 'trailblazer').earned).toBe(true);
+ expect(byId(result, 'established').earned).toBe(true);
+ // But not the harder migration / mcap / tenure tiers.
+ expect(byId(result, 'migrator').earned).toBe(false);
+ expect(byId(result, 'seven-figures').earned).toBe(false);
+ expect(byId(result, 'veteran').earned).toBe(false);
+ });
+
+ it('awards seven-figures only past $1M peak market cap', () => {
+ const justUnder = computeAchievements({
+ now: NOW, launches: [{ network: 'mainnet', mcap: 999_000, graduated: true, created_at: daysAgo(1) }],
+ });
+ expect(byId(justUnder, 'seven-figures').earned).toBe(false);
+ expect(byId(justUnder, 'six-figures').earned).toBe(true);
+
+ const over = computeAchievements({
+ now: NOW, launches: [{ network: 'mainnet', mcap: 2_500_000, graduated: true, created_at: daysAgo(1) }],
+ });
+ expect(byId(over, 'seven-figures').earned).toBe(true);
+ });
+
+ it('awards community tiers by distinct supporters', () => {
+ const result = computeAchievements({ now: NOW, payments: { unique_payers: 12 } });
+ expect(byId(result, 'first-supporter').earned).toBe(true);
+ expect(byId(result, 'crowd-backed').earned).toBe(true);
+ expect(byId(result, 'fan-favorite').earned).toBe(false);
+ });
+
+ it('awards reputation badges by tier rank', () => {
+ const trusted = computeAchievements({ now: NOW, reputation: { rank: 3, tier: 'trusted', tierLabel: 'Trusted' } });
+ expect(byId(trusted, 'trusted-operator').earned).toBe(true);
+ expect(byId(trusted, 'elite-operator').earned).toBe(false);
+
+ const elite = computeAchievements({ now: NOW, reputation: { rank: 4, tier: 'elite', tierLabel: 'Elite' } });
+ expect(byId(elite, 'elite-operator').earned).toBe(true);
+ });
+});
+
+describe('computeAchievements — progress + summary', () => {
+ it('reports honest progress on a locked badge', () => {
+ const result = computeAchievements({ now: NOW, payments: { unique_payers: 7 } });
+ const crowd = byId(result, 'crowd-backed'); // target 10
+ expect(crowd.earned).toBe(false);
+ expect(crowd.progress.value).toBe(7);
+ expect(crowd.progress.target).toBe(10);
+ expect(crowd.progress.pct).toBeCloseTo(0.7, 5);
+ });
+
+ it('summarizes earned count, top tier, and headline stats', () => {
+ const result = computeAchievements({
+ now: NOW,
+ agentCreatedAt: daysAgo(400),
+ // 15 launches (clears the launch-count tiers); the peak crosses $1M and
+ // all graduated (clears the migration tiers).
+ launches: Array.from({ length: 15 }, (_, i) => ({
+ network: 'mainnet',
+ graduated: true,
+ mcap: i === 0 ? 1_500_000 : 90_000,
+ created_at: daysAgo(300 - i * 10),
+ })),
+ payments: { unique_payers: 60, confirmed_payments: 200 },
+ burns: { runs: 11 },
+ reputation: { rank: 4, tier: 'elite', tierLabel: 'Elite' },
+ });
+ expect(result.summary.graduations).toBe(15);
+ expect(result.summary.topMcap).toBe(1_500_000);
+ expect(result.summary.uniquePayers).toBe(60);
+ expect(result.summary.reputationTier).toBe('Elite');
+ // A maxed-out agent earns every achievement; top tier is legendary.
+ expect(result.summary.earnedCount).toBe(ACHIEVEMENTS.length);
+ expect(result.summary.total).toBe(ACHIEVEMENTS.length);
+ expect(result.summary.topTier).toBe('legendary');
+ });
+
+ it('an empty agent earns nothing and has a null top tier', () => {
+ const result = computeAchievements({ now: NOW });
+ expect(result.earned).toHaveLength(0);
+ expect(result.summary.earnedCount).toBe(0);
+ expect(result.summary.topTier).toBe(null);
+ // Every catalog entry is still present as a locked goal.
+ expect(result.locked).toHaveLength(ACHIEVEMENTS.length);
+ });
+});
+
+describe('catalog integrity', () => {
+ it('has unique ids and known tiers', () => {
+ const ids = ACHIEVEMENTS.map((a) => a.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ for (const a of ACHIEVEMENTS) {
+ expect(TIER_RANK[a.tier]).toBeTypeOf('number');
+ expect(a.threshold).toBeGreaterThan(0);
+ }
+ });
+});