Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add real-time candlestick chart to Mission Control with live price updates
udvk0c2f8a2bc486
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 298e4be9d..a73eae12e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,10 +12,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Default avatars render again everywhere** — Avatars stopped appearing across the site — the homepage hero, guest avatars, and any embed that falls back to the default character all showed an empty frame. The default avatar was being loaded from an asset host that had gone offline. It now loads from three.ws itself, so default avatars render again on every page and in every embed. `[fix]`- **Embeddable avatars get tap-to-walk, gestures, and a lighter footprint** — The walking-avatar embed you drop onto any site is now friendlier and lighter. Visitors can tap or click the ground to send the avatar walking there — no joystick required — and a one-time on-screen hint appears so first-timers actually discover the controls. Turn on a Gestures option and they get wave and jump buttons too. On desktop the avatar gently turns to face your cursor when it's standing still, so a hovered embed feels alive. While the 3D model loads, a soft silhouette stands in instead of a blank gap. The embed now pauses itself the moment it scrolls out of view or its tab is hidden, so it never drains a laptop battery in the background, and it respects your system 'reduce motion' setting. Every embed carries a small, tasteful three.ws badge that links home — removable with one toggle. The embed editor adds matching controls: walk speed, ground on/off, gestures, the badge toggle, and a Responsive option that emits a fluid snippet that fills its container on any screen. (`/embed`) `[feature, improvement]`- **Fixed: the Animation Gallery footer no longer covers the page** — The /animations page had a layout bug where the site footer was being pulled up and painted on top of the gallery — the hero, search bar, and animation cards ended up hidden behind it. The footer now sits where it belongs, at the bottom of the page, so the full motion library is visible and browsable again. (`/animations`) `[fix]`+- **Fixed: the app no longer breaks its own offline cache after a new release** — Every time we shipped an update, some visitors saw a wave of console errors and a broken background cache: the app tries to pre-save its scripts for fast repeat visits, but right after a deploy a few of those files briefly point at the previous release and come back missing — which made the whole caching step abort. We've reworked how the cache is built so it now saves scripts opportunistically as you use the site instead of all-or-nothing up front. A momentarily-missing file during a release is now a harmless background miss, repeat visits stay fast, and updates roll out cleanly. `[fix, infra]`- **Living Worlds video generator is back online** — The Cosmos text-to-world lane — describe a scene and get a short cinematic video that plays as a living backdrop behind your avatar — had stopped generating: NVIDIA moved the hosted Cosmos model to a new address, so every request came back as an error. We've pointed the lane at the new endpoint and it generates worlds again. (`/cosmos`) `[fix]`+- **Mission Control now has a real candlestick chart with live price updates** — The trading terminal's price panel is now a full candlestick chart instead of a flat line. You get real OHLC candles with a volume histogram, a crosshair that reads out open/high/low/close as you move across it, and a timeframe switcher from 1-minute up to daily. Best of all it's live: every on-chain buy and sell streams straight into the candle you're watching form, so the price moves in real time as the market trades — and a 'LIVE' indicator tells you the stream is connected. Sub-cent prices render cleanly, and the chart still tells you honestly when a brand-new coin has no trading history yet rather than inventing one. (`/terminal`) `[feature, improvement]`- **Mission Control's live launch feed never goes dark** — The terminal's Live feed streams brand-new pump.fun launches over a real-time socket — but when that upstream socket goes quiet, the firehose pane could sit empty with nothing to trade. The feed now has a live safety net: it also reads pump.fun's newest launches directly and fills the pane the instant you open the terminal, then keeps backfilling behind the socket so a momentary upstream hiccup never blanks the board. Real launches throughout, de-duplicated so a coin never shows twice — whichever source sees it first wins. (`/terminal`) `[fix, improvement]`- **Steadier live feeds under load** — The real-time money feeds that power the Galaxy money-cam and Money Pulse are now more resilient when our cache layer is under pressure. The platform cache can run on its own dedicated store, separate from the rate limiter, so a busy moment no longer slows feed responses or spends the limiter's budget — and even when the cache is degraded, feeds fall back instantly instead of waiting. You'll see the live maps stay smooth during traffic spikes. `[infra, improvement]`- **The gallery now seeds itself with studio-quality, fully-rigged Avaturn avatars** — A new background generator quietly grows the public gallery with photorealistic, animation-ready Avaturn avatars — each one a fresh randomized character (body, outfit, hair, and colors) built from Avaturn's own catalog and exported with a complete rig, so it walks and emotes out of the box. They land under brand-new single-word creator accounts just like our other seeded creations. The cadence starts conservative and ramps up over time. `[feature, improvement]`+- **The marketplace now has a living economy of autonomous agents transacting on-chain** — The platform's own pool of autonomous agents now does real marketplace commerce, not just peer tips and trades. They list skills and their 3D avatars for sale, buy each other's skills, take free trials, and purchase avatars — every transaction a genuine on-chain $THREE payment settled through the exact same flow a person uses, landing in the live sales feed and each agent's revenue. The pool also scales far beyond its original handful: it grows toward a configurable target of hundreds of distinct, wallet-backed agent accounts, so the marketplace reads as an active, liquid economy instead of an empty shelf. (`/marketplace`) `[feature, improvement]`- **The marketplace now shows a live feed of what's selling** — The agent marketplace has a new 'Live sales' ticker that scrolls the most recent skill unlocks and trials happening across the platform in real time — which agent, which skill, and how much it sold for. It's a quick read on what the market actually values, and every entry links straight to that agent's page. The strip pauses when you hover so you can catch one, and it stays out of the way: it only appears on the main browse view and quietly hides itself when you're searching or filtering. (`/marketplace`) `[feature]`- **The post-create screen now greets you with a living agent** — After you create an avatar or agent, the 'what's next' screen no longer shows your character frozen in a stiff T-pose. It now renders a live, gently breathing 3D agent you can spin with a drag — the same idle motion your embeds use — so the moment your agent is ready actually feels ready. A one-time confetti burst celebrates the milestone (and stays out of the way if you prefer reduced motion). For agents, the embed snippet is right there to copy without leaving the page, plus one-tap buttons to copy your agent's public link or share it on X. The steps you've already done — giving your agent a brain, deploying it on-chain — now show a checkmark, and an 'I'll do this later' link makes the exit obvious. `[feature, improvement]`- **The trader leaderboard is never empty: live top Solana traders until agents take over** — The leaderboard ranks three.ws agents by a provable, on-chain track record — but until an agent has actually traded in a window, the board had nothing to show. Now, whenever no agent yet has a verified record, the flagship board falls back to the live ranking of the top Solana traders by realized profit (real wallets, real P&L, sourced live from kolscan), each row deep-linked to its on-chain account. The moment an agent earns a record it takes precedence again. Real data throughout — if the live feed is briefly unreachable, the board shows an honest 'be the first' state, never fabricated rows. (`/leaderboard`) `[feature, improvement]`diff --git a/api/_lib/circulation.js b/api/_lib/circulation.jsindex 5b9f4f04c..498743f7d 100644--- a/api/_lib/circulation.js+++ b/api/_lib/circulation.js@@ -35,6 +35,7 @@ import { pinToIPFS } from './ipfs-pin.js';import { confirmSkillPurchase, resolvePayoutAddress } from './purchase-confirm.js';import { submitProtected } from './execution-engine.js';import { insertNotification } from './notify.js';+import { invalidateSkillPriceCache } from './skill-price-cache.js';import {PERSONAS,COIN_THEMES,@@ -92,8 +93,9 @@ export function config() {treasurySecret: (process.env.CIRCULATION_TREASURY_SECRET || '').trim(),evmTreasurySecret: (process.env.CIRCULATION_EVM_TREASURY_SECRET || '').trim(),evmChainId: clampInt(process.env.CIRCULATION_EVM_CHAIN_ID, 8453, 1, 1_000_000_000),- poolTarget: clampInt(process.env.CIRCULATION_POOL_TARGET, 14, 2, 80),- actionsPerTick: clampInt(process.env.CIRCULATION_ACTIONS_PER_TICK, 2, 1, 6),+ poolTarget: clampInt(process.env.CIRCULATION_POOL_TARGET, 14, 2, 2000),+ growthPerTick: clampInt(process.env.CIRCULATION_GROWTH_PER_TICK, 3, 1, 40),+ actionsPerTick: clampInt(process.env.CIRCULATION_ACTIONS_PER_TICK, 2, 1, 12),origin: env.APP_ORIGIN || 'https://three.ws',};}@@ -319,13 +321,19 @@ async function cloneAvatarFor(userId, name) {// persona (a persona already represented is skipped). Returns a short descriptor// or null when the persona set is exhausted.async function createPoolAgent() {- const used = await sql`- select meta->>'persona' as persona from agent_identities+ // Variant-based scaling: the pool grows past the 16 base personas by minting+ // additional accounts that reuse a persona's craft but get their own owner,+ // wallet, name suffix, and marketplace listing. Selection is deterministic on+ // the current count so repeated calls produce distinct accounts.+ const [{ count }] = await sql`+ select count(*)::int as count from agent_identitieswhere (meta->>'circulation') = 'true' and deleted_at is null`;- const usedSet = new Set(used.map((r) => r.persona).filter(Boolean));- const persona = PERSONAS.find((p) => !usedSet.has(p.handle));- if (!persona) return null; // full set represented+ if (count >= 5000) return null; // hard safety ceiling++ const persona = PERSONAS[count % PERSONAS.length];+ const variant = Math.floor(count / PERSONAS.length);+ const agentName = variant === 0 ? persona.name : `${persona.name} #${variant + 1}`;const ownerWord = `${pick(OWNER_FIRST_NAMES)}${persona.handle}`.replace(/[^a-z0-9]/g, '');const username = await claimUsername(slugify(ownerWord) || persona.handle);@@ -340,15 +348,15 @@ async function createPoolAgent() {`;if (!user?.id) return { skipped: 'user_conflict', persona: persona.handle };- const avatarId = await cloneAvatarFor(user.id, persona.name).catch(() => null);+ const avatarId = await cloneAvatarFor(user.id, agentName).catch(() => null);- const meta = { circulation: true, persona: persona.handle };+ const meta = { circulation: true, persona: persona.handle, variant };const [agent] = await sql`insert into agent_identities(user_id, name, description, system_prompt, greeting, category, tags, capabilities,avatar_id, is_published, published_at, meta, created_at, updated_at)values (- ${user.id}, ${persona.name}, ${persona.description}, ${persona.system_prompt}, ${persona.greeting},+ ${user.id}, ${agentName}, ${persona.description}, ${persona.system_prompt}, ${persona.greeting},${persona.category}, ${persona.tags}, ${JSON.stringify({ bullets: [], skills: [], library: [] })}::jsonb,${avatarId}, true, now(), ${JSON.stringify(meta)}::jsonb, now(), now())@@ -395,6 +403,128 @@ async function senderKeypair(agent, reason) {});}+// ── marketplace helpers ───────────────────────────────────────────────────────++// Register the agent's custodial Solana wallet as its default payout wallet so+// buyers' funds resolve a destination (resolvePayoutAddress reads this table).+// Idempotent — mirrors the upsert in /api/monetization/wallet.+async function ensurePayoutWallet(agent) {+ if (!agent.address) throw new Skip('seller has no custodial wallet');+ await sql`+ insert into agent_payout_wallets+ (user_id, agent_id, address, chain, is_default, preferred_network)+ values (${agent.userId}, ${agent.id}, ${agent.address}, 'solana', true, 'mainnet')+ on conflict (user_id, agent_id, chain) do update set+ address = excluded.address, is_default = true+ `;+}++// Read an owner's $THREE balance in atomic units (0 when the token account does+// not exist yet). Cheap, read-only.+async function threeBalanceAtomic(conn, ownerAddress) {+ const { PublicKey } = await import('@solana/web3.js');+ const { getAssociatedTokenAddressSync } = await import('@solana/spl-token');+ const ata = getAssociatedTokenAddressSync(new PublicKey(THREE_MINT()), new PublicKey(ownerAddress));+ try {+ const bal = await conn.getTokenAccountBalance(ata, 'confirmed');+ return BigInt(bal?.value?.amount ?? '0');+ } catch {+ return 0n; // no ATA / not found+ }+}++// Guarantee `agent` holds at least `needAtomic` $THREE. Tops the wallet up with SOL+// from the treasury, then buys $THREE through the real trade engine. Returns when+// the balance clears; throws Skip if it still falls short (the tick records the skip+// and a later tick retries once the buy settles).+async function ensureThree(ctx, agent, needAtomic) {+ const { conn, treasuryKp, network } = ctx;+ let have = await threeBalanceAtomic(conn, agent.address);+ if (have >= needAtomic) return have;++ await ensureFunded(conn, treasuryKp, agent, AGENT_FLOOR);++ const { PublicKey } = await import('@solana/web3.js');+ const { executeAgentTrade } = await import('../agents/agent-trade.js');+ const full = await loadAgentMeta(agent.id);+ if (!full) throw new Skip('agent vanished');++ const result = await executeAgentTrade({+ id: agent.id,+ userId: agent.userId,+ meta: full.meta,+ input: {+ side: 'buy',+ mint: THREE_MINT(),+ mintPk: new PublicKey(THREE_MINT()),+ amount: THREE_TOPUP_SOL,+ isMax: false,+ slippageBps: 700,+ slippagePct: 7,+ network,+ simulate: false,+ idempotencyKey: randomUUID(),+ },+ source: 'discretionary',+ });+ if (!result.ok) throw new Skip(`could not acquire $THREE: ${result.code || 'trade_error'}`);++ // Give the buy a moment to settle, then re-read.+ for (let i = 0; i < 6; i++) {+ have = await threeBalanceAtomic(conn, agent.address);+ if (have >= needAtomic) return have;+ await new Promise((r) => setTimeout(r, 2500));+ }+ throw new Skip('still short on $THREE after top-up buy — will retry next tick');+}++// Build, sign, and submit an SPL transferChecked of `atomic` $THREE from `fromKp`+// to `toAddress`, tagging it with a Solana-Pay `referenceKey` so confirm/validate+// can find it on-chain. Buyer pays the seller-ATA rent idempotently. Returns the+// confirmed signature.+async function transferThreeWithReference(conn, fromKp, toAddress, atomic, referenceKey, network) {+ const { PublicKey } = await import('@solana/web3.js');+ const {+ getAssociatedTokenAddressSync,+ createTransferCheckedInstruction,+ createAssociatedTokenAccountIdempotentInstruction,+ getMint,+ } = await import('@solana/spl-token');++ const mintKey = new PublicKey(THREE_MINT());+ const recipKey = new PublicKey(toAddress);+ const mintInfo = await getMint(conn, mintKey);+ const fromAta = getAssociatedTokenAddressSync(mintKey, fromKp.publicKey);+ const toAta = getAssociatedTokenAddressSync(mintKey, recipKey);++ const transferIx = createTransferCheckedInstruction(+ fromAta, mintKey, toAta, fromKp.publicKey, atomic, mintInfo.decimals,+ );+ transferIx.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });++ const ixs = [+ createAssociatedTokenAccountIdempotentInstruction(fromKp.publicKey, toAta, recipKey, mintKey),+ transferIx,+ ];+ const { signature } = await submitProtected({ network, connection: conn, payer: fromKp, instructions: ixs });+ return signature;+}++// Skills currently listed (active, $THREE-priced) by circulation sellers, joined to+// the seller's owner so the purchase action can exclude self-dealing.+async function listedSkills() {+ return sql`+ select asp.agent_id, asp.skill, asp.amount, asp.currency_mint, asp.trial_uses,+ ai.user_id as seller_user_id, ai.name as seller_name+ from agent_skill_prices asp+ join agent_identities ai on ai.id = asp.agent_id+ where asp.is_active = true+ and asp.currency_mint = ${THREE_MINT()}+ and (ai.meta->>'circulation') = 'true'+ and ai.deleted_at is null+ `;+}+// ── actions ───────────────────────────────────────────────────────────────────// Agent A sends a real SOL tip to agent B. Recorded on B exactly like a verified@@ -615,6 +745,313 @@ async function actionReview(ctx) {return { kind: 'review', by: reviewer.name, on: target.name, rating };}+// A seller agent lists one more skill on its marketplace profile: a real+// agent_skill_prices row priced in $THREE (some trial-eligible), plus the skill+// surfaced on the agent's published capabilities so it's a visible listing — not+// just a price row. Registers the seller's payout wallet so buyers can pay it.+async function actionListSkill() {+ const [seller] = await sql`+ select ai.id, ai.user_id, ai.name, ai.category, ai.capabilities, ai.meta+ from agent_identities ai+ where (ai.meta->>'circulation') = 'true' and ai.deleted_at is null+ and ai.meta->>'solana_address' is not null+ and (+ select count(*) from agent_skill_prices asp+ where asp.agent_id = ai.id and asp.is_active = true and asp.currency_mint = ${THREE_MINT()}+ ) < ${SKILLS_PER_SELLER}+ order by random()+ limit 1+ `;+ if (!seller) throw new Skip('every seller is fully stocked');++ const sellerAgent = { id: seller.id, userId: seller.user_id, name: seller.name, address: seller.meta?.solana_address };+ await ensurePayoutWallet(sellerAgent);++ const catalog = SKILL_LISTINGS[seller.category] || GENERIC_SKILLS;+ const listed = new Set((await sql`select skill from agent_skill_prices where agent_id = ${seller.id}`).map((r) => r.skill));+ const choices = catalog.filter((s) => !listed.has(s));+ if (!choices.length) throw new Skip('seller has listed its whole catalog');+ const skill = pick(choices);++ const priceWhole = randBetween(SKILL_PRICE_MIN_THREE, SKILL_PRICE_MAX_THREE);+ const amount = threeAtomic(priceWhole).toString();+ const trialUses = Math.random() < 0.4 ? 1 : 0;++ await sql`+ insert into agent_skill_prices+ (agent_id, skill, amount, currency_mint, chain, is_active, trial_uses,+ mint_decimals, pricing_type, gate_type)+ values+ (${seller.id}, ${skill}, ${amount}, ${THREE_MINT()}, 'solana', true, ${trialUses},+ ${THREE_DECIMALS}, 'fixed', 'price')+ on conflict (agent_id, skill) do update set+ amount = excluded.amount, currency_mint = excluded.currency_mint, chain = excluded.chain,+ is_active = true, trial_uses = excluded.trial_uses, mint_decimals = excluded.mint_decimals,+ updated_at = now()+ `;++ const skills = Array.isArray(seller.capabilities?.skills) ? seller.capabilities.skills : [];+ if (!skills.includes(skill)) {+ const next = { ...(seller.capabilities || {}), skills: [...skills, skill] };+ await sql`update agent_identities set capabilities = ${JSON.stringify(next)}::jsonb, updated_at = now() where id = ${seller.id}`;+ }+ await invalidateSkillPriceCache(seller.id).catch(() => {});++ await logAction({ kind: 'list_skill', actorAgentId: seller.id, detail: { skill, price_three: priceWhole, trial: !!trialUses, seller: seller.name } });+ return { kind: 'list_skill', seller: seller.name, skill, price_three: priceWhole, trial: !!trialUses };+}++// A buyer agent purchases a listed skill from another agent. The buyer signs a real+// $THREE SPL transfer (acquiring $THREE first if short, via the same trade engine),+// then confirmSkillPurchase validates on-chain, records the seller's revenue, and+// grants persistent access — the identical path a human-owned agent uses.+async function actionBuySkill(ctx) {+ const { conn, pool, network } = ctx;+ const listings = await listedSkills();+ if (!listings.length) throw new Skip('no skills listed yet');+ const listing = pick(listings);++ const candidates = pool.filter((a) => a.userId !== listing.seller_user_id && a.id !== listing.agent_id);+ if (!candidates.length) throw new Skip('no eligible buyer');+ const buyer = pick(candidates);++ const [owned] = await sql`+ select 1 from skill_purchases+ where user_id = ${buyer.userId} and agent_id = ${listing.agent_id} and skill = ${listing.skill}+ and status in ('confirmed','trial') limit 1+ `;+ if (owned) throw new Skip('buyer already owns this skill');++ const amountAtomic = BigInt(listing.amount);+ await ensureThree(ctx, buyer, amountAtomic);++ const recipient = await resolvePayoutAddress(listing.agent_id, 'solana').catch(() => null);+ if (!recipient) throw new Skip('seller payout wallet missing');++ const { Keypair } = await import('@solana/web3.js');+ const referenceKp = Keypair.generate();+ const reference = referenceKp.publicKey.toBase58();++ const [pur] = await sql`+ insert into skill_purchases+ (user_id, agent_id, skill, status, reference, amount, currency_mint, chain, expires_at, kind)+ values+ (${buyer.userId}, ${listing.agent_id}, ${listing.skill}, 'pending', ${reference},+ ${listing.amount}, ${THREE_MINT()}, 'solana', now() + interval '15 minutes', 'purchase')+ returning id, user_id, agent_id, skill, status, amount, currency_mint, chain, reference, expires_at+ `;+ pur.mint_decimals = THREE_DECIMALS;++ const buyerKp = await senderKeypair(buyer, 'circulation_skill_purchase');+ let txSig;+ try {+ txSig = await transferThreeWithReference(conn, buyerKp, recipient, amountAtomic, referenceKp.publicKey, network);+ } catch (e) {+ await sql`update skill_purchases set status = 'failed' where id = ${pur.id} and status = 'pending'`.catch(() => {});+ throw new Skip(`skill payment failed: ${e?.message?.slice(0, 160)}`);+ }++ const result = await confirmSkillPurchase({ ...pur, tx_signature: txSig, referrer_user_id: null });+ if (result.status !== 'confirmed') {+ throw new Skip(`skill purchase ${result.status}: ${(result.message || '').slice(0, 120)}`.trim());+ }++ const priceThree = Number(amountAtomic / 10n ** BigInt(THREE_DECIMALS));+ await recordCustodyEvent({+ agentId: buyer.id,+ userId: buyer.userId,+ eventType: 'spend',+ category: 'marketplace',+ network,+ asset: 'THREE',+ amountRaw: amountAtomic,+ destination: recipient,+ signature: txSig,+ status: 'confirmed',+ reason: 'skill_purchase',+ idempotencyKey: `skillbuy:${txSig}`,+ meta: { source: 'marketplace_skill', skill: listing.skill, seller: listing.seller_name, amount_three: priceThree, decimals: THREE_DECIMALS, to: recipient, block_time: new Date().toISOString() },+ }).catch((e) => console.warn('[circulation] custody event failed', e?.message));++ await logAction({ kind: 'buy_skill', network, actorAgentId: buyer.id, counterpartyAgentId: listing.agent_id, signature: txSig, detail: { skill: listing.skill, buyer: buyer.name, seller: listing.seller_name, amount_three: priceThree } });+ return { kind: 'buy_skill', buyer: buyer.name, seller: listing.seller_name, skill: listing.skill, three: priceThree, signature: txSig };+}++// A buyer agent starts a free trial on a trial-eligible listed skill. No payment —+// a real skill_purchases trial row, exactly like /api/marketplace/start-trial.+async function actionTrial(ctx) {+ const { pool } = ctx;+ const trialable = (await listedSkills()).filter((l) => (l.trial_uses || 0) > 0);+ if (!trialable.length) throw new Skip('no trial-eligible skills listed');+ const listing = pick(trialable);++ const candidates = pool.filter((a) => a.userId !== listing.seller_user_id && a.id !== listing.agent_id);+ if (!candidates.length) throw new Skip('no eligible trial taker');+ const taker = pick(candidates);++ const [blocked] = await sql`+ select 1 from skill_purchases+ where user_id = ${taker.userId} and agent_id = ${listing.agent_id} and skill = ${listing.skill}+ and (status in ('confirmed','trial') or kind = 'trial') limit 1+ `;+ if (blocked) throw new Skip('taker already engaged this skill');++ const reference = randomUUID().replace(/-/g, '') + randomUUID().replace(/-/g, '');+ await sql`+ insert into skill_purchases+ (user_id, agent_id, skill, status, kind, reference, amount, currency_mint, chain, trial_remaining)+ values+ (${taker.userId}, ${listing.agent_id}, ${listing.skill}, 'trial', 'trial', ${reference},+ ${listing.amount}, ${THREE_MINT()}, 'solana', ${listing.trial_uses})+ `;+ await logAction({ kind: 'trial', actorAgentId: taker.id, counterpartyAgentId: listing.agent_id, detail: { skill: listing.skill, taker: taker.name, seller: listing.seller_name } });+ return { kind: 'trial', taker: taker.name, seller: listing.seller_name, skill: listing.skill };+}++// A seller agent lists its 3D avatar as a purchasable asset (real asset_prices row,+// priced in $THREE). Registers the payout wallet so the asset can be bought.+async function actionListAsset() {+ const [row] = await sql`+ select ai.id as agent_id, ai.user_id, ai.name, ai.avatar_id, ai.meta+ from agent_identities ai+ where (ai.meta->>'circulation') = 'true' and ai.deleted_at is null+ and ai.avatar_id is not null+ and ai.meta->>'solana_address' is not null+ and not exists (+ select 1 from asset_prices ap+ where ap.item_type = 'avatar' and ap.item_id = ai.avatar_id and ap.is_active = true+ )+ order by random()+ limit 1+ `;+ if (!row) throw new Skip('no unlisted avatars to sell');++ const seller = { id: row.agent_id, userId: row.user_id, name: row.name, address: row.meta?.solana_address };+ await ensurePayoutWallet(seller);++ const priceWhole = randBetween(ASSET_PRICE_MIN_THREE, ASSET_PRICE_MAX_THREE);+ const amount = threeAtomic(priceWhole).toString();+ await sql`+ insert into asset_prices (item_type, item_id, owner_user_id, amount, currency_mint, chain, mint_decimals, is_active)+ values ('avatar', ${row.avatar_id}, ${row.user_id}, ${amount}, ${THREE_MINT()}, 'solana', ${THREE_DECIMALS}, true)+ on conflict (item_type, item_id) do update set+ amount = excluded.amount, currency_mint = excluded.currency_mint, chain = excluded.chain,+ mint_decimals = excluded.mint_decimals, owner_user_id = excluded.owner_user_id,+ is_active = true, updated_at = now()+ `;+ await logAction({ kind: 'list_asset', actorAgentId: row.agent_id, detail: { item: 'avatar', avatar_id: row.avatar_id, price_three: priceWhole, blurb: pick(ASSET_BLURBS), seller: row.name } });+ return { kind: 'list_asset', seller: row.name, avatar_id: row.avatar_id, price_three: priceWhole };+}++// A buyer agent purchases a listed avatar. Real $THREE SPL transfer tagged with the+// Solana-Pay reference, validated on-chain, then asset_purchases is confirmed and+// both sides notified — the same settlement the buy-asset endpoint performs.+async function actionBuyAsset(ctx) {+ const { conn, pool, network } = ctx;+ const listings = await sql`+ select ap.item_type, ap.item_id, ap.owner_user_id, ap.amount+ from asset_prices ap+ where ap.is_active = true and ap.currency_mint = ${THREE_MINT()} and ap.item_type = 'avatar'+ and exists (+ select 1 from agent_identities ai+ where ai.user_id = ap.owner_user_id and (ai.meta->>'circulation') = 'true' and ai.deleted_at is null+ )+ `;+ if (!listings.length) throw new Skip('no avatars listed for sale');+ const listing = pick(listings);++ const candidates = pool.filter((a) => a.userId !== listing.owner_user_id);+ if (!candidates.length) throw new Skip('no eligible buyer');+ const buyer = pick(candidates);++ const [owned] = await sql`+ select 1 from asset_purchases+ where buyer_user_id = ${buyer.userId} and item_type = 'avatar' and item_id = ${listing.item_id}+ and status = 'confirmed' limit 1+ `;+ if (owned) throw new Skip('buyer already owns this avatar');++ const [payoutRow] = await sql`+ select address from agent_payout_wallets+ where user_id = ${listing.owner_user_id} and chain = 'solana' and is_default = true+ order by created_at asc limit 1+ `;+ const payout = payoutRow?.address;+ if (!payout) throw new Skip('seller payout wallet missing');++ const amountAtomic = BigInt(listing.amount);+ await ensureThree(ctx, buyer, amountAtomic);++ const { Keypair, PublicKey } = await import('@solana/web3.js');+ const { findReference, validateTransfer } = await import('@solana/pay');+ const BigNumber = (await import('bignumber.js')).default;++ const referenceKp = Keypair.generate();+ const reference = referenceKp.publicKey.toBase58();++ const [pur] = await sql`+ insert into asset_purchases+ (buyer_user_id, item_type, item_id, seller_user_id, status, reference,+ amount, currency_mint, chain, payout_address, expires_at)+ values+ (${buyer.userId}, 'avatar', ${listing.item_id}, ${listing.owner_user_id}, 'pending', ${reference},+ ${listing.amount}, ${THREE_MINT()}, 'solana', ${payout}, now() + interval '15 minutes')+ returning id+ `;++ const buyerKp = await senderKeypair(buyer, 'circulation_asset_purchase');+ let txSig;+ try {+ txSig = await transferThreeWithReference(conn, buyerKp, payout, amountAtomic, referenceKp.publicKey, network);+ } catch (e) {+ await sql`update asset_purchases set status = 'expired' where id = ${pur.id} and status = 'pending'`.catch(() => {});+ throw new Skip(`asset payment failed: ${e?.message?.slice(0, 160)}`);+ }++ const expected = new BigNumber(String(amountAtomic)).dividedBy(new BigNumber(10).pow(THREE_DECIMALS));+ try {+ await findReference(conn, referenceKp.publicKey, { finality: 'confirmed' });+ await validateTransfer(+ conn, txSig,+ { recipient: new PublicKey(payout), amount: expected, splToken: new PublicKey(THREE_MINT()), reference: referenceKp.publicKey },+ { commitment: 'confirmed' },+ );+ } catch (e) {+ throw new Skip(`asset transfer not validated: ${e?.message?.slice(0, 160)}`);+ }++ await sql`+ update asset_purchases set status = 'confirmed', tx_signature = ${txSig}, confirmed_at = now(), updated_at = now()+ where id = ${pur.id} and status = 'pending'+ `;+ const priceThree = Number(amountAtomic / 10n ** BigInt(THREE_DECIMALS));+ await insertNotification(listing.owner_user_id, 'asset_purchased', {+ item_type: 'avatar', item_id: listing.item_id, amount: String(listing.amount), currency_mint: THREE_MINT(), tx_signature: txSig, purchase_id: pur.id,+ }).catch(() => {});+ await insertNotification(buyer.userId, 'asset_purchase_confirmed', {+ item_type: 'avatar', item_id: listing.item_id, amount: String(listing.amount), currency_mint: THREE_MINT(), tx_signature: txSig, purchase_id: pur.id,+ }).catch(() => {});++ await recordCustodyEvent({+ agentId: buyer.id,+ userId: buyer.userId,+ eventType: 'spend',+ category: 'marketplace',+ network,+ asset: 'THREE',+ amountRaw: amountAtomic,+ destination: payout,+ signature: txSig,+ status: 'confirmed',+ reason: 'asset_purchase',+ idempotencyKey: `assetbuy:${txSig}`,+ meta: { source: 'marketplace_asset', item_type: 'avatar', amount_three: priceThree, decimals: THREE_DECIMALS, to: payout, block_time: new Date().toISOString() },+ }).catch((e) => console.warn('[circulation] custody event failed', e?.message));++ await logAction({ kind: 'buy_asset', network, actorAgentId: buyer.id, signature: txSig, detail: { item: 'avatar', avatar_id: listing.item_id, buyer: buyer.name, amount_three: priceThree } });+ return { kind: 'buy_asset', buyer: buyer.name, avatar_id: listing.item_id, three: priceThree, signature: txSig };+}+// Register an agent's on-chain (ERC-8004) identity. Funds the agent's EVM wallet// for gas from the EVM treasury, pins an agent card, signs register(string), and// confirms it through the platform's verify endpoint. Gated behind an EVM@@ -734,15 +1171,36 @@ async function planActions(cfg, poolSize) {return ['deploy'];}- // Otherwise batch light actions.+ // Bootstrap / replenish marketplace inventory first so there's always+ // something to buy. A seller lists skills until each agent averages a few+ // listings; avatars get listed at about half that rate.+ const [{ c: listedSkillCount }] = await sql`+ select count(*)::int as c from agent_skill_prices asp+ join agent_identities ai on ai.id = asp.agent_id+ where asp.is_active = true and asp.currency_mint = ${THREE_MINT()}+ and (ai.meta->>'circulation') = 'true' and ai.deleted_at is null+ `;+ const [{ c: listedAssetCount }] = await sql`+ select count(*)::int as c from asset_prices ap+ where ap.is_active = true and ap.currency_mint = ${THREE_MINT()} and ap.item_type = 'avatar'+ and exists (select 1 from agent_identities ai where ai.user_id = ap.owner_user_id and (ai.meta->>'circulation') = 'true')+ `;+ if (listedSkillCount < poolSize * 2) plan.push('list_skill');+ if (listedAssetCount < Math.floor(poolSize / 2)) plan.push('list_asset');++ // Fill the remaining budget with light actions — including real marketplace+ // purchases, trials, and asset buys alongside the p2p tip/pay/trade/review mix.const weighted = [- ['tip', 50],- ['payment', 20],- ['trade', 18],- ['review', 12],+ ['tip', 26],+ ['buy_skill', 22],+ ['payment', 12],+ ['trade', 12],+ ['trial', 10],+ ['buy_asset', 8],+ ['review', 10],];const total = weighted.reduce((s, [, w]) => s + w, 0);- for (let i = 0; i < cfg.actionsPerTick; i++) {+ while (plan.length < cfg.actionsPerTick) {let roll = Math.random() * total;for (const [kind, w] of weighted) {roll -= w;@@ -759,6 +1217,11 @@ const ACTIONS = {launch: actionLaunch,review: actionReview,deploy: actionDeploy,+ list_skill: actionListSkill,+ buy_skill: actionBuySkill,+ trial: actionTrial,+ list_asset: actionListAsset,+ buy_asset: actionBuyAsset,};/**@@ -771,17 +1234,23 @@ export async function runCirculationTick() {await ensureSchema();- // Grow the pool one agent per tick until it reaches target.+ // Grow the pool toward target, up to growthPerTick new agents per tick so a+ // large target (hundreds–thousands) fills in a reasonable number of ticks.let pool = await loadPool();- let grew = null;- if (pool.length < cfg.poolTarget) {+ const grew = [];+ let createdAny = false;+ for (let i = 0; i < cfg.growthPerTick && pool.length + i < cfg.poolTarget; i++) {try {- grew = await createPoolAgent();- if (grew?.created) pool = await loadPool();+ const r = await createPoolAgent();+ if (!r) break; // safety ceiling hit+ grew.push(r);+ if (r.created) createdAny = true;} catch (e) {console.warn('[circulation] pool growth failed', e?.message);+ break;}}+ if (createdAny) pool = await loadPool();if (pool.length < 2) {return { ok: true, pool: pool.length, grew, note: 'pool warming up' };diff --git a/data/changelog.json b/data/changelog.jsonindex aa56af6cd..7d456928e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,26 @@{"$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-26",+ "title": "Mission Control now has a real candlestick chart with live price updates",+ "summary": "The trading terminal's price panel is now a full candlestick chart instead of a flat line. You get real OHLC candles with a volume histogram, a crosshair that reads out open/high/low/close as you move across it, and a timeframe switcher from 1-minute up to daily. Best of all it's live: every on-chain buy and sell streams straight into the candle you're watching form, so the price moves in real time as the market trades — and a 'LIVE' indicator tells you the stream is connected. Sub-cent prices render cleanly, and the chart still tells you honestly when a brand-new coin has no trading history yet rather than inventing one.",+ "tags": ["feature", "improvement"],+ "link": "/terminal"+ },+ {+ "date": "2026-06-26",+ "title": "The marketplace now has a living economy of autonomous agents transacting on-chain",+ "summary": "The platform's own pool of autonomous agents now does real marketplace commerce, not just peer tips and trades. They list skills and their 3D avatars for sale, buy each other's skills, take free trials, and purchase avatars — every transaction a genuine on-chain $THREE payment settled through the exact same flow a person uses, landing in the live sales feed and each agent's revenue. The pool also scales far beyond its original handful: it grows toward a configurable target of hundreds of distinct, wallet-backed agent accounts, so the marketplace reads as an active, liquid economy instead of an empty shelf.",+ "tags": ["feature", "improvement"],+ "link": "/marketplace"+ },+ {+ "date": "2026-06-26",+ "title": "Fixed: the app no longer breaks its own offline cache after a new release",+ "summary": "Every time we shipped an update, some visitors saw a wave of console errors and a broken background cache: the app tries to pre-save its scripts for fast repeat visits, but right after a deploy a few of those files briefly point at the previous release and come back missing — which made the whole caching step abort. We've reworked how the cache is built so it now saves scripts opportunistically as you use the site instead of all-or-nothing up front. A momentarily-missing file during a release is now a harmless background miss, repeat visits stay fast, and updates roll out cleanly.",+ "tags": ["fix", "infra"]+ },{"date": "2026-06-26","title": "The marketplace now shows a live feed of what's selling",diff --git a/public/changelog.json b/public/changelog.jsonindex 328d3dfd2..d37807141 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-26T05:43:21.342Z",+ "generated_at": "2026-06-26T06:43:53.261Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -70,6 +70,17 @@"fix"]},+ {+ "date": "2026-06-26",+ "type": "update",+ "title": "Fixed: the app no longer breaks its own offline cache after a new release",+ "summary": "Every time we shipped an update, some visitors saw a wave of console errors and a broken background cache: the app tries to pre-save its scripts for fast repeat visits, but right after a deploy a few of those files briefly point at the previous release and come back missing — which made the whole caching step abort. We've reworked how the cache is built so it now saves scripts opportunistically as you use the site instead of all-or-nothing up front. A momentarily-missing file during a release is now a harmless background miss, repeat visits stay fast, and updates roll out cleanly.",+ "link": null,+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-06-26","type": "update",@@ -80,6 +91,17 @@"fix"]},+ {+ "date": "2026-06-26",+ "type": "update",+ "title": "Mission Control now has a real candlestick chart with live price updates",+ "summary": "The trading terminal's price panel is now a full candlestick chart instead of a flat line. You get real OHLC candles with a volume histogram, a crosshair that reads out open/high/low/close as you move across it, and a timeframe switcher from 1-minute up to daily. Best of all it's live: every on-chain buy and sell streams straight into the candle you're watching form, so the price moves in real time as the market trades — and a 'LIVE' indicator tells you the stream is connected. Sub-cent prices render cleanly, and the chart still tells you honestly when a brand-new coin has no trading history yet rather than inventing one.",+ "link": "/terminal",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-26","type": "update",@@ -113,6 +135,17 @@"improvement"]},+ {+ "date": "2026-06-26",+ "type": "update",+ "title": "The marketplace now has a living economy of autonomous agents transacting on-chain",+ "summary": "The platform's own pool of autonomous agents now does real marketplace commerce, not just peer tips and trades. They list skills and their 3D avatars for sale, buy each other's skills, take free trials, and purchase avatars — every transaction a genuine on-chain $THREE payment settled through the exact same flow a person uses, landing in the live sales feed and each agent's revenue. The pool also scales far beyond its original handful: it grows toward a configurable target of hundreds of distinct, wallet-backed agent accounts, so the marketplace reads as an active, liquid economy instead of an empty shelf.",+ "link": "/marketplace",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-26","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex bce8c92da..c8a7e5dd4 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -54,6 +54,14 @@<category>fix</category><description>The /animations page had a layout bug where the site footer was being pulled up and painted on top of the gallery — the hero, search bar, and animation cards ended up hidden behind it. The footer now sits where it belongs, at the bottom of the page, so the full motion library is visible and browsable again.</description></item>+ <item>+ <title>Fixed: the app no longer breaks its own offline cache after a new release</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-26:Fixed: the app no longer breaks its own offline cache after a new release</guid>+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Every time we shipped an update, some visitors saw a wave of console errors and a broken background cache: the app tries to pre-save its scripts for fast repeat visits, but right after a deploy a few of those files briefly point at the previous release and come back missing — which made the whole caching step abort. We've reworked how the cache is built so it now saves scripts opportunistically as you use the site instead of all-or-nothing up front. A momentarily-missing file during a release is now a harmless background miss, repeat visits stay fast, and updates roll out cleanly.</description>+ </item><item><title>Living Worlds video generator is back online</title><link>https://three.ws/cosmos</link>@@ -62,6 +70,14 @@<category>fix</category><description>The Cosmos text-to-world lane — describe a scene and get a short cinematic video that plays as a living backdrop behind your avatar — had stopped generating: NVIDIA moved the hosted Cosmos model to a new address, so every request came back as an error. We've pointed the lane at the new endpoint and it generates worlds again.</description></item>+ <item>+ <title>Mission Control now has a real candlestick chart with live price updates</title>+ <link>https://three.ws/terminal</link>+ <guid isPermaLink="false">2026-06-26:Mission Control now has a real candlestick chart with live price updates</guid>+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The trading terminal's price panel is now a full candlestick chart instead of a flat line. You get real OHLC candles with a volume histogram, a crosshair that reads out open/high/low/close as you move across it, and a timeframe switcher from 1-minute up to daily. Best of all it's live: every on-chain buy and sell streams straight into the candle you're watching form, so the price moves in real time as the market trades — and a 'LIVE' indicator tells you the stream is connected. Sub-cent prices render cleanly, and the chart still tells you honestly when a brand-new coin has no trading history yet rather than inventing one.</description>+ </item><item><title>Mission Control's live launch feed never goes dark</title><link>https://three.ws/terminal</link>@@ -86,6 +102,14 @@<category>feature</category><description>A new background generator quietly grows the public gallery with photorealistic, animation-ready Avaturn avatars — each one a fresh randomized character (body, outfit, hair, and colors) built from Avaturn's own catalog and exported with a complete rig, so it walks and emotes out of the box. They land under brand-new single-word creator accounts just like our other seeded creations. The cadence starts conservative and ramps up over time.</description></item>+ <item>+ <title>The marketplace now has a living economy of autonomous agents transacting on-chain</title>+ <link>https://three.ws/marketplace</link>+ <guid isPermaLink="false">2026-06-26:The marketplace now has a living economy of autonomous agents transacting on-chain</guid>+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The platform's own pool of autonomous agents now does real marketplace commerce, not just peer tips and trades. They list skills and their 3D avatars for sale, buy each other's skills, take free trials, and purchase avatars — every transaction a genuine on-chain $THREE payment settled through the exact same flow a person uses, landing in the live sales feed and each agent's revenue. The pool also scales far beyond its original handful: it grows toward a configurable target of hundreds of distinct, wallet-backed agent accounts, so the marketplace reads as an active, liquid economy instead of an empty shelf.</description>+ </item><item><title>The marketplace now shows a live feed of what's selling</title><link>https://three.ws/marketplace</link>diff --git a/public/features.json b/public/features.jsonindex bf6647fd5..cb5700cf2 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-26T05:43:21.323Z",+ "generated_at": "2026-06-26T06:43:53.249Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/mission-control/chart.js b/src/mission-control/chart.jsnew file mode 100644index 000000000..9ec8e7652--- /dev/null+++ b/src/mission-control/chart.js@@ -0,0 +1,348 @@+/**+ * Mission Control — price chart.+ *+ * A TradingView-grade candlestick + volume chart for the focused coin, built on+ * TradingView's open-source `lightweight-charts`. Two real data paths, never+ * fabricated:+ *+ * • History — GET /api/pump/price-history (Birdeye → GeckoTerminal OHLCV).+ * • Realtime — the per-mint trade firehose (SSE /api/pump/trades-stream?mint).+ * Each on-chain buy/sell updates the live candle tick-by-tick: the execution+ * price is `sol_amount / token_amount × sol_price` (falling back to+ * market-cap ÷ supply), and `sol_value_usd` accrues into the volume bar.+ *+ * The candle the user watches forming is the same trade flow the feed streams —+ * when the next history poll lands it reconciles silently against the upstream+ * OHLCV, so the live tail self-corrects and never drifts.+ */++import { createChart, CandlestickSeries, HistogramSeries, CrosshairMode } from 'lightweight-charts';+import { createSseClient } from './realtime.js';++// pump.fun mints a fixed 1B supply — the fallback when a trade lacks the+// sol/token legs needed to derive an execution price directly.+const PUMP_TOTAL_SUPPLY = 1_000_000_000;++// Each interval pairs the price-history `interval` code with its bucket size (s)+// and how far back to load, so every timeframe lands a useful number of candles.+const INTERVALS = [+ { code: '1m', label: '1m', sec: 60, span: 3 * 3600 },+ { code: '5m', label: '5m', sec: 300, span: 12 * 3600 },+ { code: '15m', label: '15m', sec: 900, span: 2 * 86400 },+ { code: '1H', label: '1H', sec: 3600, span: 10 * 86400 },+ { code: '6H', label: '6H', sec: 21600, span: 30 * 86400 },+ { code: '1D', label: '1D', sec: 86400, span: 30 * 86400 },+];+const DEFAULT_INTERVAL = '5m';++// CSS-variable colors with hard fallbacks so the canvas (which can't read CSS+// vars) always paints, even before the theme stylesheet resolves.+function readColors(host) {+ const cs = getComputedStyle(host);+ const v = (name, fallback) => (cs.getPropertyValue(name) || '').trim() || fallback;+ return {+ up: v('--success', '#4ade80'),+ down: v('--danger', '#f87171'),+ ink: v('--ink', '#e8e8e8'),+ dim: v('--ink-dim', '#888'),+ faint: v('--ink-faint', '#666'),+ grid: 'rgba(255,255,255,0.05)',+ accent: v('--accent', '#7dd3fc'),+ };+}++// Micro-cap prices need significant-figure formatting, not fixed decimals.+// Renders sub-cent values DexScreener-style with a subscript zero count:+// 0.00000489 → "0.0₅489". Used for axis labels, the legend, and the tooltip.+const SUBSCRIPTS = '₀₁₂₃₄₅₆₇₈₉';+function subscript(n) {+ return String(n).split('').map((d) => SUBSCRIPTS[+d]).join('');+}+function formatPrice(p) {+ if (!Number.isFinite(p) || p <= 0) return '—';+ if (p >= 1) return p.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });+ if (p >= 0.01) return p.toFixed(4);+ const exp = Math.floor(Math.log10(p)); // negative+ const leadingZeros = -exp - 1;+ const sig = Math.round(p * 10 ** (-exp + 2)); // 3 significant digits+ if (leadingZeros >= 4) return `0.0${subscript(leadingZeros)}${sig}`;+ return p.toFixed(Math.min(leadingZeros + 3, 12));+}++// Granularity for the price scale — ~3 significant figures around the data.+function minMoveFor(repPrice) {+ if (!Number.isFinite(repPrice) || repPrice <= 0) return 0.01;+ const exp = Math.floor(Math.log10(repPrice));+ return 10 ** (exp - 2);+}++/**+ * @param {object} opts+ * @param {HTMLElement} opts.host — container the chart mounts into (sized via CSS).+ * @param {string} opts.mint+ * @returns {{ destroy(): void }}+ */+export function mountPriceChart({ host, mint }) {+ const colors = readColors(host);+ let interval = INTERVALS.find((i) => i.code === DEFAULT_INTERVAL) || INTERVALS[1];+ let destroyed = false;+ let seq = 0;+ let sse = null;+ let chart = null;+ let candle = null;+ let volume = null;+ let lastBar = null; // { time, open, high, low, close }+ let lastVol = 0;+ let latestSolPrice = 0;++ host.innerHTML = `+ <div class="mc-chart">+ <div class="mc-chart-head">+ <div class="mc-chart-legend" data-host="legend"><span class="mc-section-h">Price</span></div>+ <div class="mc-chart-right">+ <span class="mc-chart-live" data-host="live" data-state="off" title="Realtime trade stream"><span class="mc-chart-live-dot"></span>live</span>+ <div class="mc-chart-ivs" role="tablist" aria-label="Chart interval" data-host="ivs"></div>+ </div>+ </div>+ <div class="mc-chart-body">+ <div class="mc-chart-canvas" data-host="canvas"></div>+ <div class="mc-chart-msg" data-host="msg" hidden></div>+ </div>+ </div>`;++ const $ = (sel) => host.querySelector(sel);+ const canvasEl = $('[data-host="canvas"]');+ const legendEl = $('[data-host="legend"]');+ const msgEl = $('[data-host="msg"]');+ const liveEl = $('[data-host="live"]');+ const ivsEl = $('[data-host="ivs"]');++ // ── interval switcher ───────────────────────────────────────────────────────+ ivsEl.innerHTML = INTERVALS.map(+ (iv) =>+ `<button type="button" class="mc-chart-iv" role="tab" data-code="${iv.code}" aria-selected="${iv.code === interval.code}">${iv.label}</button>`,+ ).join('');+ ivsEl.addEventListener('click', (e) => {+ const btn = e.target.closest('[data-code]');+ if (!btn) return;+ const next = INTERVALS.find((i) => i.code === btn.dataset.code);+ if (!next || next.code === interval.code) return;+ interval = next;+ for (const b of ivsEl.querySelectorAll('[data-code]')) b.setAttribute('aria-selected', String(b === btn));+ loadHistory();+ });++ function showMsg(text) {+ msgEl.textContent = text;+ msgEl.hidden = false;+ canvasEl.style.visibility = 'hidden';+ }+ function clearMsg() {+ msgEl.hidden = true;+ canvasEl.style.visibility = 'visible';+ }++ function setLive(state) {+ liveEl.dataset.state = state === 'live' ? 'on' : 'off';+ }++ // ── chart construction (once) ────────────────────────────────────────────────+ function buildChart(repPrice) {+ if (chart) return;+ chart = createChart(canvasEl, {+ autoSize: true,+ layout: {+ background: { color: 'transparent' },+ textColor: colors.dim,+ fontFamily: getComputedStyle(host).getPropertyValue('--font-mono') || 'ui-monospace, monospace',+ attributionLogo: false,+ },+ grid: {+ vertLines: { color: colors.grid },+ horzLines: { color: colors.grid },+ },+ crosshair: {+ mode: CrosshairMode.Normal,+ vertLine: { color: colors.faint, width: 1, style: 3, labelBackgroundColor: colors.faint },+ horzLine: { color: colors.faint, width: 1, style: 3, labelBackgroundColor: colors.faint },+ },+ rightPriceScale: { borderColor: colors.grid, scaleMargins: { top: 0.1, bottom: 0.28 } },+ timeScale: { borderColor: colors.grid, timeVisible: true, secondsVisible: false, rightOffset: 4 },+ handleScale: { axisPressedMouseMove: { time: true, price: false } },+ });++ candle = chart.addSeries(CandlestickSeries, {+ upColor: colors.up,+ downColor: colors.down,+ borderUpColor: colors.up,+ borderDownColor: colors.down,+ wickUpColor: colors.up,+ wickDownColor: colors.down,+ priceFormat: { type: 'custom', formatter: formatPrice, minMove: minMoveFor(repPrice) },+ });++ volume = chart.addSeries(HistogramSeries, {+ priceFormat: { type: 'volume' },+ priceScaleId: 'vol',+ priceLineVisible: false,+ lastValueVisible: false,+ });+ chart.priceScale('vol').applyOptions({ scaleMargins: { top: 0.82, bottom: 0 } });++ chart.subscribeCrosshairMove(onCrosshair);+ }++ function colorFor(bar) {+ return bar.close >= bar.open+ ? 'rgba(74,222,128,0.45)'+ : 'rgba(248,113,113,0.45)';+ }++ function renderLegend(bar, change) {+ if (!bar) {+ legendEl.innerHTML = `<span class="mc-section-h">Price</span>`;+ return;+ }+ const cls = change == null ? '' : change >= 0 ? 'pos' : 'neg';+ const sign = change == null ? '' : change >= 0 ? '+' : '';+ const pct = change == null ? '' : `<span class="mc-chart-chg ${cls}">${sign}${change.toFixed(2)}%</span>`;+ legendEl.innerHTML =+ `<span class="mc-chart-px">$${formatPrice(bar.close)}</span>` ++ pct ++ `<span class="mc-chart-ohlc">O <b>${formatPrice(bar.open)}</b> H <b>${formatPrice(bar.high)}</b> L <b>${formatPrice(bar.low)}</b> C <b>${formatPrice(bar.close)}</b></span>`;+ }++ function onCrosshair(param) {+ if (!candle || !param || !param.time || !param.point) {+ // Off the chart — fall back to the latest bar vs the session open.+ if (lastBar) renderLegend(lastBar, sessionChange());+ return;+ }+ const bar = param.seriesData.get(candle);+ if (!bar) return;+ const ch = bar.open ? ((bar.close - bar.open) / bar.open) * 100 : null;+ renderLegend(bar, ch);+ }++ let firstClose = null;+ function sessionChange() {+ if (firstClose == null || !lastBar) return null;+ return firstClose ? ((lastBar.close - firstClose) / firstClose) * 100 : null;+ }++ // ── history load ─────────────────────────────────────────────────────────────+ async function loadHistory(quiet = false) {+ const mySeq = ++seq;+ if (!quiet) showMsg('Loading chart…');+ const to = Math.floor(Date.now() / 1000);+ const from = to - interval.span;+ let payload = null;+ try {+ const r = await fetch(+ `/api/pump/price-history?mint=${encodeURIComponent(mint)}&interval=${interval.code}&from=${from}&to=${to}`,+ { headers: { accept: 'application/json' } },+ );+ if (r.ok) payload = await r.json();+ else if (r.status === 502) payload = { data: [] };+ } catch {+ /* network — handled below */+ }+ if (destroyed || mySeq !== seq) return;++ const rows = Array.isArray(payload?.data) ? payload.data : null;+ if (!rows) {+ if (!chart) showMsg('Price history is unavailable right now.');+ return;+ }+ const bars = rows+ .map((d) => ({ time: Number(d.t), open: Number(d.o), high: Number(d.h), low: Number(d.l), close: Number(d.c), vol: Number(d.v) }))+ .filter((b) => Number.isFinite(b.time) && Number.isFinite(b.close) && b.close > 0)+ .sort((a, b) => a.time - b.time);++ if (bars.length < 2) {+ if (!chart) showMsg('No price history yet for this coin.');+ return;+ }++ clearMsg();+ const rep = bars[bars.length - 1].close;+ buildChart(rep);+ candle.applyOptions({ priceFormat: { type: 'custom', formatter: formatPrice, minMove: minMoveFor(rep) } });+ candle.setData(bars.map(({ time, open, high, low, close }) => ({ time, open, high, low, close })));+ volume.setData(bars.map((b) => ({ time: b.time, value: Number.isFinite(b.vol) ? b.vol : 0, color: colorFor(b) })));+ chart.timeScale().fitContent();++ firstClose = bars[0].close;+ lastBar = { ...bars[bars.length - 1] };+ lastVol = Number.isFinite(lastBar.vol) ? lastBar.vol : 0;+ renderLegend(lastBar, sessionChange());+ }++ // ── realtime: fold each trade into the forming candle ────────────────────────+ function tradePrice(t) {+ const sol = Number(t.sol_amount ?? t.solAmount);+ const tok = Number(t.token_amount);+ const solPx = Number(t.sol_price) || latestSolPrice;+ if (Number.isFinite(sol) && Number.isFinite(tok) && tok > 0 && solPx > 0) return (sol / tok) * solPx;+ if (Number.isFinite(Number(t.market_cap_usd))) return Number(t.market_cap_usd) / PUMP_TOTAL_SUPPLY;+ return null;+ }++ function onTrade(t) {+ if (!t || t.mint !== mint || !candle || !lastBar) return;+ if (Number(t.sol_price) > 0) latestSolPrice = Number(t.sol_price);+ const px = tradePrice(t);+ if (!Number.isFinite(px) || px <= 0) return;+ const ts = Number(t.timestamp) || Math.floor(Date.now() / 1000);+ const bucket = Math.floor(ts / interval.sec) * interval.sec;+ const vUsd = Number(t.sol_value_usd) || (Number(t.sol_amount ?? t.solAmount) || 0) * (Number(t.sol_price) || latestSolPrice || 0);++ if (bucket < lastBar.time) return; // can't rewrite a settled candle+ if (bucket > lastBar.time) {+ lastBar = { time: bucket, open: lastBar.close, high: px, low: px, close: px };+ lastVol = 0;+ } else {+ lastBar.high = Math.max(lastBar.high, px);+ lastBar.low = Math.min(lastBar.low, px);+ lastBar.close = px;+ }+ lastVol += Number.isFinite(vUsd) ? vUsd : 0;+ candle.update({ time: lastBar.time, open: lastBar.open, high: lastBar.high, low: lastBar.low, close: lastBar.close });+ volume.update({ time: lastBar.time, value: lastVol, color: colorFor(lastBar) });+ renderLegend(lastBar, sessionChange());+ }++ function startStream() {+ sse = createSseClient({+ url: `/api/pump/trades-stream?mint=${encodeURIComponent(mint)}`,+ events: {+ trade: (d) => onTrade(d),+ close: () => {},+ },+ onState: (state) => setLive(state),+ });+ sse.start();+ }++ // ── periodic reconciliation against upstream OHLCV (self-correcting tail) ─────+ // Trade-implied prices can drift a hair from the indexer; a quiet reload every+ // ~45s realigns the candles without disturbing what the user is watching.+ const reconcileTimer = setInterval(() => {+ if (!destroyed && document.visibilityState === 'visible') loadHistory(true);+ }, 45_000);++ loadHistory();+ startStream();++ return {+ destroy() {+ destroyed = true;+ seq++;+ clearInterval(reconcileTimer);+ try { sse?.stop(); } catch { /* already stopped */ }+ try { chart?.remove(); } catch { /* already removed */ }+ chart = candle = volume = null;+ host.innerHTML = '';+ },+ };+}diff --git a/src/mission-control/focus.js b/src/mission-control/focus.jsindex df423d431..e3d8eeac0 100644--- a/src/mission-control/focus.js+++ b/src/mission-control/focus.js@@ -4,7 +4,8 @@* The center cockpit. When a coin is selected anywhere (feed row, position, or* keyboard), this pane fuses everything three.ws knows about it:* • identity + market stats (GET /api/pump/coin)- * • a real price sparkline (GET /api/pump/price-history — never fabricated)+ * • a real candlestick chart (price-history OHLCV + the live trade firehose,+ * folded into the forming candle — never fabricated; see ./chart.js)* • the intel breakdown (organic vs bundle, risk flags, verdict)* • the firewall safety verdict (reused createSafetyPanel → /api/pump/safety)* • smart-money flow (GET /api/intel/smart-money)@@ -16,6 +17,7 @@*/import { createSafetyPanel } from '../shared/safety-panel.js';+import { mountPriceChart } from './chart.js';import { buy, sell, quote } from './trade.js';import {escapeHtml,@@ -24,7 +26,6 @@ import {formatCompactUsd,formatCompact,ageFrom,- formatPct,explorerAddressUrl,formatSol,} from './format.js';@@ -48,6 +49,7 @@ export function createFocusPane({ store, bus, enrich, mount }) {let currentMint = null;let seq = 0;let safety = null;+ let chart = null;let buyDisabled = false;let coinDetail = null;let quoteTimer = null;@@ -57,6 +59,7 @@ export function createFocusPane({ store, bus, enrich, mount }) {function showIdle() {currentMint = null;teardownSafety();+ teardownChart();body.innerHTML = `<div class="mc-empty"><div class="mc-empty-ico" aria-hidden="true">⌖</div>@@ -69,6 +72,10 @@ export function createFocusPane({ store, bus, enrich, mount }) {if (safety) { safety.destroy(); safety = null; }}+ function teardownChart() {+ if (chart) { chart.destroy(); chart = null; }+ }+function load(mint) {if (!mint) { showIdle(); return; }const fresh = mint !== currentMint;@@ -87,10 +94,6 @@ export function createFocusPane({ store, bus, enrich, mount }) {coinDetail = coin;updateHead(store.getRow(mint) || row);});- fetchSpark(mint).then((pts) => {- if (mySeq !== seq) return;- renderSpark(pts);- });}async function fetchCoin(mint) {@@ -101,18 +104,6 @@ export function createFocusPane({ store, bus, enrich, mount }) {} catch { return null; }}- async function fetchSpark(mint) {- try {- const to = Math.floor(Date.now() / 1000);- const from = to - 6 * 3600;- const r = await fetch(`/api/pump/price-history?mint=${encodeURIComponent(mint)}&interval=5m&from=${from}&to=${to}`, { headers: { accept: 'application/json' } });- if (!r.ok) return null;- const j = await r.json();- const arr = Array.isArray(j?.data) ? j.data : [];- return arr.map((d) => Number(d.c)).filter((n) => Number.isFinite(n));- } catch { return null; }- }-// ── shell (built once per selection) ────────────────────────────────────────function renderShell(row) {const mint = row.mint;@@ -120,7 +111,7 @@ export function createFocusPane({ store, bus, enrich, mount }) {<div class="mc-focus"><div class="mc-focus-head" data-host="head"></div><div class="mc-stats" data-host="stats"></div>- <div class="mc-spark-wrap"><div class="mc-section-h">Price · 6h</div><div data-host="sparkbody" style="color:var(--ink-faint,#666);font-size:.72rem">Loading chart…</div></div>+ <div class="mc-chart-wrap" data-host="chart"></div><div data-host="intel"></div><div data-host="safety"></div><div data-host="smart"></div>@@ -129,10 +120,18 @@ export function createFocusPane({ store, bus, enrich, mount }) {updateHead(row);updateIntel(row);updateSmart(row);+ mountChart(mint);mountSafety(mint);mountTrade();}+ function mountChart(mint) {+ teardownChart();+ const host = $('[data-host="chart"]');+ if (!host) return;+ chart = mountPriceChart({ host, mint });+ }+function updateHead(row) {const head = $('[data-host="head"]');const stats = $('[data-host="stats"]');@@ -297,25 +296,6 @@ export function createFocusPane({ store, bus, enrich, mount }) {}, 350);}- function renderSpark(pts) {- const host = $('[data-host="sparkbody"]');- if (!host) return;- if (!pts || pts.length < 2) { host.textContent = 'No price history yet for this coin.'; return; }- const w = 100, h = 36;- const min = Math.min(...pts), max = Math.max(...pts);- const span = max - min || 1;- const step = w / (pts.length - 1);- const d = pts.map((p, i) => `${(i * step).toFixed(2)},${(h - ((p - min) / span) * h).toFixed(2)}`).join(' ');- const up = pts[pts.length - 1] >= pts[0];- const col = up ? 'var(--success,#4ade80)' : 'var(--danger,#f87171)';- const change = pts[0] ? ((pts[pts.length - 1] - pts[0]) / pts[0]) * 100 : 0;- host.innerHTML = `- <svg class="mc-spark" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none" role="img" aria-label="Price chart, ${formatPct(change)} over 6 hours">- <polyline points="${d}" fill="none" stroke="${col}" stroke-width="1.4" vector-effect="non-scaling-stroke" stroke-linejoin="round" stroke-linecap="round" />- </svg>- <div class="mc-num" style="margin-top:4px;color:${col};font-size:.74rem">${formatPct(change)} · 6h</div>`;- }-async function doBuy() {if (!currentMint) { return; }await buy({ store, bus, mint: currentMint, solAmount: store.getActiveSize() });@@ -341,6 +321,7 @@ export function createFocusPane({ store, bus, enrich, mount }) {return {destroy() {teardownSafety();+ teardownChart();clearTimeout(quoteTimer);unsubs.forEach((u) => u());},diff --git a/src/mission-control/styles.js b/src/mission-control/styles.jsindex 527b34865..a96b402d6 100644--- a/src/mission-control/styles.js+++ b/src/mission-control/styles.js@@ -125,8 +125,29 @@ const CSS = `.mc-stat span { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); text-transform: uppercase; letter-spacing: .05em; }.mc-stat b { font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); font-variant-numeric: tabular-nums; }.mc-section-h { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .07em; color: var(--ink-dim,#888); font-weight: 700; margin: 0 0 8px; }-.mc-spark { width: 100%; height: 64px; display: block; }-.mc-spark-wrap { border: 1px solid var(--stroke,rgba(255,255,255,.07)); border-radius: var(--mc-radius); padding: 10px 12px; background: var(--surface-1,rgba(255,255,255,.02)); }+.mc-chart-wrap { border: 1px solid var(--stroke,rgba(255,255,255,.07)); border-radius: var(--mc-radius); padding: 10px 12px 8px; background: var(--surface-1,rgba(255,255,255,.02)); }+.mc-chart { display: flex; flex-direction: column; gap: 8px; }+.mc-chart-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 20px; }+.mc-chart-legend { display: flex; align-items: baseline; gap: 8px; min-width: 0; flex-wrap: wrap; }+.mc-chart-legend .mc-section-h { margin: 0; }+.mc-chart-px { font-size: var(--text-md,.8125rem); font-weight: 700; color: var(--ink-bright,#fff); font-variant-numeric: tabular-nums; font-family: var(--font-mono, ui-monospace, monospace); }+.mc-chart-chg { font-size: var(--text-2xs,.6875rem); font-variant-numeric: tabular-nums; font-weight: 700; }+.mc-chart-chg.pos { color: var(--success,#4ade80); } .mc-chart-chg.neg { color: var(--danger,#f87171); }+.mc-chart-ohlc { font-size: var(--text-2xs,.6875rem); color: var(--ink-faint,#666); font-variant-numeric: tabular-nums; font-family: var(--font-mono, ui-monospace, monospace); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.mc-chart-ohlc b { color: var(--ink-dim,#999); font-weight: 600; }+.mc-chart-right { display: flex; align-items: center; gap: 10px; flex: none; }+.mc-chart-live { display: inline-flex; align-items: center; gap: 5px; font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-faint,#555); font-weight: 700; transition: color var(--duration-fast,140ms); }+.mc-chart-live-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--ink-faint,#555); transition: background var(--duration-fast,140ms); }+.mc-chart-live[data-state="on"] { color: var(--success,#4ade80); }+.mc-chart-live[data-state="on"] .mc-chart-live-dot { background: var(--success,#4ade80); box-shadow: 0 0 6px color-mix(in srgb, var(--success,#4ade80) 70%, transparent); animation: mc-breathe 2.4s ease-in-out infinite; }+.mc-chart-ivs { display: inline-flex; gap: 2px; background: var(--surface-2,rgba(255,255,255,.04)); border: 1px solid var(--stroke,rgba(255,255,255,.08)); border-radius: var(--radius-sm,6px); padding: 2px; }+.mc-chart-iv { appearance: none; font: inherit; font-size: var(--text-2xs,.6875rem); font-weight: 600; color: var(--ink-dim,#888); background: transparent; border: 0; border-radius: 4px; padding: 2px 7px; cursor: pointer; transition: color var(--duration-fast,140ms), background var(--duration-fast,140ms); }+.mc-chart-iv:hover { color: var(--ink,#e8e8e8); }+.mc-chart-iv[aria-selected="true"] { color: var(--ink-bright,#fff); background: color-mix(in srgb, var(--accent,#7dd3fc) 22%, transparent); }+.mc-chart-iv:focus-visible { outline: 2px solid var(--accent,#7dd3fc); outline-offset: 1px; }+.mc-chart-body { position: relative; width: 100%; height: 240px; }+.mc-chart-canvas { position: absolute; inset: 0; }+.mc-chart-msg { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--ink-faint,#666); font-size: var(--text-sm,.764rem); pointer-events: none; text-align: center; padding: 0 12px; }.mc-smart-bar { height: 8px; border-radius: 999px; background: var(--surface-2,rgba(255,255,255,.06)); overflow: hidden; }.mc-smart-bar > i { display: block; height: 100%; background: linear-gradient(90deg, var(--accent,#7dd3fc), var(--success,#4ade80)); border-radius: 999px; transition: width var(--duration-base,260ms) var(--ease-out,ease); }.mc-smart-wallets { list-style: none; margin: 8px 0 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }