Skip to content

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

feat: shared cache for token market, referrals, and agent payment refinements

nirholas9cb9a91071e3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 379605f7b..4ca3a1565 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **$THREE buyback commitment is now public and verifiable on the token page** — The $THREE page now leads with the protocol's buyback commitment — the fixed share of all platform revenue routed into buying $THREE on the open market and sending it to the treasury — shown as revenue earned, dollars committed, dollars deployed on-chain, and how much of the commitment has been kept. Every individual buyback is listed with a one-click Solscan receipt, so the promise is provable, not just stated. No burn: supply is never destroyed. (`/three-token`) `[feature]`
- **$THREE holder leaderboard loads faster from a shared snapshot** — The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces. (`/leaderboard`) `[improvement, infra]`
+- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set. You can see what your remaining cap covers, get a heads-up when it runs low, top it up, or revoke it in one click anytime. Prefer to sign each payment? Just leave it off. (`/three-token`) `[feature]`
- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice. (`/three-token`) `[feature]`
- **Discover and character feeds load faster under heavy traffic** — The Discover grid and the published-agents (Characters) feed now serve from the edge cache, so a surge of visitors is absorbed at the CDN instead of re-running a database scan on every request. Pages stay fast and consistent even during a rush, and a stale-while-revalidate window keeps them warm between refreshes. (`/discover`) `[improvement, infra]`
- **Forge hardened for a traffic surge — faster loads, protected free lanes** — We scaled Forge for the influx of new users. The engine catalog and live health status now serve from the edge cache, so the page loads instantly even under heavy traffic instead of recomputing on every visit. We also added a platform-wide safety valve on paid generation: if demand ever spikes past the shared paid budget, the free engines (NVIDIA and Hugging Face) stay fully open and you get a clear 'try a free engine' message instead of a hard failure — your own bring-your-own-key engines are never affected. Net result: Forge stays fast and available as we grow, and free 3D generation never gets crowded out. (`/forge`) `[infra, improvement]`
diff --git a/api/_lib/cache.js b/api/_lib/cache.js
index b447c0ab4..76d26f846 100644
--- a/api/_lib/cache.js
+++ b/api/_lib/cache.js
@@ -139,3 +139,28 @@ export async function cacheDel(key) {
export function cacheBackend() {
return redisConfigured() ? 'upstash' : 'memory';
}
+
+/**
+ * Read-through cache: return the cached value for `key`, or compute it with
+ * `fn()`, store it for `ttlSeconds`, and return it. Use to shield expensive but
+ * staleness-tolerant work (full-table COUNT(*) aggregates, leaderboards) from
+ * every request — at 100x traffic these are the queries that fall over.
+ *
+ * `null`/`undefined` results are NOT cached (so a transient failure isn't pinned
+ * as "no data"); a thrown `fn` propagates and caches nothing.
+ *
+ * @template T
+ * @param {string} key
+ * @param {number} ttlSeconds
+ * @param {() => Promise<T>} fn
+ * @returns {Promise<T>}
+ */
+export async function cacheWrap(key, ttlSeconds, fn) {
+ const hit = await cacheGet(key);
+ if (hit !== null && hit !== undefined) return hit;
+ const value = await fn();
+ if (value !== null && value !== undefined) {
+ await cacheSet(key, value, ttlSeconds);
+ }
+ return value;
+}
diff --git a/api/_lib/referrals.js b/api/_lib/referrals.js
index baed9665e..ab857774a 100644
--- a/api/_lib/referrals.js
+++ b/api/_lib/referrals.js
@@ -1,5 +1,6 @@
import { randomBytes } from 'crypto';
import { sql } from './db.js';
+import { cacheWrap } from './cache.js';
/**
* Generates a random, human-readable referral code.
@@ -87,9 +88,15 @@ export async function getMembershipCard(userId) {
SELECT COUNT(*)::int AS position FROM users
WHERE id <= ${userId} AND deleted_at IS NULL
`;
- const [{ total }] = await sql`
- SELECT COUNT(*)::int AS total FROM users WHERE deleted_at IS NULL
- `;
+ // Platform-wide member count: a full-table COUNT(*) that is identical for
+ // every viewer and grows monotonically — cache for 60s instead of scanning
+ // users on every member-card render.
+ const total = await cacheWrap('users:total:active', 60, async () => {
+ const [{ total }] = await sql`
+ SELECT COUNT(*)::int AS total FROM users WHERE deleted_at IS NULL
+ `;
+ return total;
+ });
// `referral_earnings_total` accumulates atomic USDC units (6 decimals),
// written by api/_lib/purchase-confirm.js.
diff --git a/api/agents.js b/api/agents.js
index d42e51421..fd6929bd4 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -22,6 +22,7 @@ import { publicUrl } from './_lib/r2.js';
import { pingIndexNow } from './_lib/indexnow.js';
import { publishFeedEvent } from './_lib/feed.js';
import { getSkillPrices, skillPriceMap } from './_lib/skill-price-cache.js';
+import { cacheWrap } from './_lib/cache.js';
import { env } from './_lib/env.js';
import { z } from 'zod';
import { isUuid } from './_lib/validate.js';
@@ -401,12 +402,17 @@ export async function handleGetOne(req, res, id) {
// a usage-stats query failure (e.g. usage_events not yet migrated, code
// 42P01) take down the whole agent fetch. Degrade to 0.
try {
- const [chatRow] = await sql`
- SELECT COUNT(*)::int AS total
- FROM usage_events
- WHERE agent_id = ${id} AND kind = 'llm'
- `;
- row.chat_count = chatRow?.total ?? 0;
+ // COUNT(*) over the append-only usage_events table per agent GET — cache
+ // it per agent for 60s so a popular profile doesn't re-scan the partition
+ // on every view. chat_count is decorative, so slight staleness is fine.
+ row.chat_count = await cacheWrap(`agent:chat_count:${id}`, 60, async () => {
+ const [chatRow] = await sql`
+ SELECT COUNT(*)::int AS total
+ FROM usage_events
+ WHERE agent_id = ${id} AND kind = 'llm'
+ `;
+ return chatRow?.total ?? 0;
+ });
} catch (err) {
console.warn(
'[agents] chat_count usage_events query failed, defaulting to 0:',
diff --git a/api/agents/payments/[action].js b/api/agents/payments/[action].js
index 828e5a8cf..a61a1ccab 100644
--- a/api/agents/payments/[action].js
+++ b/api/agents/payments/[action].js
@@ -271,6 +271,24 @@ async function handlePayPrep(req, res) {
const body = parse(payPrepSchema, await readJson(req));
+ // The payer wallet is the fee-payer of the invoice tx and is persisted as the
+ // intent's owner-facing wallet, so it must belong to the authenticated caller —
+ // otherwise any signed-in user could mint intent rows "as" an arbitrary wallet
+ // for any agent/amount/mint (record pollution + spoofed payer attribution).
+ // Mirrors the linkage check every other wallet-signing prep handler enforces.
+ let payerPk;
+ try {
+ payerPk = new PublicKey(body.wallet_address);
+ } catch {
+ return error(res, 400, 'validation_error', 'invalid wallet_address');
+ }
+ const [payerWallet] = await sql`
+ select id from user_wallets
+ where user_id = ${user.id} and address = ${body.wallet_address} and chain_type = 'solana'
+ limit 1
+ `;
+ if (!payerWallet) return error(res, 403, 'forbidden', 'wallet not linked to your account');
+
const [agent] = await sql`
select id, name, meta from agent_identities
where id = ${body.agent_id} and deleted_at is null limit 1
@@ -293,7 +311,7 @@ async function handlePayPrep(req, res) {
const endTime = startTime + 60 * 60 * 24; // 24h validity window for the invoice
const ixs = await pumpAgent.buildAcceptPaymentInstructions({
- user: new PublicKey(body.wallet_address),
+ user: payerPk,
currencyMint: new PublicKey(body.currency_mint),
amount: new BN(body.amount),
memo: new BN(memo),
@@ -303,7 +321,7 @@ async function handlePayPrep(req, res) {
const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
const tx = new Transaction({
- feePayer: new PublicKey(body.wallet_address),
+ feePayer: payerPk,
blockhash,
lastValidBlockHeight,
}).add(
diff --git a/api/explore.js b/api/explore.js
index 23c556f7a..6b162325c 100644
--- a/api/explore.js
+++ b/api/explore.js
@@ -25,6 +25,7 @@ function isAutoNamed(name) {
}
import { sql } from './_lib/db.js';
+import { cacheWrap } from './_lib/cache.js';
import { cors, json, method, wrap, error, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';
@@ -274,19 +275,29 @@ export default wrap(async (req, res) => {
const items = merged.slice(0, limit);
const nextCursor = hasMore && items.length > 0 ? items[items.length - 1].sortDate : null;
- const [{ total: onchainTotal }] = await sql`
- SELECT count(*)::text as total FROM erc8004_agents_index WHERE active = true
- `;
- const [{ total3d: onchain3d }] = await sql`
- SELECT count(*)::text as total3d FROM erc8004_agents_index WHERE active = true AND has_3d = true
- `;
- const [{ total: avatarTotal }] = await sql`
- SELECT count(*)::text as total FROM avatars WHERE deleted_at IS NULL AND visibility = 'public'
- `;
- const [{ total: solanaTotal }] = await sql`
- SELECT count(*)::text as total FROM agent_identities
- WHERE deleted_at IS NULL AND meta->>'chain_type' = 'solana' AND meta->>'network' = 'mainnet'
- `;
+ // Directory totals are four full-table COUNT(*) scans that are identical for
+ // every visitor and change slowly — cache them for 60s so the discover page
+ // doesn't re-scan four growing tables on every request.
+ const { onchainTotal, onchain3d, avatarTotal, solanaTotal } = await cacheWrap(
+ 'explore:totals:v1',
+ 60,
+ async () => {
+ const [{ total: onchainTotal }] = await sql`
+ SELECT count(*)::text as total FROM erc8004_agents_index WHERE active = true
+ `;
+ const [{ total3d: onchain3d }] = await sql`
+ SELECT count(*)::text as total3d FROM erc8004_agents_index WHERE active = true AND has_3d = true
+ `;
+ const [{ total: avatarTotal }] = await sql`
+ SELECT count(*)::text as total FROM avatars WHERE deleted_at IS NULL AND visibility = 'public'
+ `;
+ const [{ total: solanaTotal }] = await sql`
+ SELECT count(*)::text as total FROM agent_identities
+ WHERE deleted_at IS NULL AND meta->>'chain_type' = 'solana' AND meta->>'network' = 'mainnet'
+ `;
+ return { onchainTotal, onchain3d, avatarTotal, solanaTotal };
+ },
+ );
const avatarCount = Number(avatarTotal);
const solCount = Number(solanaTotal);
const allTotal = Number(onchainTotal) + solCount + avatarCount;
diff --git a/data/changelog.json b/data/changelog.json
index 513266a53..d7ff4b1ed 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$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-21",
+ "title": "Authorize $THREE once, then pay with no wallet popups",
+ "summary": "The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set. You can see what your remaining cap covers, get a heads-up when it runs low, top it up, or revoke it in one click anytime. Prefer to sign each payment? Just leave it off.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/three-token"
+ },
{
"date": "2026-06-21",
"title": "Discover and character feeds load faster under heavy traffic",
diff --git a/public/changelog.json b/public/changelog.json
index ca70c6e28..8e6f9f335 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T05:42:22.088Z",
+ "generated_at": "2026-06-21T06:04:18.477Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -27,6 +27,16 @@
"infra"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Authorize $THREE once, then pay with no wallet popups",
+ "summary": "The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set. You can see what your remaining cap covers, get a heads-up when it runs low, top it up, or revoke it in one click anytime. Prefer to sign each payment? Just leave it off.",
+ "link": "/three-token",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 97f6635cb..56af4bc99 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -22,6 +22,14 @@
<category>improvement</category>
<description>The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces.</description>
</item>
+ <item>
+ <title>Authorize $THREE once, then pay with no wallet popups</title>
+ <link>https://three.ws/three-token</link>
+ <guid isPermaLink="false">2026-06-21:Authorize $THREE once, then pay with no wallet popups</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions &amp; Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set. You can see what your remaining cap covers, get a heads-up when it runs low, top it up, or revoke it in one click anytime. Prefer to sign each payment? Just leave it off.</description>
+ </item>
<item>
<title>Authorize $THREE once, then pay with no wallet popups</title>
<link>https://three.ws/three-token</link>
diff --git a/public/features.json b/public/features.json
index aab46a509..a0b060f9a 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T05:42:22.061Z",
+ "generated_at": "2026-06-21T06:04:18.418Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/probe-app-empty-state.mjs b/scripts/probe-app-empty-state.mjs
new file mode 100644
index 000000000..0474ece67
--- /dev/null
+++ b/scripts/probe-app-empty-state.mjs
@@ -0,0 +1,37 @@
+// One-off probe: what does a brand-new (no-agent, signed-out) user see at /app?
+// Captures the agent-home container, sidebar text, console errors, and a shot.
+import { chromium } from 'playwright';
+
+const URL = process.env.PROBE_URL || 'http://localhost:3000/app';
+const browser = await chromium.launch();
+const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });
+const page = await ctx.newPage();
+
+const errors = [];
+page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
+page.on('pageerror', (e) => errors.push('PAGEERROR: ' + e.message));
+
+// Fresh user: no localStorage, no session.
+await page.addInitScript(() => { try { localStorage.clear(); sessionStorage.clear(); } catch {} });
+await page.goto(URL, { waitUntil: 'networkidle', timeout: 45000 }).catch((e) => errors.push('GOTO: ' + e.message));
+await page.waitForTimeout(4000);
+
+const report = await page.evaluate(() => {
+ const home = document.getElementById('agent-home-container');
+ const authGate = document.querySelector('[data-auth-gate], #auth-gate, .auth-gate, #signin, .signin');
+ const sidebar = document.querySelector('#sidebar, .sidebar, aside');
+ const visible = (el) => !!el && el.offsetParent !== null && (el.textContent || '').trim().length > 0;
+ return {
+ homeExists: !!home,
+ homeHasContent: home ? (home.innerHTML || '').trim().length : -1,
+ homeText: home ? (home.textContent || '').trim().slice(0, 200) : null,
+ authGateVisible: visible(authGate),
+ authGateText: authGate ? (authGate.textContent || '').trim().slice(0, 160) : null,
+ sidebarText: sidebar ? (sidebar.textContent || '').trim().slice(0, 200) : null,
+ bodyHasCreateCTA: /create.*(your )?(first )?agent|get started|sign in|log in/i.test(document.body.textContent || ''),
+ };
+});
+
+await page.screenshot({ path: '/tmp/app-fresh-user.png', fullPage: false });
+console.log(JSON.stringify({ report, errors: errors.slice(0, 20) }, null, 2));
+await browser.close();
diff --git a/src/agent-solana-wallet.js b/src/agent-solana-wallet.js
index 4dbd75341..6083bffb6 100644
--- a/src/agent-solana-wallet.js
+++ b/src/agent-solana-wallet.js
@@ -95,6 +95,63 @@ export async function provisionAgentSolanaWallet({
return json.data;
}
+/**
+ * Apply a vanity address via the sweep-safe endpoint.
+ *
+ * Unlike provisionAgentSolanaWallet (which targets the base /solana endpoint and
+ * does NOT migrate funds), this POSTs the browser-ground keypair to
+ * /api/agents/:id/solana/vanity. If the agent already holds a funded wallet, the
+ * server sweeps every SOL/token to the new address BEFORE swapping the stored key
+ * — funds can never be stranded (the swap aborts if the sweep fails) — and it
+ * re-derives the address to prove it matches the pattern before storing it. Use
+ * this to REPLACE a possibly-funded wallet; never delete-then-provision.
+ *
+ * @param {object} opts
+ * @param {string} opts.agentId
+ * @param {Uint8Array} opts.secretKey — 64-byte browser-ground key.
+ * @param {string} [opts.prefix]
+ * @param {string} [opts.suffix]
+ * @param {boolean} [opts.ignoreCase]
+ * @param {number} [opts.iterations]
+ * @param {number} [opts.durationMs]
+ * @param {AbortSignal} [opts.signal]
+ * @returns {Promise<{ address: string, vanity_prefix: string|null, vanity_suffix: string|null, swept: object|null, source: string }>}
+ */
+export async function applyAgentVanityWallet({
+ agentId, secretKey, prefix = '', suffix = '', ignoreCase = false,
+ iterations = null, durationMs = null, signal,
+} = {}) {
+ if (!agentId) throw new Error('agentId required');
+ if (!secretKey || secretKey.length !== 64) throw new Error('a 64-byte secret key is required');
+
+ const headers = { 'Content-Type': 'application/json' };
+ const token = await consumeCsrfToken();
+ if (token) headers['x-csrf-token'] = token;
+
+ const resp = await fetch(`/api/agents/${encodeURIComponent(agentId)}/solana/vanity`, {
+ method: 'POST',
+ credentials: 'include',
+ headers,
+ body: JSON.stringify({
+ secret_key: Array.from(secretKey),
+ ...(prefix ? { prefix } : {}),
+ ...(suffix ? { suffix } : {}),
+ ignoreCase: !!ignoreCase,
+ ...(iterations != null ? { iterations } : {}),
+ ...(durationMs != null ? { duration_ms: Math.round(durationMs) } : {}),
+ }),
+ signal,
+ });
+ const json = await resp.json().catch(() => ({}));
+ if (!resp.ok) {
+ const msg = json?.error_description || json?.error?.message || json?.message || `apply failed (${resp.status})`;
+ const err = new Error(msg);
+ err.status = resp.status;
+ throw err;
+ }
+ return json.data;
+}
+
export async function deleteAgentSolanaWallet(agentId) {
const delHeaders = {};
const delToken = await consumeCsrfToken();
diff --git a/src/agent-vanity-grinder.js b/src/agent-vanity-grinder.js
index 3ae7fce8a..42065ea2e 100644
--- a/src/agent-vanity-grinder.js
+++ b/src/agent-vanity-grinder.js
@@ -12,9 +12,9 @@
import { openVanityModal } from './erc8004/vanity-modal.js';
import {
fetchAgentSolanaWallet,
- provisionAgentSolanaWallet,
- deleteAgentSolanaWallet,
+ applyAgentVanityWallet,
} from './agent-solana-wallet.js';
+import { grindVanity } from './solana/vanity/grinder.js';
const STYLE = `
.agent-vanity-grinder-details { margin: .85rem 0; }
@@ -158,21 +158,35 @@ export function mountAgentVanityGrinderCard({ panel, identity, onProvisioned })
const preGround = typeof choice === 'object' ? choice.secretKey : null;
if (state.hasWallet) {
- if (!confirm('Replace the existing Solana wallet with a vanity-ground one? The old key will be discarded — funds will be lost if not transferred first.')) return;
+ if (!confirm('Replace this agent’s wallet with a vanity address? Any SOL or tokens it currently holds are automatically moved to the new address first — funds are never lost.')) return;
}
state.busy = true; state.err = null; state.progress = null; render();
abort = new AbortController();
try {
- if (state.hasWallet) {
- await deleteAgentSolanaWallet(identity.id);
+ // Grind in the browser (worker pool), then apply through the sweep-safe
+ // endpoint: it migrates any existing balance to the new address BEFORE
+ // swapping the key, so a replace can never strand funds. No delete-first.
+ let secretKey = preGround;
+ let iterations = null;
+ let durationMs = null;
+ if (!secretKey) {
+ const ground = await grindVanity({
+ prefix,
+ signal: abort.signal,
+ onProgress: (p) => { state.progress = p; render(); },
+ });
+ secretKey = ground.secretKey;
+ iterations = ground.attempts;
+ durationMs = ground.durationMs;
}
- const data = await provisionAgentSolanaWallet({
+ const data = await applyAgentVanityWallet({
agentId: identity.id,
- vanityPrefix: prefix,
- preGround,
+ secretKey,
+ prefix,
+ iterations,
+ durationMs,
signal: abort.signal,
- onProgress: (p) => { state.progress = p; render(); },
});
state.hasWallet = true;
state.address = data.address;
diff --git a/src/three-token-page.js b/src/three-token-page.js
index 7c3a08973..10933a675 100644
--- a/src/three-token-page.js
+++ b/src/three-token-page.js
@@ -50,6 +50,7 @@ const relTime = (sec) => {
function injectStyles() {
const css = `
:root { color-scheme: dark; }
+ html { scroll-behavior: smooth; }
* { box-sizing: border-box; }
body { margin:0; background:#0a0a0d; color:#f5f5f7; font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,sans-serif; -webkit-font-smoothing:antialiased; }
a { color:inherit; }
@@ -65,6 +66,17 @@ function injectStyles() {
.tk-stat { background:#111116; border:1px solid #1d1d24; border-radius:12px; padding:14px 16px; }
.tk-stat-l { font-size:11px; text-transform:uppercase; letter-spacing:0.06em; color:#7d7d86; margin-bottom:5px; }
.tk-stat-v { font-size:22px; font-weight:700; font-family:ui-monospace,Menlo,monospace; }
+ .tk-why { margin:2px 0 22px; }
+ .tk-why h2 { font-size:12px; text-transform:uppercase; letter-spacing:0.06em; color:#7d7d86; margin:0 0 12px; }
+ .tk-why-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(212px,1fr)); gap:12px; }
+ .tk-why-card { background:#111116; border:1px solid #1d1d24; border-radius:12px; padding:15px 16px; transition:border-color .15s,transform .12s; }
+ .tk-why-card:hover { border-color:#2a2a32; transform:translateY(-2px); }
+ .tk-why-ico { font-size:19px; line-height:1; margin-bottom:9px; }
+ .tk-why-t { font-size:14px; font-weight:700; margin:0 0 5px; letter-spacing:-0.01em; color:#f5f5f7; }
+ .tk-why-d { font-size:12.5px; color:#9a9aa3; line-height:1.5; margin:0; }
+ .tk-why-d b { color:#4ade80; font-weight:700; }
+ .tk-why-link { display:inline-block; margin-top:9px; font-size:12px; color:#7CC4FF; text-decoration:none; }
+ .tk-why-link:hover { text-decoration:underline; }
.tk-grid { display:grid; grid-template-columns:1.1fr 0.9fr; gap:18px; }
@media (max-width:820px){ .tk-grid { grid-template-columns:1fr; } }
.tk-card { background:#111116; border:1px solid #1d1d24; border-radius:14px; padding:18px; }
@@ -121,7 +133,7 @@ function injectStyles() {
.tk-bb-run a { color:#7CC4FF; text-decoration:none; justify-self:end; white-space:nowrap; }
.tk-bb-run a:hover { text-decoration:underline; }
@media (max-width:560px){ .tk-bb-head { grid-template-columns:repeat(2,1fr); gap:8px; } }
- @media (prefers-reduced-motion: reduce){ .tk-trade.in { animation:none; } .tk-skel { animation:none; } .tk-bb-bar span { transition:none; } }
+ @media (prefers-reduced-motion: reduce){ html { scroll-behavior:auto; } .tk-trade.in { animation:none; } .tk-skel { animation:none; } .tk-bb-bar span { transition:none; } .tk-why-card { transition:none; } }
`;
const el = document.createElement('style');
el.textContent = css;
@@ -146,6 +158,31 @@ function renderHeaderStats(token) {
}).join('');
}
+// ── why hold $THREE — the four real utility pillars ──────────────────────────
+// Each line maps to a live mechanism in the codebase (buyback engine, reflections
+// split leg, hold-to-access tiers, deploy/spend sinks) — concrete, not marketing.
+// The buyback % is wired to the live commitment so the headline is always current.
+function renderWhyHold(commitPct) {
+ const pct = Number.isFinite(Number(commitPct)) ? Number(commitPct) : 50;
+ const pctLabel = `${pct % 1 === 0 ? pct.toFixed(0) : pct.toFixed(1)}%`;
+ const pillars = [
+ { ico: '🔄', t: 'Revenue buybacks', d: `<b>${pctLabel}</b> of all platform revenue buys $THREE on the open market and routes it to the treasury — on-chain, verifiable.`, link: { href: '#tk-bb-proof', label: 'See the proof ↓' } },
+ { ico: '💸', t: 'Holder rewards', d: 'Every paid action reflects $THREE back to holders pro-rata — deflation-free yield, no burn.' },
+ { ico: '🎟️', t: 'Hold to access', d: 'Hold $THREE to unlock fee discounts, higher quotas, and pro perks across the platform.', link: { href: '/dashboard/three-token', label: 'View tiers →' } },
+ { ico: '⚙️', t: 'Powers the economy', d: '$THREE is spent to deploy agents, forge avatars, and trade the marketplace — real usage, real demand.' },
+ ];
+ return `<h2>Why hold $THREE</h2><div class="tk-why-grid">${pillars
+ .map(
+ (p) => `<div class="tk-why-card">
+ <div class="tk-why-ico" aria-hidden="true">${p.ico}</div>
+ <p class="tk-why-t">${esc(p.t)}</p>
+ <p class="tk-why-d">${p.d}</p>
+ ${p.link ? `<a class="tk-why-link" href="${p.link.href}">${esc(p.link.label)}</a>` : ''}
+ </div>`,
+ )
+ .join('')}</div>`;
+}
+
// ── programmatic buybacks (revenue → $THREE → treasury) ──────────────────────
const fmtRunDate = (at) => (at ? new Date(at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '');
@@ -302,6 +339,7 @@ function boot() {
<div class="tk-stats" data-stats>
${Array.from({ length: 4 }, () => `<div class="tk-stat"><div class="tk-skel" style="height:48px"></div></div>`).join('')}
</div>
+ <div class="tk-why" data-why>${renderWhyHold(50)}</div>
<div class="tk-grid">
<div class="tk-card">
<h2>Bonding curve</h2>
@@ -318,7 +356,7 @@ function boot() {
</div>
</div>
</div>
- <div class="tk-card tk-bb">
+ <div class="tk-card tk-bb" id="tk-bb-proof">
<h2>Programmatic buybacks</h2>
<div data-buyback><div class="tk-skel" style="height:96px"></div></div>
</div>
@@ -369,11 +407,16 @@ 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.
+ // Programmatic buyback panel + live commitment % in the "why hold" pillars —
+ // both from one protocol stats fetch.
const bbEl = wrap.querySelector('[data-buyback]');
+ const whyEl = wrap.querySelector('[data-why]');
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); })
+ .then((d) => {
+ bbEl.innerHTML = renderBuyback(d.buyback);
+ if (d.buyback?.commit_pct != null) whyEl.innerHTML = renderWhyHold(d.buyback.commit_pct);
+ })
.catch(() => { bbEl.innerHTML = renderBuyback(null); });
}
diff --git a/src/token-pay.js b/src/token-pay.js
index 2f0e4c63f..11b61c6dd 100644
--- a/src/token-pay.js
+++ b/src/token-pay.js
@@ -132,6 +132,9 @@ export async function payWithToken({
getAssociatedTokenAddressSync,
createTransferInstruction,
createAssociatedTokenAccountIdempotentInstruction,
+ TOKEN_PROGRAM_ID,
+ TOKEN_2022_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
} = spl;
const provider = await getProvider(wallet);
@@ -140,17 +143,35 @@ export async function payWithToken({
const connection = new Connection(rpcEndpoint(), 'confirmed');
const mint = new PublicKey(quote.mint);
- const fromAta = getAssociatedTokenAddressSync(mint, payer);
+
+ // $THREE is a Token-2022 mint, and the mint may differ per network — so the ATA
+ // derivation and transfers MUST target the mint's actual owning token program,
+ // not the legacy default. Read it from the mint account; fall back to the legacy
+ // program only if the lookup fails (a classic-SPL mint).
+ const mintInfo = await connection.getAccountInfo(mint);
+ const tokenProgramId =
+ mintInfo && mintInfo.owner.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;
+
+ const fromAta = getAssociatedTokenAddressSync(mint, payer, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);
const tx = new Transaction();
for (const leg of quote.legs) {
const owner = new PublicKey(leg.address);
// allowOwnerOffCurve: the burn incinerator is off-curve.
- const destAta = getAssociatedTokenAddressSync(mint, owner, true);
+ const destAta = getAssociatedTokenAddressSync(mint, owner, true, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);
// Idempotent: a no-op if the destination ATA already exists; otherwise the
// payer funds its rent so burn/treasury/seller can receive on first use.
- tx.add(createAssociatedTokenAccountIdempotentInstruction(payer, destAta, owner, mint));
- tx.add(createTransferInstruction(fromAta, destAta, payer, BigInt(leg.atomics)));
+ tx.add(
+ createAssociatedTokenAccountIdempotentInstruction(
+ payer,
+ destAta,
+ owner,
+ mint,
+ tokenProgramId,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ ),
+ );
+ tx.add(createTransferInstruction(fromAta, destAta, payer, BigInt(leg.atomics), [], tokenProgramId));
}
// Memo carries the quote nonce so the server can bind this tx to the quote.
tx.add(
diff --git a/tests/api/token-market-shared-cache.test.js b/tests/api/token-market-shared-cache.test.js
new file mode 100644
index 000000000..585f27d4d
--- /dev/null
+++ b/tests/api/token-market-shared-cache.test.js
@@ -0,0 +1,84 @@
+// Shared (L2) cache test for api/_lib/market/token-market.js.
+//
+// The scaling defense: Vercel runs many stateless lambda instances. The
+// per-instance in-process cache (L1) is wiped on every cold start, so under a
+// traffic spike each cold instance would independently fan out to all three
+// upstreams. The shared cache (L2) lets a cold lambda serve a sibling's recent
+// fetch instead, collapsing fleet-wide upstream load to ~1 call per key/window.
+//
+// We simulate a cold instance by clearing L1 only (__resetMarketCache) while the
+// L2 store survives, and assert the second read hits zero upstreams. Fetch is
+// fully mocked; no network. No Redis env here, so L2 resolves to cache.js's
+// in-memory fallback — same code path, deterministic in tests.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+let fetchCalls = [];
+let fetchResponses = [];
+vi.stubGlobal('fetch', (url) => {
+ fetchCalls.push(String(url));
+ const resp = fetchResponses.shift();
+ if (!resp) throw new Error(`Unexpected fetch: ${url}`);
+ return Promise.resolve({
+ ok: resp.ok ?? true,
+ status: resp.status ?? 200,
+ json: async () => resp.body,
+ text: async () => (typeof resp.body === 'string' ? resp.body : JSON.stringify(resp.body)),
+ });
+});
+
+import { fetchTokenMarketData, __resetMarketCache } from '../../api/_lib/market/token-market.js';
+
+const MINT = 'THREEsynthetic222222222222222222222222222222';
+const DEX_OK = {
+ pairs: [
+ { priceUsd: '0.5', marketCap: 500000, liquidity: { usd: 100000 }, volume: { h24: 5000 }, priceChange: { h24: 1.5 } },
+ ],
+};
+
+beforeEach(() => {
+ fetchCalls = [];
+ fetchResponses = [];
+ // No Birdeye key → DexScreener is the first source, so one upstream call.
+ delete process.env.BIRDEYE_API_KEY;
+ __resetMarketCache();
+});
+
+afterEach(() => {
+ if (fetchResponses.length) {
+ throw new Error(`Test left ${fetchResponses.length} unconsumed fetch mock(s)`);
+ }
+});
+
+describe('token-market shared (L2) cache', () => {
+ it('serves a cold instance (L1 cleared) from the shared cache with zero upstream calls', async () => {
+ // Read 1: cold everywhere — one upstream fetch, populates L1 + L2.
+ fetchResponses = [{ body: DEX_OK }];
+ const first = await fetchTokenMarketData(MINT);
+ expect(first.source).toBe('dexscreener');
+ expect(first.price_usd).toBe(0.5);
+ expect(fetchCalls).toHaveLength(1);
+
+ // Simulate a NEW cold lambda: clear the in-process L1 only; L2 survives.
+ __resetMarketCache();
+ fetchCalls = [];
+ fetchResponses = []; // any upstream call would throw "Unexpected fetch"
+
+ const second = await fetchTokenMarketData(MINT);
+ expect(second.price_usd).toBe(0.5);
+ expect(fetchCalls).toHaveLength(0); // served entirely from the shared cache
+ });
+
+ it('still bypasses the shared cache when fresh:true is requested', async () => {
+ fetchResponses = [{ body: DEX_OK }];
+ await fetchTokenMarketData(MINT);
+
+ // A forced-fresh read must hit upstream even though L2 holds a value.
+ __resetMarketCache();
+ fetchCalls = [];
+ fetchResponses = [{ body: DEX_OK }];
+ const fresh = await fetchTokenMarketData(MINT, { fresh: true });
+ expect(fresh.source).toBe('dexscreener');
+ expect(fetchCalls).toHaveLength(1);
+ });
+});