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
THREE buyback math module, x402 plumbing, club gate, and changelog updates
nirholas502cf5cf9556
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3ff4fe8ec..3c5f8700e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Holding $THREE now unlocks a premium feature** — $THREE gets its first hard utility: High-quality 3D generation on Forge — the 200k-polygon, PBR-textured tier — is now reserved for $THREE holders. Reach the Bronze holder tier (the entry tier) by holding $THREE and the High tier unlocks automatically, with no payment step. Draft and Standard generation stay free forever, and bring-your-own-key generation is unaffected. Sign in, link your Solana wallet, and the economy page shows your live holder tier and exactly what it unlocks. (`/three`) `[feature]`- **Leaving a review on an agent profile works again** — Submitting or updating a star rating on an agent's profile was quietly failing for signed-in users — the form said “Save failed” no matter what, because the security token that protects the save was being read incorrectly and never attached. Reviews now save on the first try. Signed-out visitors who tap Submit get a clear “Sign in to leave a review” prompt instead of a dead button, and agent profiles no longer log errors for agents that have no on-chain trading record — the track-record card simply stays hidden. `[fix]`- **Pay $THREE per High generation — no holding required** — Don't hold $THREE yet but want a High-quality model? You can now pay in $THREE for a single High generation instead. Pick High in Forge, choose "Pay" on the holder panel, and a clean payment flow prices it in $THREE, takes one wallet approval, verifies it on-chain, and runs your generation automatically. The platform now genuinely accepts $THREE for compute. One payment buys exactly one High generation, and if a generation fails before it runs your payment stays usable — you're never charged for a model you didn't get. Draft and Standard remain free, and holders still generate High straight away. (`/forge`) `[feature]`+- **Platform revenue now buys back $THREE onchain — and you can watch it** — The $THREE page has a new Programmatic buybacks panel that turns the protocol's economy into something you can verify, not just read about. Platform revenue is converted into $THREE bought on the open market and routed straight into the treasury — onchain, on a schedule, with every buy recorded against its Solscan receipt. This creates steady buy pressure for holders without ever burning supply. The panel shows how much revenue has been earned and what share of it has already been deployed into buybacks, so the link between the platform earning money and that money supporting $THREE is fully transparent. (`/three-token`) `[feature, infra]`- **Play is movable on phones again — and avatars load instead of a placeholder** — Two fixes for Play. On phones, the item hotbar had drifted on top of the on-screen movement joystick in the bottom-left corner, so taps meant to steer the stick landed on the hotbar instead and your character wouldn't move at all — with no keyboard to fall back on, you were stuck. The hotbar now sits in a clear band above the joystick, leaving the whole stick tappable. Separately, every avatar — yours, other players', and the loading-screen preview — had started appearing as a plain capsule stand-in because the app was missing the decoder for the compression format the avatars ship in; that decoder is now wired in, so real, animated avatars load everywhere in Play again. `[fix]`- **Play loads reliably in private windows and embeds, and explains itself if 3D can't start** — Two ways Play could fail silently are fixed. First: if your browser couldn't start 3D graphics — hardware acceleration switched off, an older device, or some in-app browsers — Play used to sit on the loading screen forever with no explanation. It now shows a clear recovery card that tells you what happened and how to fix it, with a one-tap “Try again”. Second: opening Play in a private/incognito window, or where it's embedded inside another page, could stop it loading at all because the browser blocks saved settings there. Play now treats blocked storage gracefully — it falls back to a default name and avatar and loads normally instead of breaking. `[fix]`- **Pole Club avatar swaps now actually stick** — On the Pole Club stage, tapping “Change avatar” and picking a new look sometimes did nothing — the dancer quietly snapped back to the default. Two fixes: a pick made right after the room loads is no longer overwritten by the room's own startup, and any avatar whose rig can't be animated is now clearly flagged “can’t dance” and skipped — the dancer keeps her current look and a message says why, instead of silently failing. Picks that work apply instantly and stay put. (`/club`) `[fix]`@@ -23,9 +24,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The disco dance floor in coin worlds works again** — Every coin world has a disco pad beside the totem that pulses to a shared beat and crossfades dancers in lockstep. A wiring gap meant the world tried to listen for a beat the connection didn't know about, which threw an error the moment you entered and left the pad dark. The beat is now delivered properly: step onto the pad, hit Dance, and you and everyone else standing on it move to the same animation on the same beat, with the floor and lights pulsing in time. (`/play`) `[fix]`- **The homepage avatar now prays, then walks** — Tap “🙏 Pray” on the homepage hero and the avatar finishes the prayer and rises straight into a walk — one smooth motion instead of snapping back to a standing idle at the end of the clip. After the walk plays out, the avatar eases back into its gentle idle-and-stroll rhythm. The other one-tap emotes (wave, dance, jump, and the rest) also return to that ambient motion now instead of freezing on their last frame. `[improvement]`- **Tipping a dancer goes straight to the wallet now** — Tapping Tip in the Pole Club used to open a three-step “Before you go on-chain” explainer first, and dismissing it cancelled the tip entirely — so first-time visitors couldn't pay without sitting through the wizard. That gate is gone. Tip now opens the wallet-and-amount checkout directly, where you pick Phantom or a browser wallet, see the exact USDC amount, and approve with one signature. The checkout already shows everything the explainer did, so there's no reason to stack a lecture in front of a fraction-of-a-cent tip. (`/club`) `[improvement]`+- **Tipping a dancer in the Club is now one tap** — In the Pole Club, paying a dancer used to pop an extra step that made you pick your wallet before anything happened — annoying when you just want to tip and watch her dance, and worse when tipping pole after pole. Now, when a single wallet is detected, hitting Tip goes straight to the signature: approve the $0.001 USDC and she takes the pole. The same shortcut applies to the cover charge at the door. If you have more than one wallet installed you still get to choose, and the free re-entry option for returning guests is untouched. (`/club`) `[improvement]`- **Token swaps now confirm success or failure clearly** — When you buy $THREE (or swap any pair) from the swap window, it now tells you exactly how it went. After you approve in your wallet, a banner shows it submitting and confirming on-chain, then resolves to a clear result: a green “Swap confirmed” with the amount you received and a Solscan link, a red on-chain failure with the reason (and a hint to widen slippage when that's the cause), or a “still confirming” notice with a link if the network is slow. Previously a swap could land successfully but the window sat on “Confirming…” indefinitely with no confirmation — because it was waiting on a live socket the swap proxy doesn't carry. It now polls the chain directly and gives you a definite answer in seconds. (`/three-token`) `[fix]`- **You can move the moment a Coin Communities world loads** — On phones, the first-time welcome card in /play covered the whole screen — including the movement joystick — so new players tapped the stick and nothing happened until they dismissed the intro. The welcome card is now a non-blocking overlay: the joystick (and look-drag) stay live behind it and sit crisp on top, so you can start walking the instant the world appears, whether you read the intro first or not. (`/play`) `[fix]`- **Your $THREE holder tier now shows across the site** — Holding $THREE is now visible everywhere you are. A holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) on every page and links to the full tier breakdown. On Forge, choosing the High quality tier now shows a clear, designed panel instead of a silent block: holders see an "Unlocked" badge and generate straight away, while everyone else gets a "Get $THREE" path, the exact reason (sign in, link a wallet, or hold more), and a one-tap switch back to free Draft or Standard — no dead ends and no raw errors. (`/forge`) `[feature, improvement]`+- **Your agent and its answer now sit together in chat** — When an agent replied with a 3D avatar — especially while it was thinking or forging several models at once — the avatar used to float off on its own with a big empty gap, while the reasoning note and the tool buttons drifted down beside its feet. The agent now stands next to its own response: the avatar is framed tighter so it fills its space instead of hovering in the void, and its thinking note and tool calls line up with it as one tidy block. It reads as a single reply whether you're in the normal view or have a tool's details open in the side panel. (`/chat`) `[improvement]`## 2026-06-17diff --git a/api/_lib/token/buyback-math.js b/api/_lib/token/buyback-math.jsnew file mode 100644index 000000000..63566365f--- /dev/null+++ b/api/_lib/token/buyback-math.js@@ -0,0 +1,62 @@+// Pure math + policy parsing for the programmatic $THREE buyback.+//+// Deliberately free of DB / RPC / web3 imports so it can be unit-tested in+// isolation and reused without dragging in the Solana stack. All money math is+// BigInt-on-atomics; only display conversions return Number.++export const USDC_DECIMALS = 6;+export const USDC_ATOMICS = 10n ** BigInt(USDC_DECIMALS);++/** Parse a positive-USD env value, falling back when unset/invalid. */+export function envUsd(raw, fallback) {+ if (raw === undefined || String(raw).trim() === '') return fallback;+ const n = Number(raw);+ return Number.isFinite(n) && n > 0 ? n : fallback;+}++/** Parse a slippage-bps env value (0 < bps ≤ 5000), else fallback. */+export function envSlippageBps(raw, fallback = 300) {+ const n = Number(raw);+ return Number.isFinite(n) && n > 0 && n <= 5000 ? Math.round(n) : fallback;+}++/** Whole USD → USDC atomics (6dp), floored. */+export function usdToUsdcAtomics(usd) {+ return BigInt(Math.floor(Number(usd) * Number(USDC_ATOMICS)));+}++/** USDC atomics (6dp) → whole USD. */+export function usdcAtomicsToUsd(atomics) {+ return Number(BigInt(atomics)) / Number(USDC_ATOMICS);+}++/** Token atomics → whole tokens at the given decimals. */+export function atomicsToTokens(atomics, decimals) {+ return Number(BigInt(atomics)) / 10 ** Number(decimals);+}++/**+ * Decide how much USDC to deploy this run: spend up to the per-run cap, bounded+ * by the wallet's live balance, and only if it clears the minimum (so a run never+ * pays more in fees than it buys). Pure — the single source of sizing truth.+ *+ * @param {bigint|string|number} walletUsdcAtomics live USDC balance (atomics)+ * @param {{ maxUsd: number, minUsd: number }} caps+ * @returns {{ spendAtomics: bigint, reason: 'ok'|'empty'|'below_threshold' }}+ */+export function computeSpend(walletUsdcAtomics, { maxUsd, minUsd }) {+ const wallet = BigInt(walletUsdcAtomics);+ const cap = usdToUsdcAtomics(maxUsd);+ const min = usdToUsdcAtomics(minUsd);+ const spend = wallet > cap ? cap : wallet;+ if (spend < min) {+ return { spendAtomics: 0n, reason: wallet === 0n ? 'empty' : 'below_threshold' };+ }+ return { spendAtomics: spend, reason: 'ok' };+}++/** Share of revenue already deployed to buybacks, clamped to [0,100]. */+export function deployedPct(deployedUsd, revenueUsd) {+ if (!(revenueUsd > 0)) return 0;+ return Math.min(100, (deployedUsd / revenueUsd) * 100);+}diff --git a/api/_lib/token/buyback.js b/api/_lib/token/buyback.jsindex 34a9a4118..c0c609fb7 100644--- a/api/_lib/token/buyback.js+++ b/api/_lib/token/buyback.js@@ -25,18 +25,22 @@ import {import { sql } from '../db.js';import { getConnection, solanaPubkey } from '../pump.js';-import { SOLANA_USDC_MINT } from '../payments/_config.js';+import { SOLANA_USDC_MINT } from '../../payments/_config.js';import { TOKEN_MINT, TOKEN_DECIMALS } from './config.js';import { treasuryWallet, treasuryWalletOrNull } from './config.js';+import {+ computeSpend,+ deployedPct,+ envSlippageBps,+ envUsd,+ usdcAtomicsToUsd as usdcToUsd,+ atomicsToTokens,+} from './buyback-math.js';const JUP_QUOTE_URL = 'https://lite-api.jup.ag/swap/v1/quote';const JUP_SWAP_URL = 'https://lite-api.jup.ag/swap/v1/swap';const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';-const USDC_DECIMALS = 6;-const USDC_ATOMICS = 10n ** BigInt(USDC_DECIMALS);-const THREE_ATOMICS = 10n ** BigInt(TOKEN_DECIMALS);-// ── policy knobs (env, with safe defaults) ──────────────────────────────────/** Execution gate. A scheduled run is a recorded no-op unless this is truthy. */@@ -44,28 +48,19 @@ export function isEnabled() {return ['1', 'true', 'yes', 'on'].includes(String(process.env.THREE_BUYBACK_ENABLED || '').toLowerCase());}-function positiveEnvUsd(key, fallback) {- const raw = process.env[key];- if (raw === undefined || String(raw).trim() === '') return fallback;- const n = Number(raw);- return Number.isFinite(n) && n > 0 ? n : fallback;-}-/** Max USD a single run may deploy — bounds a runaway/over-funded sweep. */export function maxUsdPerRun() {- return positiveEnvUsd('THREE_BUYBACK_MAX_USD', 250);+ return envUsd(process.env.THREE_BUYBACK_MAX_USD, 250);}/** Below this, a run is skipped so dust doesn't pay more in fees than it buys. */export function minUsdPerRun() {- return positiveEnvUsd('THREE_BUYBACK_MIN_USD', 10);+ return envUsd(process.env.THREE_BUYBACK_MIN_USD, 10);}/** Jupiter slippage tolerance in basis points (default 3%). */export function slippageBps() {- const raw = process.env.THREE_BUYBACK_SLIPPAGE_BPS;- const n = Number(raw);- return Number.isFinite(n) && n > 0 && n <= 5000 ? Math.round(n) : 300;+ return envSlippageBps(process.env.THREE_BUYBACK_SLIPPAGE_BPS, 300);}/** Load the buyback signer (base64 of 64 secret-key bytes). Null when unset. */@@ -85,8 +80,8 @@ export async function loadBuybackSigner() {// ── helpers ─────────────────────────────────────────────────────────────────-const usd = (atomics) => Number(BigInt(atomics)) / Number(USDC_ATOMICS);-const threeTokens = (atomics) => Number(BigInt(atomics)) / Number(THREE_ATOMICS);+const usd = (atomics) => usdcToUsd(atomics);+const threeTokens = (atomics) => atomicsToTokens(atomics, TOKEN_DECIMALS);/** SPL balance of `owner` for `mint`, in atomics. Missing ATA → 0n (never throws). */async function splBalanceAtomics(connection, ownerPk, mintPk) {@@ -152,20 +147,22 @@ async function jupiterSwapTx(quote, userPublicKey) {* @returns {Promise<object>} { ok, reason?, spendUsdcAtomics, walletUsdcAtomics, quote?, expectedThreeAtomics?, priceUsd? }*/export async function planBuyback(signerPubkey) {+ // Fail BEFORE spending if the treasury sink is unconfigured — otherwise a buy+ // could succeed with nowhere policy-correct to route the bought $THREE.+ if (!treasuryWalletOrNull()) {+ return { ok: false, reason: 'treasury_unavailable', walletUsdcAtomics: 0n, spendUsdcAtomics: 0n };+ }+const connection = getConnection({ network: 'mainnet' });const walletUsdc = await splBalanceAtomics(connection, solanaPubkey(signerPubkey), solanaPubkey(SOLANA_USDC_MINT));- const capAtomics = BigInt(Math.floor(maxUsdPerRun() * Number(USDC_ATOMICS)));- const minAtomics = BigInt(Math.floor(minUsdPerRun() * Number(USDC_ATOMICS)));- const spend = walletUsdc > capAtomics ? capAtomics : walletUsdc;-- if (spend < minAtomics) {- return {- ok: false,- reason: walletUsdc === 0n ? 'empty' : 'below_threshold',- walletUsdcAtomics: walletUsdc,- spendUsdcAtomics: 0n,- };+ const { spendAtomics: spend, reason } = computeSpend(walletUsdc, {+ maxUsd: maxUsdPerRun(),+ minUsd: minUsdPerRun(),+ });++ if (reason !== 'ok') {+ return { ok: false, reason, walletUsdcAtomics: walletUsdc, spendUsdcAtomics: 0n };}const quote = await jupiterQuote(spend);@@ -286,13 +283,26 @@ export async function sweepStrandedThree(signer) {// ── accounting / public stats ────────────────────────────────────────────────+// Resilient query: a public read path must degrade to a sane default whether the+// query rejects (table missing) OR sql throws synchronously (env unconfigured).+async function safeQuery(run, fallback) {+ try {+ return await run();+ } catch {+ return fallback;+ }+}+/** Lifetime platform USDC fee revenue (atomics, 6dp) — the "earned" figure. */export async function revenueFeeAtomicsToDate() {- const rows = await sql`- select coalesce(sum(fee_amount), 0)::bigint as total- from agent_revenue_events- where currency_mint = ${SOLANA_USDC_MINT} and chain = 'solana'- `.catch(() => [{ total: 0 }]);+ const rows = await safeQuery(+ () => sql`+ select coalesce(sum(fee_amount), 0)::bigint as total+ from agent_revenue_events+ where currency_mint = ${SOLANA_USDC_MINT} and chain = 'solana'+ `,+ [{ total: 0 }],+ );return BigInt(rows[0]?.total ?? 0);}@@ -302,21 +312,27 @@ export async function revenueFeeAtomicsToDate() {*/export async function buybackStats() {const [agg, lastRow, revenueAtomics] = await Promise.all([- sql`- select- coalesce(sum(usdc_spent_atomics), 0)::bigint as usdc_spent,- coalesce(sum(three_bought_atomics), 0)::bigint as three_bought,- count(*)::int as runs- from three_buyback_runs- where status = 'confirmed'- `.catch(() => [{ usdc_spent: 0, three_bought: 0, runs: 0 }]),- sql`- select status, usdc_spent_atomics, three_bought_atomics, price_usd, buy_signature, created_at- from three_buyback_runs- where status = 'confirmed'- order by created_at desc- limit 1- `.catch(() => []),+ safeQuery(+ () => sql`+ select+ coalesce(sum(usdc_spent_atomics), 0)::bigint as usdc_spent,+ coalesce(sum(three_bought_atomics), 0)::bigint as three_bought,+ count(*)::int as runs+ from three_buyback_runs+ where status = 'confirmed'+ `,+ [{ usdc_spent: 0, three_bought: 0, runs: 0 }],+ ),+ safeQuery(+ () => sql`+ select status, usdc_spent_atomics, three_bought_atomics, price_usd, buy_signature, created_at+ from three_buyback_runs+ where status = 'confirmed'+ order by created_at desc+ limit 1+ `,+ [],+ ),revenueFeeAtomicsToDate(),]);@@ -331,7 +347,7 @@ export async function buybackStats() {revenue_usd: revenueUsd,deployed_usd: deployedUsd,// Share of platform revenue already converted to onchain buy pressure.- deployed_pct: revenueUsd > 0 ? Math.min(100, (deployedUsd / revenueUsd) * 100) : 0,+ deployed_pct: deployedPct(deployedUsd, revenueUsd),three_bought: threeTokens(threeBought),runs: agg[0]?.runs ?? 0,last_run: lastdiff --git a/api/three-token/[action].js b/api/three-token/[action].jsindex 970c55cfa..f1c875d45 100644--- a/api/three-token/[action].js+++ b/api/three-token/[action].js@@ -21,6 +21,7 @@ import { cors, error, json, method, wrap } from '../_lib/http.js';import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';import { fetchTokenMarketData } from '../_lib/market/token-market.js';import { fetchHolderBalances } from '../_lib/coin/holders.js';+import { buybackStats } from '../_lib/token/buyback.js';// Truncate a base58 wallet for display: "FeMb…Jpump".function shortWallet(addr) {@@ -99,9 +100,12 @@ export default wrap(async (req, res) => {const action = parts[2];if (action === 'stats') {- const [market, platform] = await Promise.all([+ const [market, platform, buyback] = await Promise.all([fetchTokenMarketData(THREE_MINT).catch(() => null),fetchPlatformMetrics(),+ // Programmatic buyback summary (revenue → $THREE bought into treasury).+ // Resilient: returns zeros before the first run / migration.+ buybackStats().catch(() => null),]);return json(@@ -128,6 +132,16 @@ export default wrap(async (req, res) => {revenue_share_pool_pct: REVENUE_SHARE_POOL_PCT,agent_deploy_burn: AGENT_DEPLOY_BURN,},+ // Revenue converted to onchain buy pressure — programmatic, no burn.+ buyback: buyback ?? {+ enabled: false,+ revenue_usd: 0,+ deployed_usd: 0,+ deployed_pct: 0,+ three_bought: 0,+ runs: 0,+ last_run: null,+ },},// Edge-cache the public stats at the CDN so most page loads never reach// the lambda (or Birdeye). 20s freshness is invisible for a token price;diff --git a/chat/src/Message.svelte b/chat/src/Message.svelteindex a91f2486f..b4664937e 100644--- a/chat/src/Message.svelte+++ b/chat/src/Message.svelte@@ -290,7 +290,9 @@<divclass="{message.role === 'user'? 'bg-paper-deep text-ink rounded-2xl px-4 py-3 max-w-[78%] relative'- : 'relative flex w-full gap-x-3.5 items-end'}"+ : hasLogo && isLatestAssistant+ ? 'relative flex w-full gap-x-3.5 items-center'+ : 'relative flex w-full gap-x-3.5 items-end'}">{#if message.role !== 'user'}<div class="relative shrink-0 flex flex-col items-center">@@ -320,10 +322,13 @@}}}class="shrink-0 rounded-md md:rounded-[6px] {message.role === 'assistant' && hasLogo && isLatestAssistant- ? 'flex w-[140px] h-[280px]'+ ? 'flex w-[132px] h-[224px]': 'flex h-8 w-8 md:h-9 md:w-9'}">{#if message.role === 'assistant' && hasLogo && isLatestAssistant}+ <!-- The figure is framed with ~30% headroom; render the canvas taller than+ its window and pull it up so the empty headroom is cropped, keeping the+ figure large without the avatar floating in dead space. --><span bind:this={agentSlotEl} class="w-full h-full overflow-hidden inline-block shrink-0 rounded-[inherit] will-change-transform" style="opacity:0;"><!-- svelte-ignore custom-element-no-implicit-ns --><agent-3d@@ -334,12 +339,12 @@? { 'agent-id': message.agent.id }: { src: '/avatars/cz.glb' })}mode="inline"- width="140"+ width="132"height="280"background="transparent"kioskname-plate="off"- style="width:100%;height:100%;display:block;"+ style="width:132px;height:280px;display:block;margin-top:-46px;"></agent-3d></span>{:else}diff --git a/data/changelog.json b/data/changelog.jsonindex cf7e36dc4..c520d231a 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,34 @@{"$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-18",+ "title": "Your agent and its answer now sit together in chat",+ "summary": "When an agent replied with a 3D avatar — especially while it was thinking or forging several models at once — the avatar used to float off on its own with a big empty gap, while the reasoning note and the tool buttons drifted down beside its feet. The agent now stands next to its own response: the avatar is framed tighter so it fills its space instead of hovering in the void, and its thinking note and tool calls line up with it as one tidy block. It reads as a single reply whether you're in the normal view or have a tool's details open in the side panel.",+ "tags": [+ "improvement"+ ],+ "link": "/chat"+ },+ {+ "date": "2026-06-18",+ "title": "Tipping a dancer in the Club is now one tap",+ "summary": "In the Pole Club, paying a dancer used to pop an extra step that made you pick your wallet before anything happened — annoying when you just want to tip and watch her dance, and worse when tipping pole after pole. Now, when a single wallet is detected, hitting Tip goes straight to the signature: approve the $0.001 USDC and she takes the pole. The same shortcut applies to the cover charge at the door. If you have more than one wallet installed you still get to choose, and the free re-entry option for returning guests is untouched.",+ "tags": [+ "improvement"+ ],+ "link": "/club"+ },+ {+ "date": "2026-06-18",+ "title": "Platform revenue now buys back $THREE onchain — and you can watch it",+ "summary": "The $THREE page has a new Programmatic buybacks panel that turns the protocol's economy into something you can verify, not just read about. Platform revenue is converted into $THREE bought on the open market and routed straight into the treasury — onchain, on a schedule, with every buy recorded against its Solscan receipt. This creates steady buy pressure for holders without ever burning supply. The panel shows how much revenue has been earned and what share of it has already been deployed into buybacks, so the link between the platform earning money and that money supporting $THREE is fully transparent.",+ "tags": [+ "feature",+ "infra"+ ],+ "link": "/three-token"+ },{"date": "2026-06-18","title": "Embedded 3D agents animate on any site, not just three.ws",diff --git a/public/changelog.json b/public/changelog.jsonindex 775386e2a..a61629f6c 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T04:45:54.243Z",+ "generated_at": "2026-06-18T05:03:49.103Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -88,6 +88,17 @@"feature"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Platform revenue now buys back $THREE onchain — and you can watch it",+ "summary": "The $THREE page has a new Programmatic buybacks panel that turns the protocol's economy into something you can verify, not just read about. Platform revenue is converted into $THREE bought on the open market and routed straight into the treasury — onchain, on a schedule, with every buy recorded against its Solscan receipt. This creates steady buy pressure for holders without ever burning supply. The panel shows how much revenue has been earned and what share of it has already been deployed into buybacks, so the link between the platform earning money and that money supporting $THREE is fully transparent.",+ "link": "/three-token",+ "tags": [+ "feature",+ "infra"+ ]+ },{"date": "2026-06-18","type": "update",@@ -178,6 +189,16 @@"improvement"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Tipping a dancer in the Club is now one tap",+ "summary": "In the Pole Club, paying a dancer used to pop an extra step that made you pick your wallet before anything happened — annoying when you just want to tip and watch her dance, and worse when tipping pole after pole. Now, when a single wallet is detected, hitting Tip goes straight to the signature: approve the $0.001 USDC and she takes the pole. The same shortcut applies to the cover charge at the door. If you have more than one wallet installed you still get to choose, and the free re-entry option for returning guests is untouched.",+ "link": "/club",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-18","type": "update",@@ -209,6 +230,16 @@"improvement"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Your agent and its answer now sit together in chat",+ "summary": "When an agent replied with a 3D avatar — especially while it was thinking or forging several models at once — the avatar used to float off on its own with a big empty gap, while the reasoning note and the tool buttons drifted down beside its feet. The agent now stands next to its own response: the avatar is framed tighter so it fills its space instead of hovering in the void, and its thinking note and tool calls line up with it as one tidy block. It reads as a single reply whether you're in the normal view or have a tool's details open in the side panel.",+ "link": "/chat",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-17","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 5f27fd12c..fa6ac6311 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -70,6 +70,14 @@<category>feature</category><description>Don't hold $THREE yet but want a High-quality model? You can now pay in $THREE for a single High generation instead. Pick High in Forge, choose "Pay" on the holder panel, and a clean payment flow prices it in $THREE, takes one wallet approval, verifies it on-chain, and runs your generation automatically. The platform now genuinely accepts $THREE for compute. One payment buys exactly one High generation, and if a generation fails before it runs your payment stays usable — you're never charged for a model you didn't get. Draft and Standard remain free, and holders still generate High straight away.</description></item>+ <item>+ <title>Platform revenue now buys back $THREE onchain — and you can watch it</title>+ <link>https://three.ws/three-token</link>+ <guid isPermaLink="false">2026-06-18:Platform revenue now buys back $THREE onchain — and you can watch it</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The $THREE page has a new Programmatic buybacks panel that turns the protocol's economy into something you can verify, not just read about. Platform revenue is converted into $THREE bought on the open market and routed straight into the treasury — onchain, on a schedule, with every buy recorded against its Solscan receipt. This creates steady buy pressure for holders without ever burning supply. The panel shows how much revenue has been earned and what share of it has already been deployed into buybacks, so the link between the platform earning money and that money supporting $THREE is fully transparent.</description>+ </item><item><title>Play is movable on phones again — and avatars load instead of a placeholder</title><link>https://three.ws/changelog</link>@@ -142,6 +150,14 @@<category>improvement</category><description>Tapping Tip in the Pole Club used to open a three-step “Before you go on-chain” explainer first, and dismissing it cancelled the tip entirely — so first-time visitors couldn't pay without sitting through the wizard. That gate is gone. Tip now opens the wallet-and-amount checkout directly, where you pick Phantom or a browser wallet, see the exact USDC amount, and approve with one signature. The checkout already shows everything the explainer did, so there's no reason to stack a lecture in front of a fraction-of-a-cent tip.</description></item>+ <item>+ <title>Tipping a dancer in the Club is now one tap</title>+ <link>https://three.ws/club</link>+ <guid isPermaLink="false">2026-06-18:Tipping a dancer in the Club is now one tap</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>In the Pole Club, paying a dancer used to pop an extra step that made you pick your wallet before anything happened — annoying when you just want to tip and watch her dance, and worse when tipping pole after pole. Now, when a single wallet is detected, hitting Tip goes straight to the signature: approve the $0.001 USDC and she takes the pole. The same shortcut applies to the cover charge at the door. If you have more than one wallet installed you still get to choose, and the free re-entry option for returning guests is untouched.</description>+ </item><item><title>Token swaps now confirm success or failure clearly</title><link>https://three.ws/three-token</link>@@ -166,6 +182,14 @@<category>feature</category><description>Holding $THREE is now visible everywhere you are. A holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) on every page and links to the full tier breakdown. On Forge, choosing the High quality tier now shows a clear, designed panel instead of a silent block: holders see an "Unlocked" badge and generate straight away, while everyone else gets a "Get $THREE" path, the exact reason (sign in, link a wallet, or hold more), and a one-tap switch back to free Draft or Standard — no dead ends and no raw errors.</description></item>+ <item>+ <title>Your agent and its answer now sit together in chat</title>+ <link>https://three.ws/chat</link>+ <guid isPermaLink="false">2026-06-18:Your agent and its answer now sit together in chat</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>When an agent replied with a 3D avatar — especially while it was thinking or forging several models at once — the avatar used to float off on its own with a big empty gap, while the reasoning note and the tool buttons drifted down beside its feet. The agent now stands next to its own response: the avatar is framed tighter so it fills its space instead of hovering in the void, and its thinking note and tool calls line up with it as one tidy block. It reads as a single reply whether you're in the normal view or have a tool's details open in the side panel.</description>+ </item><item><title>Animation Gallery</title><link>https://three.ws/animations</link>diff --git a/public/features.json b/public/features.jsonindex fb49e53e2..355ba0061 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T04:45:54.225Z",+ "generated_at": "2026-06-18T05:03:49.091Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/x402.js b/public/x402.jsindex c6b694af5..f136ed60b 100644--- a/public/x402.js+++ b/public/x402.js@@ -659,6 +659,10 @@ class CheckoutModal {this.accept = null;this.challenge = null;this.disposed = false;+ // One-shot guard for opts.autoConnect: we only auto-open the wallet on the+ // first connect render, so an error that drops the user back to this step+ // shows the manual picker instead of re-launching the wallet in a loop.+ this.autoConnectTried = false;}mount() {@@ -762,6 +766,20 @@ class CheckoutModal {}}+ // autoConnect (opt-in via opts.autoConnect): when the caller knows the+ // user is wallet-ready and shouldn't have to pick, skip the picker and go+ // straight to the signature — but only when exactly one supported wallet+ // is actually detected. Zero wallets (must install) or two (must choose)+ // still fall through to the picker, as does the SIWX "you haven't paid"+ // fallback, which needs to explain itself. One-shot via autoConnectTried.+ if (this.opts.autoConnect && !this.autoConnectTried && !this.siwxFallbackNotice) {+ this.autoConnectTried = true;+ const solanaViable = !!(solanaAccept && phantomDetected);+ const evmViable = !!(evmAccept && evmDetected);+ if (solanaViable && !evmViable) { this.runSolana(solanaAccept); return; }+ if (evmViable && !solanaViable) { this.runEvm(evmAccept); return; }+ }+const buttons = [];if (solanaAccept) {buttons.push(`diff --git a/src/club-gate.js b/src/club-gate.jsindex ec264ef11..4a032d626 100644--- a/src/club-gate.js+++ b/src/club-gate.js@@ -74,6 +74,9 @@ async function payCover(root, { payBtn, msgEl, tierEl }) {method: 'GET',merchant: 'three.ws Pole Club',action: 'Cover charge — enter the club',+ // Skip the checkout's wallet-picker when one wallet is detected — the+ // SIWX free-re-entry choice and the install/pick cases still surface.+ autoConnect: true,});const pass = out?.result;if (!pass?.ok) throw new Error(pass?.error || 'cover did not settle');diff --git a/src/club.js b/src/club.jsindex e87d40373..7b85d8fad 100644--- a/src/club.js+++ b/src/club.js@@ -1346,7 +1346,10 @@ async function tipDancer({ dancer, dance, button }) {// entire money flow — wallet connect (Phantom/EVM), USDC, and the amount the// user confirms before signing. A $0.001 tip should never sit behind a// three-step explainer that re-teaches what the checkout already shows, so- // there's no pre-gate here: click Tip → the wallet/amount modal opens.+ // there's no pre-gate here. With autoConnect the checkout also skips its own+ // wallet-picker step when a single wallet is detected: click Tip → the wallet+ // signs straight away. Rapid tipping shouldn't mean re-picking a wallet each+ // time.// First click on a Tip button is the user gesture browsers require to// unlock AudioContext. Do this BEFORE opening the wallet modal so the@@ -1371,6 +1374,7 @@ async function tipDancer({ dancer, dance, button }) {method: 'GET',merchant: 'three.ws Pole Club',action: `Tip Dancer ${dancer} — ${dance}`,+ autoConnect: true,});const ticket = out?.result;if (!ticket?.ok) {diff --git a/src/three-token-page.js b/src/three-token-page.jsindex c3e063a93..55c15205e 100644--- a/src/three-token-page.js+++ b/src/three-token-page.js@@ -95,7 +95,20 @@ function injectStyles() {@keyframes tkSh { from { background-position:200% 0; } to { background-position:-200% 0; } }.tk-foot { display:flex; gap:18px; flex-wrap:wrap; margin-top:26px; font-size:13px; }.tk-foot a { color:#9a9aa3; text-decoration:none; } .tk-foot a:hover { color:#fff; }- @media (prefers-reduced-motion: reduce){ .tk-trade.in { animation:none; } .tk-skel { animation:none; } }+ .tk-bb { margin-top:18px; }+ .tk-bb-lead { color:#9a9aa3; font-size:13px; margin:0 0 14px; line-height:1.5; }+ .tk-bb-empty { color:#b8b8c0; font-size:14px; line-height:1.6; }+ .tk-bb-empty strong { color:#f5f5f7; }+ .tk-bb-empty span { display:block; color:#7d7d86; font-size:13px; margin-top:6px; }+ .tk-bb-head { display:grid; grid-template-columns:repeat(3,1fr); gap:12px; margin-bottom:14px; }+ .tk-bb-k { font-size:11px; text-transform:uppercase; letter-spacing:0.06em; color:#7d7d86; margin-bottom:4px; }+ .tk-bb-v { font-size:20px; font-weight:700; font-family:ui-monospace,Menlo,monospace; }+ .tk-bb-bar { height:8px; border-radius:6px; background:#1d1d24; overflow:hidden; }+ .tk-bb-bar span { display:block; height:100%; background:linear-gradient(90deg,#4ade80,#22d3ee); border-radius:6px; transition:width .6s ease; }+ .tk-bb-foot { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; margin-top:10px; font-size:12.5px; color:#7d7d86; }+ .tk-bb-foot a { color:#7CC4FF; text-decoration:none; } .tk-bb-foot a:hover { text-decoration:underline; }+ @media (max-width:560px){ .tk-bb-head { grid-template-columns:1fr; gap:8px; } }+ @media (prefers-reduced-motion: reduce){ .tk-trade.in { animation:none; } .tk-skel { animation:none; } .tk-bb-bar span { transition:none; } }`;const el = document.createElement('style');el.textContent = css;@@ -120,6 +133,38 @@ function renderHeaderStats(token) {}).join('');}+// ── programmatic buybacks (revenue → $THREE → treasury) ──────────────────────+function renderBuyback(bb) {+ if (!bb) return `<div class="tk-empty" style="padding:24px 0">Couldn’t load buyback data.</div>`;+ const revenue = fmtUsd(bb.revenue_usd);+ const lead = `Platform revenue is programmatically converted into $THREE buy pressure and routed to the treasury — onchain, on a schedule. No burn: supply is never destroyed.`;+ if (!bb.runs) {+ return `+ <p class="tk-bb-lead">${lead}</p>+ <div class="tk-bb-empty">+ <strong>${revenue}</strong> in platform revenue earned so far.+ <span>Buybacks begin once the treasury deploys revenue onchain — every run will appear here with its Solscan receipt.</span>+ </div>`;+ }+ const pct = Math.max(0, Math.min(100, Number(bb.deployed_pct) || 0));+ const last = bb.last_run;+ const lastDate = last?.at ? new Date(last.at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : null;+ return `+ <p class="tk-bb-lead">${lead}</p>+ <div class="tk-bb-head">+ <div><div class="tk-bb-k">Revenue earned</div><div class="tk-bb-v">${revenue}</div></div>+ <div><div class="tk-bb-k">Deployed to buybacks</div><div class="tk-bb-v">${fmtUsd(bb.deployed_usd)}</div></div>+ <div><div class="tk-bb-k">$THREE bought</div><div class="tk-bb-v">${fmtNum(bb.three_bought)}</div></div>+ </div>+ <div class="tk-bb-bar" role="progressbar" aria-valuenow="${pct.toFixed(0)}" aria-valuemin="0" aria-valuemax="100" aria-label="Share of revenue deployed to buybacks">+ <span style="width:${pct}%"></span>+ </div>+ <div class="tk-bb-foot">+ <span>${pct.toFixed(1)}% of revenue → onchain buy pressure · ${fmtNum(bb.runs)} run${bb.runs === 1 ? '' : 's'}</span>+ ${last?.signature ? `<a href="https://solscan.io/tx/${esc(last.signature)}" target="_blank" rel="noopener">Last buyback${lastDate ? ` · ${lastDate}` : ''} ↗</a>` : ''}+ </div>`;+}+// ── live trade tape via SSE (reconnecting) ───────────────────────────────────function startTradeTape(tapeEl, statusEl) {let es = null;@@ -223,6 +268,10 @@ function boot() {</div></div></div>+ <div class="tk-card tk-bb">+ <h2>Programmatic buybacks</h2>+ <div data-buyback><div class="tk-skel" style="height:96px"></div></div>+ </div><div class="tk-foot"><a href="/dashboard/holders">🏆 Holder leaderboard</a><a href="/three-live">⚡ Protocol Pulse (live 3D)</a>@@ -260,6 +309,13 @@ function boot() {// Live trade tape.startTradeTape(wrap.querySelector('[data-tape]'), wrap.querySelector('[data-tape-status]'));++ // Programmatic buyback panel — real figures from the protocol stats endpoint.+ const bbEl = wrap.querySelector('[data-buyback]');+ fetch('/api/three-token/stats', { headers: { accept: 'application/json' } })+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`stats ${r.status}`))))+ .then((d) => { bbEl.innerHTML = renderBuyback(d.buyback); })+ .catch(() => { bbEl.innerHTML = renderBuyback(null); });}if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);diff --git a/tests/api/three-buyback-math.test.js b/tests/api/three-buyback-math.test.jsnew file mode 100644index 000000000..9acd8f73e--- /dev/null+++ b/tests/api/three-buyback-math.test.js@@ -0,0 +1,107 @@+// Unit tests for the programmatic $THREE buyback sizing + policy math.+//+// Pure logic — no DB, no RPC, no web3. Verifies that a run spends up to the+// per-run cap bounded by the live wallet balance, skips correctly below the+// minimum, and that the public ratio / unit conversions are exact.++import { describe, it, expect } from 'vitest';++import {+ USDC_ATOMICS,+ computeSpend,+ deployedPct,+ envSlippageBps,+ envUsd,+ usdToUsdcAtomics,+ usdcAtomicsToUsd,+ atomicsToTokens,+} from '../../api/_lib/token/buyback-math.js';++const usdc = (n) => usdToUsdcAtomics(n); // whole USD → atomics++describe('buyback computeSpend', () => {+ const caps = { maxUsd: 250, minUsd: 10 };++ it('skips an empty wallet with reason "empty"', () => {+ expect(computeSpend(0n, caps)).toEqual({ spendAtomics: 0n, reason: 'empty' });+ });++ it('skips a wallet below the minimum with reason "below_threshold"', () => {+ // $9.99 < $10 minimum+ expect(computeSpend(usdc(9.99), caps)).toEqual({ spendAtomics: 0n, reason: 'below_threshold' });+ });++ it('spends the full balance when between min and cap', () => {+ const r = computeSpend(usdc(120), caps);+ expect(r.reason).toBe('ok');+ expect(r.spendAtomics).toBe(usdc(120));+ });++ it('caps the spend at the per-run maximum, leaving the rest in the wallet', () => {+ const r = computeSpend(usdc(1000), caps);+ expect(r.reason).toBe('ok');+ expect(r.spendAtomics).toBe(usdc(250)); // capped, not 1000+ });++ it('spends exactly the minimum at the boundary', () => {+ const r = computeSpend(usdc(10), caps);+ expect(r.reason).toBe('ok');+ expect(r.spendAtomics).toBe(usdc(10));+ });++ it('accepts string/number atomics inputs (DB bigints arrive as strings)', () => {+ expect(computeSpend('50000000', caps)).toEqual({ spendAtomics: 50_000_000n, reason: 'ok' }); // $50+ });+});++describe('buyback deployedPct', () => {+ it('is 0 when no revenue has been earned', () => {+ expect(deployedPct(0, 0)).toBe(0);+ expect(deployedPct(5, 0)).toBe(0);+ });++ it('computes the deployed share of revenue', () => {+ expect(deployedPct(25, 100)).toBe(25);+ });++ it('clamps to 100 even if more was deployed than the measured revenue', () => {+ // deployed can exceed the fee ledger when the wallet is topped up directly.+ expect(deployedPct(150, 100)).toBe(100);+ });+});++describe('buyback unit conversions', () => {+ it('round-trips USD ↔ USDC atomics', () => {+ expect(usdToUsdcAtomics(1)).toBe(USDC_ATOMICS);+ expect(usdcAtomicsToUsd(USDC_ATOMICS)).toBe(1);+ expect(usdcAtomicsToUsd(usdToUsdcAtomics(42.5))).toBe(42.5);+ });++ it('converts $THREE atomics to whole tokens at 6 decimals', () => {+ expect(atomicsToTokens(1_000_000n, 6)).toBe(1);+ expect(atomicsToTokens(2_500_000n, 6)).toBe(2.5);+ });+});++describe('buyback env parsing', () => {+ it('falls back when unset, empty, or non-positive', () => {+ expect(envUsd(undefined, 250)).toBe(250);+ expect(envUsd('', 250)).toBe(250);+ expect(envUsd('0', 250)).toBe(250);+ expect(envUsd('-5', 250)).toBe(250);+ expect(envUsd('abc', 250)).toBe(250);+ });++ it('parses a valid positive USD override', () => {+ expect(envUsd('500', 250)).toBe(500);+ expect(envUsd('12.5', 10)).toBe(12.5);+ });++ it('clamps slippage to (0, 5000] bps and rounds', () => {+ expect(envSlippageBps(undefined)).toBe(300);+ expect(envSlippageBps('0')).toBe(300);+ expect(envSlippageBps('6000')).toBe(300); // over ceiling → fallback+ expect(envSlippageBps('150')).toBe(150);+ expect(envSlippageBps('150.7')).toBe(151);+ });+});diff --git a/vercel.json b/vercel.jsonindex 561fd7754..d48130ecc 100644--- a/vercel.json+++ b/vercel.json@@ -3609,6 +3609,10 @@"path": "/api/cron/run-distribute-payments","schedule": "30 * * * *"},+ {+ "path": "/api/cron/run-three-buyback",+ "schedule": "0 6 * * *"+ },{"path": "/api/cron/audit-log-cleanup","schedule": "0 4 * * *"