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(three-token): show the treasury and rewards wallets live, with a fee-flow diagram and light theme

nirholas05faebd92f86
diff --git a/api/_lib/token/wallet-balances.js b/api/_lib/token/wallet-balances.js
new file mode 100644
index 000000000..6ae07c4f5
--- /dev/null
+++ b/api/_lib/token/wallet-balances.js
@@ -0,0 +1,101 @@
+// Live balances of the two public $THREE fund-routing wallets.
+//
+// The treasury (funds buybacks) and the holder-rewards pool receive a share of
+// every $THREE split (SPLIT_POLICIES in ./config.js). Publishing their addresses
+// is only half of "people trust what they can check": this module reads what
+// each one actually holds, $THREE and USDC, straight from Solana so /three-token
+// can show it next to the address.
+//
+// Honesty contract: a balance is either a real RPC read or explicitly
+// unavailable. An empty token-account list is a real zero (the wallet has never
+// held that mint); an RPC failure after the whole failover chain is exhausted is
+// `null` with `ok: false`, never a zero and never a cached stale number dressed
+// up as current.
+
+import { PublicKey } from '@solana/web3.js';
+import { rpcFallbackFromEnv } from '../solana/rpc-fallback.js';
+import { cacheGet, cacheSet } from '../cache.js';
+import { SOLANA_USDC_MINT } from '../../payments/_config.js';
+import { TOKEN_MINT, treasuryWalletOrNull, rewardsWalletOrNull } from './config.js';
+
+const CACHE_KEY = 'three-token:public-wallet-balances:v1';
+const CACHE_TTL_S = 60;
+
+// The assets shown per wallet. `mint` is resolved at call time so a devnet or
+// test override of THREE_TOKEN_MINT / SOLANA_USDC_MINT is honoured.
+const ASSETS = [
+ { key: 'three', symbol: '$THREE', mint: () => TOKEN_MINT },
+ { key: 'usdc', symbol: 'USDC', mint: () => SOLANA_USDC_MINT },
+];
+
+/**
+ * Sum every token account `owner` holds for `mint`. Querying by mint (not by a
+ * derived ATA) covers both the classic SPL program and Token-2022, which $THREE
+ * uses, and also counts any non-ATA account the wallet happens to own.
+ * @returns {Promise<{ amount: number, atomics: string, decimals: number }>}
+ */
+async function readMintBalance(rpc, owner, mint) {
+ const res = await rpc.withFallback((conn) =>
+ conn.getParsedTokenAccountsByOwner(new PublicKey(owner), { mint: new PublicKey(mint) }, 'confirmed'),
+ );
+ let atomics = 0n;
+ let decimals = null;
+ for (const { account } of res?.value ?? []) {
+ const ta = account?.data?.parsed?.info?.tokenAmount;
+ if (!ta?.amount) continue;
+ atomics += BigInt(ta.amount);
+ if (decimals == null && Number.isInteger(ta.decimals)) decimals = ta.decimals;
+ }
+ const d = decimals ?? 0;
+ return { atomics: atomics.toString(), decimals: d, amount: Number(atomics) / 10 ** d };
+}
+
+async function readWallet(rpc, address) {
+ const balances = {};
+ await Promise.all(
+ ASSETS.map(async (asset) => {
+ try {
+ const b = await readMintBalance(rpc, address, asset.mint());
+ balances[asset.key] = { symbol: asset.symbol, ok: true, ...b };
+ } catch (err) {
+ console.warn(`[three-token] ${asset.symbol} balance read failed for ${address}:`, err?.message || err);
+ balances[asset.key] = { symbol: asset.symbol, ok: false, amount: null, atomics: null, decimals: null };
+ }
+ }),
+ );
+ return balances;
+}
+
+/**
+ * Public, read-only snapshot of the treasury and rewards wallets.
+ * Unconfigured wallets are listed with `configured: false` so the page can say
+ * "not yet published" instead of hiding the row.
+ * @returns {Promise<{ as_of: string, wallets: Array<{ role: string, address: string|null, configured: boolean, balances: object|null }> }>}
+ */
+export async function publicWalletBalances() {
+ const cached = await cacheGet(CACHE_KEY);
+ if (cached) return cached;
+
+ const targets = [
+ { role: 'treasury', address: treasuryWalletOrNull() },
+ { role: 'rewards', address: rewardsWalletOrNull() },
+ ];
+ const needsRpc = targets.some((t) => t.address);
+ const rpc = needsRpc ? rpcFallbackFromEnv({ network: 'mainnet', commitment: 'confirmed' }) : null;
+
+ const wallets = await Promise.all(
+ targets.map(async (t) => ({
+ role: t.role,
+ address: t.address,
+ configured: t.address != null,
+ balances: t.address ? await readWallet(rpc, t.address) : null,
+ })),
+ );
+ const snapshot = { as_of: new Date().toISOString(), wallets };
+
+ // Cache only a fully successful read: a partial failure must be retried on
+ // the next request, not pinned for a minute.
+ const allOk = wallets.every((w) => !w.balances || Object.values(w.balances).every((b) => b.ok));
+ if (allOk) cacheSet(CACHE_KEY, snapshot, CACHE_TTL_S).catch(() => {});
+ return snapshot;
+}
diff --git a/api/three-token/[action].js b/api/three-token/[action].js
index 187e756cd..37fa0fade 100644
--- a/api/three-token/[action].js
+++ b/api/three-token/[action].js
@@ -6,6 +6,7 @@
* GET /api/three-token/burns: platform burn ledger (always empty: no platform burns)
* GET /api/three-token/activity — protocol activity feed
* GET /api/three-token/leaderboard — ranked $THREE holders (public, paginated)
+ * GET /api/three-token/wallets: treasury + rewards wallet addresses and live balances (public)
*
* Market data (price, market cap, supply, holders) comes from the shared market
* module — Birdeye → DexScreener → GeckoTerminal failover with a stale cache —
@@ -24,6 +25,7 @@ import { threeHolderBalances, threeHolderCount } from '../_lib/coin/three-holder
import { buybackStats } from '../_lib/token/buyback.js';
import { microbuyStats } from '../_lib/token/microbuy.js';
import { fetchPumpVerification } from '../_lib/pump-verification.js';
+import { publicWalletBalances } from '../_lib/token/wallet-balances.js';
// Truncate a base58 wallet for display: "FeMb…Jpump".
function shortWallet(addr) {
@@ -172,6 +174,14 @@ export default wrap(async (req, res) => {
);
}
+ if (action === 'wallets') {
+ // The two public receivers of every $THREE split, with what each holds right
+ // now. Unset wallets come back `configured: false` (never hidden), and a
+ // balance the RPC chain could not read comes back `ok: false` (never zero).
+ const snapshot = await publicWalletBalances();
+ return json(res, 200, snapshot, { 'cache-control': 'public, s-maxage=30, stale-while-revalidate=60' });
+ }
+
if (action === 'revenue-share') {
const user = await getSessionUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
diff --git a/src/three-token-fee-flow.js b/src/three-token-fee-flow.js
new file mode 100644
index 000000000..f6298fbff
--- /dev/null
+++ b/src/three-token-fee-flow.js
@@ -0,0 +1,353 @@
+// "Where every $100 goes" on /three-token.
+//
+// Renders every $THREE split policy the platform enforces, read live from
+// GET /api/token/config (`split_policies`, basis points per role), as "of every
+// $100 paid for <surface>". No split figure is typed here: the numbers come
+// from the API, so a policy added to SPLIT_POLICIES in api/_lib/token/config.js
+// shows up on the page with no change to this file (an unknown key gets a
+// readable label derived from its name).
+//
+// Under the breakdown, "where the money is": the treasury and holder-rewards
+// wallets with copy buttons, Solscan links and their live $THREE and USDC
+// balances (GET /api/three-token/wallets, real RPC reads), plus a summary of
+// the buyback history the page already loads for its buyback panel.
+
+import { errorStateHTML } from './shared/state-kit.js';
+
+// ── human labels: the ONE place a policy key or role gets its words ─────────
+// Keys match SPLIT_POLICIES. Copy only; never a number.
+export const POLICY_COPY = {
+ consumption: {
+ label: 'Paid compute',
+ detail: 'Forge paid tiers, voice cloning, 3D generation over MCP, selfie to avatar',
+ },
+ marketplace_sale: {
+ label: 'Marketplace sales',
+ detail: 'Skills, animations, avatars, assets and collectible resales',
+ roles: { seller: 'Seller or creator' },
+ },
+ scarcity_mint: {
+ label: 'Scarcity mints',
+ detail: 'Limited drops, rare-name auctions and pay-to-mint',
+ },
+ spin: {
+ label: 'Spins',
+ detail: 'Paid spins of the in-app wheel',
+ },
+ copy_performance_fee: {
+ label: 'Copy-trading performance fees',
+ detail: 'Charged only on a copier\'s realized profit',
+ roles: { seller: 'Trader you copy' },
+ },
+};
+
+export const ROLE_COPY = {
+ seller: { label: 'Seller or creator', note: 'keeps the sale' },
+ treasury: { label: 'Treasury', note: 'funds $THREE buybacks' },
+ rewards: { label: 'Holder rewards', note: 'paid back to $THREE holders' },
+};
+
+// Display order: the policies people meet most first. Anything not listed
+// (a newly added policy) follows in the order the API returns it.
+const POLICY_ORDER = ['consumption', 'marketplace_sale', 'scarcity_mint', 'spin', 'copy_performance_fee'];
+
+const esc = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+
+/** "copy_performance_fee" becomes "Copy performance fee". */
+export function humanizeKey(key) {
+ const s = String(key || '').replace(/[_-]+/g, ' ').trim();
+ return s ? s[0].toUpperCase() + s.slice(1) : 'Other';
+}
+
+export function policyLabel(key) {
+ return POLICY_COPY[key]?.label || humanizeKey(key);
+}
+
+export function roleLabel(role, policyKey) {
+ return POLICY_COPY[policyKey]?.roles?.[role] || ROLE_COPY[role]?.label || humanizeKey(role);
+}
+
+/** Dollars out of $100 for a leg in basis points (10,000 bps = $100). */
+export function dollarsOfHundred(bps) {
+ return Number(bps) / 100;
+}
+
+const fmtDollars = (n) =>
+ `$${Number(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+
+/** Policies from a public token config, in display order. */
+export function orderedPolicies(config) {
+ const policies = config?.split_policies && typeof config.split_policies === 'object' ? config.split_policies : {};
+ const keys = Object.keys(policies).filter((k) => Array.isArray(policies[k]) && policies[k].length);
+ const rank = (k) => {
+ const i = POLICY_ORDER.indexOf(k);
+ return i === -1 ? POLICY_ORDER.length + keys.indexOf(k) : i;
+ };
+ return keys.sort((a, b) => rank(a) - rank(b)).map((key) => ({ key, legs: policies[key] }));
+}
+
+function roleClass(role) {
+ return ROLE_COPY[role] ? `tk-ff-r-${role}` : 'tk-ff-r-other';
+}
+
+function renderPolicy({ key, legs }) {
+ const detail = POLICY_COPY[key]?.detail;
+ const totalBps = legs.reduce((sum, leg) => sum + (Number(leg.bps) || 0), 0) || 1;
+ const parts = legs.map((leg) => ({
+ role: leg.role,
+ bps: Number(leg.bps) || 0,
+ label: roleLabel(leg.role, key),
+ note: ROLE_COPY[leg.role]?.note || '',
+ dollars: dollarsOfHundred(leg.bps),
+ }));
+ const sentence = parts.map((p) => `${fmtDollars(p.dollars)} to ${p.label.toLowerCase()}`).join(', ');
+ const segments = parts
+ .map(
+ (p) =>
+ `<span class="tk-ff-seg ${roleClass(p.role)}" style="flex-grow:${p.bps}">${p.bps * 8 >= totalBps ? `<span class="tk-ff-seg-t">${esc(fmtDollars(p.dollars))}</span>` : ''}</span>`,
+ )
+ .join('');
+ const legend = parts
+ .map(
+ (p) => `<li class="tk-ff-leg">
+ <span class="tk-ff-dot ${roleClass(p.role)}" aria-hidden="true"></span>
+ <span class="tk-ff-amt">${esc(fmtDollars(p.dollars))}</span>
+ <span class="tk-ff-role">${esc(p.label)}${p.note ? ` <small>${esc(p.note)}</small>` : ''}</span>
+ </li>`,
+ )
+ .join('');
+ return `<li class="tk-ff-row" data-policy="${esc(key)}">
+ <div class="tk-ff-row-h">
+ <h3 class="tk-ff-name">Of every $100 paid for ${esc(policyLabel(key).toLowerCase())}</h3>
+ ${detail ? `<p class="tk-ff-detail">${esc(detail)}</p>` : ''}
+ </div>
+ <div class="tk-ff-bar" role="img" aria-label="${esc(`Of every $100: ${sentence}.`)}">${segments}</div>
+ <ul class="tk-ff-legend">${legend}</ul>
+ </li>`;
+}
+
+/** The breakdown list for a public token config. Pure: string in, string out. */
+export function renderPolicies(config) {
+ const policies = orderedPolicies(config);
+ if (!policies.length) {
+ return `<p class="tk-ff-note">No split policy is published right now. Every $THREE payment is refused until one is, so no money moves without a published split.</p>`;
+ }
+ return `<ul class="tk-ff-list">${policies.map(renderPolicy).join('')}</ul>`;
+}
+
+// ── where the money is ───────────────────────────────────────────────────────
+
+const WALLET_COPY = {
+ treasury: {
+ label: 'Treasury',
+ note: 'Receives the treasury share of every split and funds $THREE buybacks.',
+ },
+ rewards: {
+ label: 'Holder rewards pool',
+ note: 'Receives the holder-rewards share and pays it back to $THREE holders pro rata.',
+ },
+};
+
+const fmtTokenAmount = (n) => {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return '';
+ if (Math.abs(v) >= 1e9) return `${(v / 1e9).toFixed(2)}B`;
+ if (Math.abs(v) >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
+ if (Math.abs(v) >= 1e4) return `${(v / 1e3).toFixed(1)}K`;
+ return v.toLocaleString('en-US', { maximumFractionDigits: 2 });
+};
+
+function renderBalance(b, kind) {
+ if (!b || !b.ok) {
+ return `<div class="tk-ff-bal"><span class="tk-ff-bal-k">${esc(b?.symbol || kind)}</span><span class="tk-ff-bal-v tk-ff-muted">Balance unavailable</span></div>`;
+ }
+ const full = Number(b.amount).toLocaleString('en-US', { maximumFractionDigits: 6 });
+ const shown = kind === 'usdc'
+ ? Number(b.amount).toLocaleString('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 2 })
+ : fmtTokenAmount(b.amount);
+ return `<div class="tk-ff-bal"><span class="tk-ff-bal-k">${esc(b.symbol)}</span><span class="tk-ff-bal-v" title="${esc(`${full} ${b.symbol}`)}">${esc(shown)}</span></div>`;
+}
+
+function renderWallet(w) {
+ const copy = WALLET_COPY[w.role] || { label: humanizeKey(w.role), note: '' };
+ if (!w.configured || !w.address) {
+ return `<li class="tk-ff-wallet" data-wallet="${esc(w.role)}">
+ <div class="tk-ff-wallet-h">
+ <h3 class="tk-ff-wallet-name">${esc(copy.label)}</h3>
+ <span class="tk-ff-pill">Not yet published</span>
+ </div>
+ <p class="tk-ff-detail">${esc(copy.note)}</p>
+ <p class="tk-ff-note">The address has not been published yet. Payments that include this share are paused until it is, so no money is ever sent to an unset address.</p>
+ </li>`;
+ }
+ const addr = esc(w.address);
+ return `<li class="tk-ff-wallet" data-wallet="${esc(w.role)}">
+ <div class="tk-ff-wallet-h">
+ <h3 class="tk-ff-wallet-name">${esc(copy.label)}</h3>
+ </div>
+ <p class="tk-ff-detail">${esc(copy.note)}</p>
+ <div class="tk-ff-addr-row">
+ <code class="tk-ff-addr">${addr}</code>
+ <button type="button" class="tk-ff-btn" data-ff-copy="${addr}" aria-label="Copy the ${esc(copy.label.toLowerCase())} address">Copy</button>
+ <a class="tk-ff-btn" href="https://solscan.io/account/${addr}" target="_blank" rel="noopener" aria-label="View the ${esc(copy.label.toLowerCase())} on Solscan (opens in a new tab)">Solscan ↗</a>
+ </div>
+ <div class="tk-ff-bals">
+ ${renderBalance(w.balances?.three, 'three')}
+ ${renderBalance(w.balances?.usdc, 'usdc')}
+ </div>
+ </li>`;
+}
+
+/** The wallet rows for a GET /api/three-token/wallets snapshot. Pure. */
+export function renderWallets(snapshot) {
+ const wallets = Array.isArray(snapshot?.wallets) ? snapshot.wallets : [];
+ const asOf = snapshot?.as_of ? new Date(snapshot.as_of) : null;
+ const stamp = asOf && !Number.isNaN(asOf.getTime())
+ ? `Balances read from Solana at ${asOf.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}.`
+ : '';
+ return `<ul class="tk-ff-wallets">${wallets.map(renderWallet).join('')}</ul>${stamp ? `<p class="tk-ff-src">${esc(stamp)}</p>` : ''}`;
+}
+
+/** One-line summary of the buyback history the page already fetched. */
+export function renderBuybackSummary(bb) {
+ if (!bb) return '';
+ const runs = Number(bb.runs) || 0;
+ if (!runs) {
+ return `<p class="tk-ff-bb">No treasury buyback has run yet. Each one will appear in <a href="#tk-bb-proof">Programmatic buybacks</a> with its Solscan receipt.</p>`;
+ }
+ const bought = fmtTokenAmount(bb.three_bought);
+ return `<p class="tk-ff-bb">${runs.toLocaleString('en-US')} buyback${runs === 1 ? '' : 's'} so far, ${esc(bought)} $THREE bought into the treasury. <a href="#tk-bb-proof">See every receipt</a></p>`;
+}
+
+// ── styles (theme tokens come from the page's --tk-* variables) ──────────────
+export const FEE_FLOW_CSS = `
+ .tk-ff { margin-top:18px; }
+ .tk-ff-lead { color:var(--tk-muted); font-size:13.5px; line-height:1.6; margin:0 0 16px; max-width:720px; }
+ .tk-ff-lead a, .tk-ff-src a, .tk-ff-bb a { color:var(--tk-link); text-decoration:none; }
+ .tk-ff-lead a:hover, .tk-ff-src a:hover, .tk-ff-bb a:hover { text-decoration:underline; }
+ .tk-ff-list, .tk-ff-legend, .tk-ff-wallets { list-style:none; margin:0; padding:0; }
+ .tk-ff-list { display:grid; gap:14px; }
+ .tk-ff-row { padding:14px; border-radius:12px; background:var(--tk-inset); border:1px solid var(--tk-border); transition:border-color .15s; }
+ .tk-ff-row:hover { border-color:var(--tk-border-hover); }
+ .tk-ff-row-h { margin-bottom:10px; }
+ .tk-ff-name { font-size:14.5px; font-weight:700; margin:0; color:var(--tk-text); letter-spacing:-0.01em; }
+ .tk-ff-detail { margin:3px 0 0; font-size:12.5px; color:var(--tk-dim); line-height:1.5; }
+ .tk-ff-bar { display:flex; gap:2px; height:30px; border-radius:8px; overflow:hidden; }
+ .tk-ff-seg { flex-basis:0; min-width:4px; display:flex; align-items:center; justify-content:center; transition:filter .15s; }
+ .tk-ff-row:hover .tk-ff-seg { filter:saturate(1.15); }
+ .tk-ff-seg-t { font-size:12px; font-weight:700; font-family:ui-monospace,Menlo,monospace; color:#07130c; white-space:nowrap; overflow:hidden; text-overflow:clip; padding:0 6px; }
+ .tk-ff-r-seller { background:#a78bfa; }
+ .tk-ff-r-treasury { background:#4ade80; }
+ .tk-ff-r-rewards { background:#22d3ee; }
+ .tk-ff-r-other { background:#fbbf24; }
+ .tk-ff-legend { display:flex; flex-wrap:wrap; gap:6px 18px; margin-top:10px; }
+ .tk-ff-leg { display:flex; align-items:baseline; gap:7px; font-size:13px; color:var(--tk-text-2); min-width:0; }
+ .tk-ff-dot { width:9px; height:9px; border-radius:3px; flex-shrink:0; align-self:center; }
+ .tk-ff-amt { font-family:ui-monospace,Menlo,monospace; font-weight:700; color:var(--tk-text); }
+ .tk-ff-role small { color:var(--tk-dim); font-size:12px; }
+ .tk-ff-sub { font-size:12px; text-transform:uppercase; letter-spacing:0.06em; color:var(--tk-dim); margin:24px 0 12px; font-weight:600; }
+ .tk-ff-wallets { display:grid; grid-template-columns:repeat(auto-fit,minmax(280px,1fr)); gap:12px; }
+ .tk-ff-wallet { padding:14px; border-radius:12px; background:var(--tk-inset); border:1px solid var(--tk-border); min-width:0; }
+ .tk-ff-wallet-h { display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; }
+ .tk-ff-wallet-name { font-size:14.5px; font-weight:700; margin:0; color:var(--tk-text); }
+ .tk-ff-pill { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:0.05em; padding:3px 8px; border-radius:999px; color:var(--tk-warn); border:1px solid currentColor; }
+ .tk-ff-note { margin:10px 0 0; font-size:12.5px; color:var(--tk-muted); line-height:1.55; }
+ .tk-ff-addr-row { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-top:10px; min-width:0; }
+ .tk-ff-addr { flex:1 1 220px; min-width:0; font-family:ui-monospace,Menlo,monospace; font-size:12px; color:var(--tk-text-2); background:var(--tk-surface); border:1px solid var(--tk-border); border-radius:8px; padding:7px 9px; overflow-wrap:anywhere; }
+ .tk-ff-btn { appearance:none; font:inherit; font-size:12.5px; font-weight:600; color:var(--tk-text); background:var(--tk-btn); border:1px solid var(--tk-border-2); border-radius:8px; padding:7px 11px; cursor:pointer; text-decoration:none; white-space:nowrap; transition:background .15s,border-color .15s,transform .1s; }
+ .tk-ff-btn:hover { background:var(--tk-btn-hover); border-color:var(--tk-border-hover); }
+ .tk-ff-btn:active { transform:translateY(1px); }
+ .tk-ff-btn:focus-visible { outline:2px solid var(--tk-link); outline-offset:2px; }
+ .tk-ff-bals { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-top:12px; }
+ .tk-ff-bal { display:flex; flex-direction:column; gap:3px; min-width:0; }
+ .tk-ff-bal-k { font-size:11px; text-transform:uppercase; letter-spacing:0.06em; color:var(--tk-dim); }
+ .tk-ff-bal-v { font-size:18px; font-weight:700; font-family:ui-monospace,Menlo,monospace; color:var(--tk-text); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
+ .tk-ff-bal-v.tk-ff-muted { font-size:13px; font-weight:600; color:var(--tk-muted); font-family:inherit; }
+ .tk-ff-src, .tk-ff-bb { font-size:12.5px; color:var(--tk-dim); margin:12px 0 0; line-height:1.55; }
+ .tk-ff-skel-row { height:98px; margin-bottom:14px; }
+ @media (max-width:560px){ .tk-ff-bar { height:26px; } .tk-ff-seg-t { font-size:11px; padding:0 3px; } }
+ @media (prefers-reduced-motion: reduce){ .tk-ff-row, .tk-ff-seg, .tk-ff-btn { transition:none; } }
+`;
+
+const SKELETON_ROWS = (n) => Array.from({ length: n }, () => '<div class="tk-skel tk-ff-skel-row"></div>').join('');
+
+/**
+ * Mount the section into `host`. Fetches the config and the wallet snapshot
+ * independently so one failing never blanks the other.
+ * @param {HTMLElement} host
+ * @param {{ copyText: (text: string) => Promise<boolean> }} deps
+ * @returns {{ setBuyback: (bb: object|null) => void }}
+ */
+export function mountFeeFlow(host, { copyText }) {
+ host.innerHTML = `
+ <h2>Where every $100 goes</h2>
+ <p class="tk-ff-lead">Every payment made in $THREE is split on-chain by a published policy, each share paid straight to its wallet. These splits are read live from <a href="/api/token/config" target="_blank" rel="noopener">the public token config</a>, the same one the payment code enforces. The platform never burns $THREE: every share goes to a seller, the treasury, or holders, and nothing is destroyed. <a href="/docs/three-thesis">Why buybacks instead of burns</a></p>
+ <div data-ff-policies aria-live="polite" aria-busy="true">${SKELETON_ROWS(3)}</div>
+ <h3 class="tk-ff-sub">Where the money is</h3>
+ <div data-ff-wallets aria-live="polite" aria-busy="true">${SKELETON_ROWS(1)}</div>
+ <div data-ff-bb></div>`;
+
+ const policiesEl = host.querySelector('[data-ff-policies]');
+ const walletsEl = host.querySelector('[data-ff-wallets]');
+ const bbEl = host.querySelector('[data-ff-bb]');
+
+ const loadJson = (url) =>
+ fetch(url, { headers: { accept: 'application/json' } }).then((r) =>
+ r.ok ? r.json() : Promise.reject(new Error(`${url} ${r.status}`)),
+ );
+
+ const loadPolicies = () => {
+ policiesEl.setAttribute('aria-busy', 'true');
+ policiesEl.innerHTML = SKELETON_ROWS(3);
+ return loadJson('/api/token/config')
+ .then((cfg) => { policiesEl.innerHTML = renderPolicies(cfg); })
+ .catch(() => {
+ policiesEl.innerHTML = errorStateHTML({
+ title: 'The split policies did not load',
+ body: 'The public token config did not respond. Payments are unaffected; retry, or read the same data directly.',
+ actions: [
+ { label: 'Retry', id: 'ff-policies-retry', primary: true },
+ { label: 'Open /api/token/config', id: 'ff-config-open' },
+ ],
+ });
+ })
+ .finally(() => policiesEl.setAttribute('aria-busy', 'false'));
+ };
+
+ const loadWallets = () => {
+ walletsEl.setAttribute('aria-busy', 'true');
+ walletsEl.innerHTML = SKELETON_ROWS(1);
+ return loadJson('/api/three-token/wallets')
+ .then((snap) => { walletsEl.innerHTML = renderWallets(snap); })
+ .catch(() => {
+ walletsEl.innerHTML = errorStateHTML({
+ title: 'Wallet balances did not load',
+ body: 'The wallet feed did not respond. Retry in a moment; every balance is also readable on Solscan.',
+ actions: [{ label: 'Retry', id: 'ff-wallets-retry', primary: true }],
+ });
+ })
+ .finally(() => walletsEl.setAttribute('aria-busy', 'false'));
+ };
+
+ host.addEventListener('click', async (e) => {
+ const act = e.target.closest('[data-sk-action]')?.dataset.skAction;
+ if (act === 'ff-policies-retry') return loadPolicies();
+ if (act === 'ff-config-open') return window.open('/api/token/config', '_blank', 'noopener');
+ if (act === 'ff-wallets-retry') return loadWallets();
+ const copyBtn = e.target.closest('[data-ff-copy]');
+ if (copyBtn) {
+ const ok = await copyText(copyBtn.dataset.ffCopy);
+ const label = copyBtn.dataset.label || (copyBtn.dataset.label = copyBtn.textContent);
+ copyBtn.textContent = ok ? 'Copied' : 'Copy failed';
+ setTimeout(() => { copyBtn.textContent = label; }, 1600);
+ }
+ });
+
+ loadPolicies();
+ loadWallets();
+
+ return {
+ setBuyback(bb) { bbEl.innerHTML = renderBuybackSummary(bb); },
+ };
+}
diff --git a/src/three-token-page.js b/src/three-token-page.js
index 27b71d913..bb78f1ae5 100644
--- a/src/three-token-page.js
+++ b/src/three-token-page.js
@@ -14,6 +14,7 @@ import { emptyStateHTML, errorStateHTML, ensureStateKitStyles } from './shared/s
import { paintVerifiedBadge } from './pump/verified-badge.js';
import { chartEmbedUrls } from './shared/chart-embeds.js';
import { watchEmbed, embedFallbackNode } from './shared/embed-guard.js';
+import { mountFeeFlow, FEE_FLOW_CSS } from './three-token-fee-flow.js';
import {
THREE_DEXTOOLS_PAIR,
DEXTOOLS_PAIR_URL,
@@ -87,34 +88,49 @@ const relTime = (sec) => {
// ── styles ──────────────────────────────────────────────────────────────────
function injectStyles() {
const css = `
- :root { color-scheme: dark; }
+ :root {
+ color-scheme: dark;
+ --tk-bg:#0a0a0d; --tk-surface:#111116; --tk-inset:#0e0e12; --tk-inset-hover:#15151b; --tk-inset-border:#16161c;
+ --tk-border:#1d1d24; --tk-border-2:#232329; --tk-border-hover:#3a3a42;
+ --tk-text:#f5f5f7; --tk-text-2:#c8c8d0; --tk-muted:#9a9aa3; --tk-dim:#85858e; --tk-strong:#fff;
+ --tk-btn:#1a1a20; --tk-btn-hover:#23232b; --tk-link:#7CC4FF; --tk-warn:#fbbf24;
+ --tk-skel-a:#16161c; --tk-skel-b:#1d1d24;
+ }
+ :root[data-theme="light"] {
+ color-scheme: light;
+ --tk-bg:#f6f6f8; --tk-surface:#ffffff; --tk-inset:#f3f3f6; --tk-inset-hover:#ececf1; --tk-inset-border:#e6e6ec;
+ --tk-border:#e2e2e8; --tk-border-2:#d6d6de; --tk-border-hover:#b9b9c4;
+ --tk-text:#111116; --tk-text-2:#33333b; --tk-muted:#55555e; --tk-dim:#62626b; --tk-strong:#000;
+ --tk-btn:#f0f0f4; --tk-btn-hover:#e5e5ec; --tk-link:#0b63b6; --tk-warn:#a15c00;
+ --tk-skel-a:#ececf0; --tk-skel-b:#f6f6f9;
+ }
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; }
+ body { margin:0; background:var(--tk-bg); color:var(--tk-text); font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,sans-serif; -webkit-font-smoothing:antialiased; }
a { color:inherit; }
.tk-wrap { max-width:1080px; margin:0 auto; padding:24px 18px 64px; }
.tk-head { display:flex; align-items:center; gap:14px; margin-bottom:4px; }
- .tk-logo { width:46px; height:46px; border-radius:12px; background:#111116; border:1px solid #232329; display:grid; place-items:center; flex-shrink:0; overflow:hidden; }
+ .tk-logo { width:46px; height:46px; border-radius:12px; background:var(--tk-surface); border:1px solid var(--tk-border-2); display:grid; place-items:center; flex-shrink:0; overflow:hidden; }
.tk-logo img { width:32px; height:32px; display:block; }
.tk-titlerow { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
.tk-title { font-size:26px; font-weight:800; margin:0; letter-spacing:-0.02em; }
- .tk-sub { margin:0; color:#9a9aa3; font-size:13px; }
- .tk-ca { font-family:ui-monospace,Menlo,monospace; font-size:11.5px; color:#8a8a93; cursor:pointer; border:1px solid #232329; border-radius:8px; padding:3px 8px; background:none; }
- .tk-ca:hover { color:#fff; border-color:#3a3a42; }
+ .tk-sub { margin:0; color:var(--tk-muted); font-size:13px; }
+ .tk-ca { font-family:ui-monospace,Menlo,monospace; font-size:11.5px; color:var(--tk-muted); cursor:pointer; border:1px solid var(--tk-border-2); border-radius:8px; padding:3px 8px; background:none; }
+ .tk-ca:hover { color:var(--tk-strong); border-color:var(--tk-border-hover); }
.tk-stats { display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:10px; margin:18px 0 22px; }
- .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 { background:var(--tk-surface); border:1px solid var(--tk-border); border-radius:12px; padding:14px 16px; }
+ .tk-stat-l { font-size:11px; text-transform:uppercase; letter-spacing:0.06em; color:var(--tk-dim); 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 h2 { font-size:12px; text-transform:uppercase; letter-spacing:0.06em; color:var(--tk-dim); 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-card { background:var(--tk-surface); border:1px solid var(--tk-border); border-radius:12px; padding:15px 16px; transition:border-color .15s,transform .12s; }
+ .tk-why-card:hover { border-color:var(--tk-border-hover); 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-t { font-size:14px; font-weight:700; margin:0 0 5px; letter-spacing:-0.01em; color:var(--tk-text); }
+ .tk-why-d { font-size:12.5px; color:var(--tk-muted); 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 { display:inline-block; margin-top:9px; font-size:12px; color:var(--tk-link); 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; } }
@@ -122,16 +138,16 @@ function injectStyles() {
(a trade line, a buyback receipt) grows its track past the viewport and
clips off-screen at 320px. Let every track shrink to its box instead. */
.tk-grid > *, .tk-card, .tk-trade, .tk-trade > *, .tk-bb-run, .tk-bb-run > *, .tk-bb-head > * { min-width:0; }
- .tk-card { background:#111116; border:1px solid #1d1d24; border-radius:14px; padding:18px; }
- .tk-card h2 { font-size:12px; text-transform:uppercase; letter-spacing:0.06em; color:#7d7d86; margin:0 0 12px; }
+ .tk-card { background:var(--tk-surface); border:1px solid var(--tk-border); border-radius:14px; padding:18px; }
+ .tk-card h2 { font-size:12px; text-transform:uppercase; letter-spacing:0.06em; color:var(--tk-dim); margin:0 0 12px; }
.tk-buy { display:flex; gap:10px; margin-top:16px; flex-wrap:wrap; }
- .tk-btn { appearance:none; border:1px solid #2a2a32; background:#1a1a20; color:#fff; border-radius:10px; padding:11px 18px; font-size:14px; font-weight:600; cursor:pointer; text-decoration:none; display:inline-flex; align-items:center; gap:8px; transition:background .15s,border-color .15s,transform .1s; }
- .tk-btn:hover { background:#23232b; border-color:#3a3a44; }
+ .tk-btn { appearance:none; border:1px solid var(--tk-border-hover); background:var(--tk-btn); color:var(--tk-text); border-radius:10px; padding:11px 18px; font-size:14px; font-weight:600; cursor:pointer; text-decoration:none; display:inline-flex; align-items:center; gap:8px; transition:background .15s,border-color .15s,transform .1s; }
+ .tk-btn:hover { background:var(--tk-btn-hover); border-color:var(--tk-border-hover); }
.tk-btn:active { transform:translateY(1px); }
.tk-btn.primary { background:linear-gradient(135deg,#fff,#cfcfd6); color:#000; border:none; }
.tk-btn.primary:hover { filter:brightness(0.95); }
- .tk-btn:focus-visible { outline:2px solid #7CC4FF; outline-offset:2px; }
- .tk-wrap a:focus-visible, .tk-ca:focus-visible { outline:2px solid #7CC4FF; outline-offset:2px; border-radius:6px; }
+ .tk-btn:focus-visible { outline:2px solid var(--tk-link); outline-offset:2px; }
+ .tk-wrap a:focus-visible, .tk-ca:focus-visible { outline:2px solid var(--tk-link); outline-offset:2px; border-radius:6px; }
.tk-tape { display:flex; flex-direction:column; gap:2px; max-height:430px; overflow-y:auto; }
.tk-trade { display:grid; grid-template-columns:54px 1fr auto; gap:8px; align-items:center; padding:8px 10px; border-radius:8px; font-size:13px; }
.tk-trade.buy { background:rgba(74,222,128,0.07); }
@@ -140,61 +156,69 @@ function injectStyles() {
@keyframes tkIn { from { opacity:0; transform:translateY(-6px); } to { opacity:1; transform:none; } }
.tk-side { font-weight:700; font-size:11px; text-transform:uppercase; letter-spacing:0.04em; }
.tk-side.buy { color:#4ade80; } .tk-side.sell { color:#f87171; }
- .tk-trader { font-family:ui-monospace,Menlo,monospace; color:#b8b8c0; text-decoration:none; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; display:block; }
- .tk-trader:hover { color:#fff; }
+ .tk-trader { font-family:ui-monospace,Menlo,monospace; color:var(--tk-text-2); text-decoration:none; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; display:block; }
+ .tk-trader:hover { color:var(--tk-strong); }
.tk-amt { font-family:ui-monospace,Menlo,monospace; text-align:right; }
- .tk-amt small { color:#7d7d86; }
- .tk-status { display:inline-flex; align-items:center; gap:6px; font-size:11.5px; color:#7d7d86; }
+ .tk-amt small { color:var(--tk-dim); }
+ .tk-status { display:inline-flex; align-items:center; gap:6px; font-size:11.5px; color:var(--tk-dim); }
.tk-dot { width:7px; height:7px; border-radius:50%; background:#4ade80; box-shadow:0 0 8px #4ade80; }
.tk-dot.off { background:#f87171; box-shadow:none; }
- .tk-empty { text-align:center; color:#7d7d86; font-size:13px; padding:40px 0; }
+ .tk-empty { text-align:center; color:var(--tk-dim); font-size:13px; padding:40px 0; }
.tk-stats-err { grid-column:1/-1; }
- .tk-skel { background:linear-gradient(90deg,#16161c,#1d1d24,#16161c); background-size:200% 100%; animation:tkSh 1.4s infinite; border-radius:10px; }
+ .tk-skel { background:linear-gradient(90deg,var(--tk-skel-a),var(--tk-skel-b),var(--tk-skel-a)); background-size:200% 100%; animation:tkSh 1.4s infinite; border-radius:10px; }
@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; }
+ .tk-foot a { color:var(--tk-muted); text-decoration:none; } .tk-foot a:hover { color:var(--tk-strong); }
.tk-bb { margin-top:18px; }
.tk-bb-commit { display:flex; align-items:baseline; gap:10px; flex-wrap:wrap; margin:0 0 8px; }
.tk-bb-commit b { font-size:30px; line-height:1; font-weight:800; font-family:ui-monospace,Menlo,monospace; background:linear-gradient(90deg,#4ade80,#22d3ee); -webkit-background-clip:text; background-clip:text; -webkit-text-fill-color:transparent; }
- .tk-bb-commit em { font-style:normal; color:#d8d8e0; font-size:14px; font-weight:600; }
- .tk-bb-lead { color:#9a9aa3; font-size:13px; margin:0 0 14px; line-height:1.55; }
- .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-commit em { font-style:normal; color:var(--tk-text-2); font-size:14px; font-weight:600; }
+ .tk-bb-lead { color:var(--tk-muted); font-size:13px; margin:0 0 14px; line-height:1.55; }
+ .tk-bb-empty { color:var(--tk-text-2); font-size:14px; line-height:1.6; }
+ .tk-bb-empty strong { color:var(--tk-text); }
+ .tk-bb-empty span { display:block; color:var(--tk-dim); font-size:13px; margin-top:6px; }
.tk-bb-head { display:grid; grid-template-columns:repeat(4,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-k { font-size:11px; text-transform:uppercase; letter-spacing:0.06em; color:var(--tk-dim); margin-bottom:4px; }
.tk-bb-v { font-size:19px; font-weight:700; font-family:ui-monospace,Menlo,monospace; }
- .tk-bb-bar { height:8px; border-radius:6px; background:#1d1d24; overflow:hidden; }
+ .tk-bb-bar { height:8px; border-radius:6px; background:var(--tk-border); 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; }
- .tk-bb-runs-h { font-size:11px; text-transform:uppercase; letter-spacing:0.06em; color:#7d7d86; margin:18px 0 8px; }
+ .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:var(--tk-dim); }
+ .tk-bb-foot a { color:var(--tk-link); text-decoration:none; } .tk-bb-foot a:hover { text-decoration:underline; }
+ .tk-bb-runs-h { font-size:11px; text-transform:uppercase; letter-spacing:0.06em; color:var(--tk-dim); margin:18px 0 8px; }
.tk-bb-runs { display:flex; flex-direction:column; gap:3px; }
- .tk-bb-run { display:grid; grid-template-columns:auto 1fr auto; gap:10px; align-items:center; padding:8px 10px; border-radius:8px; font-size:12.5px; background:#0e0e12; border:1px solid #16161c; }
- .tk-bb-run:hover { background:#15151b; border-color:#23232b; }
- .tk-bb-run-date { color:#7d7d86; font-family:ui-monospace,Menlo,monospace; }
- .tk-bb-run-amt { font-family:ui-monospace,Menlo,monospace; color:#d8d8e0; }
+ .tk-bb-run { display:grid; grid-template-columns:auto 1fr auto; gap:10px; align-items:center; padding:8px 10px; border-radius:8px; font-size:12.5px; background:var(--tk-inset); border:1px solid var(--tk-inset-border); }
+ .tk-bb-run:hover { background:var(--tk-inset-hover); border-color:var(--tk-btn-hover); }
+ .tk-bb-run-date { color:var(--tk-dim); font-family:ui-monospace,Menlo,monospace; }
+ .tk-bb-run-amt { font-family:ui-monospace,Menlo,monospace; color:var(--tk-text-2); }
.tk-bb-run-amt b { color:#4ade80; font-weight:700; }
- .tk-bb-run a { color:#7CC4FF; text-decoration:none; justify-self:end; white-space:nowrap; }
+ .tk-bb-run a { color:var(--tk-link); text-decoration:none; justify-self:end; white-space:nowrap; }
.tk-bb-run a:hover { text-decoration:underline; }
- .tk-bb-lead a { color:#7CC4FF; text-decoration:none; } .tk-bb-lead a:hover { text-decoration:underline; }
+ .tk-bb-lead a { color:var(--tk-link); text-decoration:none; } .tk-bb-lead a:hover { text-decoration:underline; }
.tk-dt-cta { margin:0 0 4px; }
.tk-chart { margin-bottom:18px; }
.tk-chart-h { display:flex; align-items:center; justify-content:space-between; gap:12px; }
- .tk-chart-h a { color:#7CC4FF; text-decoration:none; text-transform:none; letter-spacing:0; font-size:12.5px; } .tk-chart-h a:hover { text-decoration:underline; }
- .tk-chart-host { position:relative; height:clamp(340px,52vh,520px); border-radius:10px; overflow:hidden; background:#0e0e12; }
+ .tk-chart-h a { color:var(--tk-link); text-decoration:none; text-transform:none; letter-spacing:0; font-size:12.5px; } .tk-chart-h a:hover { text-decoration:underline; }
+ .tk-chart-host { position:relative; height:clamp(340px,52vh,520px); border-radius:10px; overflow:hidden; background:var(--tk-inset); }
.tk-chart-skel { position:absolute; inset:0; transition:opacity .3s ease; }
.tk-chart-frame { position:absolute; inset:0; width:100%; height:100%; border:0; opacity:0; transition:opacity .3s ease; }
.tk-chart-host.ready .tk-chart-frame { opacity:1; }
.tk-chart-host.ready .tk-chart-skel { opacity:0; }
- .tk-chart-state { height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:10px; text-align:center; padding:20px; color:#9a9aa3; font-size:13.5px; line-height:1.55; }
+ .tk-chart-state { height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:10px; text-align:center; padding:20px; color:var(--tk-muted); font-size:13.5px; line-height:1.55; }
.tk-chart-state p { margin:0; max-width:420px; }
- .tk-chart-state a { color:#7CC4FF; text-decoration:none; } .tk-chart-state a:hover { text-decoration:underline; }
+ .tk-chart-state a { color:var(--tk-link); text-decoration:none; } .tk-chart-state a:hover { text-decoration:underline; }
+ .tk-chg { font-size:12px; margin-top:3px; }
+ .tk-chg.up { color:#4ade80; } .tk-chg.down { color:#f87171; }
+ :root[data-theme="light"] .tk-btn.primary { background:linear-gradient(135deg,#1a1a20,#34343d); color:#fff; }
+ :root[data-theme="light"] .tk-why-d b, :root[data-theme="light"] .tk-side.buy, :root[data-theme="light"] .tk-bb-run-amt b, :root[data-theme="light"] .tk-chg.up { color:#15803d; }
+ :root[data-theme="light"] .tk-side.sell, :root[data-theme="light"] .tk-chg.down { color:#b91c1c; }
+ :root[data-theme="light"] .tk-trade.buy { background:rgba(22,163,74,0.08); }
+ :root[data-theme="light"] .tk-trade.sell { background:rgba(220,38,38,0.07); }
+ :root[data-theme="light"] .tk-bb-commit b { background:linear-gradient(90deg,#15803d,#0e7490); -webkit-background-clip:text; background-clip:text; }
@media (max-width:560px){ .tk-bb-head { grid-template-columns:repeat(2,1fr); gap:8px; } }
@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; } .tk-chart-skel, .tk-chart-frame { transition:none; } }
`;
const el = document.createElement('style');
- el.textContent = css;
+ el.textContent = css + FEE_FLOW_CSS;
document.head.appendChild(el);
}
@@ -211,7 +235,7 @@ function renderHeaderStats(token) {
return `<div class="tk-stat">
<div class="tk-stat-l">${esc(s.l)}</div>
<div class="tk-stat-v">${s.v}</div>
- ${s.sub ? `<div style="font-size:12px;margin-top:3px;color:${up ? '#4ade80' : '#f87171'}">${s.sub} 24h</div>` : ''}
+ ${s.sub ? `<div class="tk-chg ${up ? 'up' : 'down'}">${s.sub} 24h</div>` : ''}
</div>`;
}).join('');
}
@@ -564,6 +588,7 @@ function boot() {
</div>
</div>
</div>
+ <section class="tk-card tk-ff" id="tk-fee-flow" data-fee-flow aria-label="Where every $100 goes"></section>
<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>
@@ -642,6 +667,10 @@ function boot() {
// Programmatic buyback panel + live commitment % in the "why hold" pillars —
// both from one protocol stats fetch.
+ // Where every $100 goes: live split policies + the two public wallets. The
+ // buyback summary under the wallets reuses the stats fetch below.
+ const feeFlow = mountFeeFlow(wrap.querySelector('[data-fee-flow]'), { copyText });
+
const bbEl = wrap.querySelector('[data-buyback]');
const whyEl = wrap.querySelector('[data-why]');
const loadBuyback = () => {
@@ -650,6 +679,7 @@ function boot() {
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(`stats ${r.status}`))))
.then((d) => {
bbEl.innerHTML = renderBuyback(d.buyback);
+ feeFlow.setBuyback(d.buyback);
if (d.buyback?.commit_pct != null) whyEl.innerHTML = renderWhyHold(d.buyback.commit_pct);
})
.catch(() => { bbEl.innerHTML = renderBuyback(null); });
diff --git a/tests/three-token-fee-flow.test.js b/tests/three-token-fee-flow.test.js
new file mode 100644
index 000000000..cde7af210
--- /dev/null
+++ b/tests/three-token-fee-flow.test.js
@@ -0,0 +1,172 @@
+// "Where every $100 goes" on /three-token: the breakdown renders every live
+// split policy with numbers taken only from the config, a policy added to
+// SPLIT_POLICIES appears with no page change, no split figure is typed into
+// the page code, and the wallet snapshot never turns a failed read into a zero.
+
+import { readFileSync } from 'node:fs';
+import { PublicKey } from '@solana/web3.js';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+vi.mock('../api/_lib/cache.js', () => ({
+ cacheGet: async () => null,
+ cacheSet: async () => {},
+}));
+
+const rpcState = { fail: false, balances: {} };
+vi.mock('../api/_lib/solana/rpc-fallback.js', () => ({
+ rpcFallbackFromEnv: () => ({
+ withFallback: async (fn) => {
+ if (rpcState.fail) throw new Error('all rpc lanes exhausted');
+ return fn({
+ getParsedTokenAccountsByOwner: async (owner, { mint }) => {
+ const entry = rpcState.balances[`${owner.toBase58()}:${mint.toBase58()}`];
+ return {
+ value: entry
+ ? [{ account: { data: { parsed: { info: { tokenAmount: entry } } } } }]
+ : [],
+ };
+ },
+ });
+ },
+ }),
+}));
+
+const { publicConfig, SPLIT_POLICIES, TOKEN_MINT } = await import('../api/_lib/token/config.js');
+const { SOLANA_USDC_MINT } = await import('../api/payments/_config.js');
+const { publicWalletBalances } = await import('../api/_lib/token/wallet-balances.js');
+const {
+ renderPolicies,
+ renderWallets,
+ renderBuybackSummary,
+ orderedPolicies,
+ policyLabel,
+ dollarsOfHundred,
+} = await import('../src/three-token-fee-flow.js');
+
+// A synthetic, keyless owner address (32 bytes of 7s), not anyone's wallet.
+const SYNTHETIC_WALLET = new PublicKey(new Uint8Array(32).fill(7)).toBase58();
+
+const policyKeys = (html) => [...html.matchAll(/data-policy="([^"]+)"/g)].map((m) => m[1]);
+
+describe('fee flow breakdown', () => {
+ it('renders every policy the public config publishes, with amounts derived from bps', () => {
+ const cfg = publicConfig();
+ const html = renderPolicies(cfg);
+ expect(policyKeys(html).sort()).toEqual(Object.keys(SPLIT_POLICIES).sort());
+ for (const [key, legs] of Object.entries(cfg.split_policies)) {
+ const row = html.slice(html.indexOf(`data-policy="${key}"`));
+ for (const leg of legs) {
+ const dollars = `$${dollarsOfHundred(leg.bps).toFixed(2)}`;
+ expect(row).toContain(dollars);
+ }
+ }
+ });
+
+ it('shows a newly added policy with no page change, labelled from its key', () => {
+ const cfg = publicConfig();
+ const extended = {
+ ...cfg,
+ split_policies: {
+ ...cfg.split_policies,
+ holder_quest_reward: [
+ { role: 'treasury', bps: 6250 },
+ { role: 'rewards', bps: 3750 },
+ ],
+ },
+ };
+ const html = renderPolicies(extended);
+ expect(policyKeys(html)).toContain('holder_quest_reward');
+ expect(policyLabel('holder_quest_reward')).toBe('Holder quest reward');
+ expect(html).toContain('Of every $100 paid for holder quest reward');
+ expect(html).toContain('$62.50');
+ expect(html).toContain('$37.50');
+ // Known policies keep their curated order ahead of the new one.
+ expect(orderedPolicies(extended).at(-1).key).toBe('holder_quest_reward');
+ });
+
+ it('gives screen readers the numbers as text, not only the bar shapes', () => {
+ const html = renderPolicies(publicConfig());
+ const labels = [...html.matchAll(/role="img" aria-label="([^"]+)"/g)].map((m) => m[1]);
+ expect(labels).toHaveLength(Object.keys(SPLIT_POLICIES).length);
+ for (const l of labels) expect(l).toMatch(/^Of every \$100: \$\d/);
+ });
+
+ it('never states a platform burn', () => {
+ const html = renderPolicies(publicConfig());
+ expect(html.toLowerCase()).not.toContain('burn');
+ });
+
+ it('types no split figure from SPLIT_POLICIES into the page code', () => {
+ const bps = new Set(Object.values(SPLIT_POLICIES).flat().map((l) => l.bps));
+ const feeFlow = readFileSync('src/three-token-fee-flow.js', 'utf8');
+ const page = readFileSync('src/three-token-page.js', 'utf8');
+ for (const b of bps) {
+ const pct = b / 100;
+ // The module that renders the splits carries no bps figure at all.
+ expect(feeFlow).not.toMatch(new RegExp(`(?<![\\w.])${b}(?![\\w.])`));
+ // Neither file states a split as a typed percentage or dollar figure.
+ for (const src of [feeFlow, page]) {
+ expect(src).not.toMatch(new RegExp(`(?<![\\w.$:(])${pct}%`)); // CSS lengths such as radius:50% are not splits
+ expect(src).not.toMatch(new RegExp(`\\$${pct}\\.00`));
+ }
+ }
+ });
+});
+
+describe('fee flow wallets', () => {
+ const saved = {};
+ beforeEach(() => {
+ for (const k of ['THREE_TREASURY_WALLET', 'THREE_REWARDS_WALLET']) saved[k] = process.env[k];
+ rpcState.fail = false;
+ rpcState.balances = {};
+ });
+ afterEach(() => {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ });
+
+ it('lists unset wallets as not yet published instead of hiding them', async () => {
+ delete process.env.THREE_TREASURY_WALLET;
+ delete process.env.THREE_REWARDS_WALLET;
+ const snap = await publicWalletBalances();
+ expect(snap.wallets.map((w) => [w.role, w.configured, w.balances])).toEqual([
+ ['treasury', false, null],
+ ['rewards', false, null],
+ ]);
+ const html = renderWallets(snap);
+ expect(html.match(/Not yet published/g)).toHaveLength(2);
+ });
+
+ it('reads real balances for a configured wallet and a real zero for an empty one', async () => {
+ const treasury = SYNTHETIC_WALLET;
+ process.env.THREE_TREASURY_WALLET = treasury;
+ delete process.env.THREE_REWARDS_WALLET;
+ rpcState.balances[`${treasury}:${TOKEN_MINT}`] = { amount: '1234500000', decimals: 6 };
+ const snap = await publicWalletBalances();
+ const t = snap.wallets.find((w) => w.role === 'treasury');
+ expect(t.configured).toBe(true);
+ expect(t.balances.three).toMatchObject({ ok: true, amount: 1234.5, atomics: '1234500000' });
+ expect(t.balances.usdc).toMatchObject({ ok: true, amount: 0 });
+ expect(SOLANA_USDC_MINT).toBeTruthy();
+ const html = renderWallets(snap);
+ expect(html).toContain(`https://solscan.io/account/${treasury}`);
+ expect(html).toContain(`data-ff-copy="${treasury}"`);
+ });
+
+ it('reports an RPC failure as unavailable, never as a zero balance', async () => {
+ process.env.THREE_TREASURY_WALLET = SYNTHETIC_WALLET;
+ rpcState.fail = true;
+ const snap = await publicWalletBalances();
+ const t = snap.wallets.find((w) => w.role === 'treasury');
+ expect(t.balances.three).toMatchObject({ ok: false, amount: null });
+ expect(renderWallets(snap)).toContain('Balance unavailable');
+ });
+
+ it('summarizes the buyback history the page already loads', () => {
+ expect(renderBuybackSummary(null)).toBe('');
+ expect(renderBuybackSummary({ runs: 0 })).toContain('No treasury buyback has run yet');
+ expect(renderBuybackSummary({ runs: 3, three_bought: 2500000 })).toContain('3 buybacks so far, 2.50M $THREE');
+ });
+});