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.

Add $THREE pay-per-use rail and referral capture/claim dashboard

nirholas12ae370947d9
diff --git a/api/three/[action].js b/api/three/[action].js
new file mode 100644
index 000000000..2b67b0218
--- /dev/null
+++ b/api/three/[action].js
@@ -0,0 +1,106 @@
+// $THREE pay-per-use rail — the canonical HTTP surface every paid compute action
+// charges through. One endpoint, one currency.
+//
+// GET /api/three/catalog — public price list (display)
+// POST /api/three/charge — issue a $THREE quote, or settle a paid one (auth)
+//
+// The charge → settle handshake reuses api/_lib/pricing/charge-three.js, which
+// wraps the token rail (quote → on-chain verify → settle). No action burns; every
+// spend routes to treasury + the holder-rewards pool per its split policy.
+//
+// Lever-1 surfaces (Forge standard/high, voice clone, MCP-3D tools, Granite,
+// selfie→avatar) are all catalog actions, so they charge through this one path.
+// The always-free lanes (NVIDIA draft, free LLM chat, discovery, social) are on
+// the free-forever allowlist and never reach here.
+
+import { z } from 'zod';
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import { publicCatalog } from '../_lib/pricing/catalog.js';
+import { requireThreePayment } from '../_lib/pricing/charge-three.js';
+import { holderDiscountBps } from '../_lib/three-tier.js';
+
+const SOLANA_ADDRESS = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'invalid Solana address');
+
+// ── GET /api/three/catalog ─────────────────────────────────────────────────────
+
+async function handleCatalog(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.tokenPriceIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+ return json(res, 200, { actions: publicCatalog() });
+}
+
+// ── POST /api/three/charge ───────────────────────────────────────────────────────
+
+const chargeSchema = z.object({
+ action: z.string().min(1).max(64),
+ // Per-call price for variable actions (auctions, marketplace listings). Ignored
+ // for fixed-price catalog actions.
+ usd: z.number().positive().optional(),
+ seller_wallet: SOLANA_ADDRESS.optional(),
+ ref_type: z.string().max(64).optional(),
+ ref_id: z.string().max(128).optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ // Present together to SETTLE a previously-issued quote.
+ quote_token: z.string().min(40).optional(),
+ tx_signature: z.string().min(80).max(100).optional(),
+ payer_wallet: SOLANA_ADDRESS.optional(),
+});
+
+async function handleCharge(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const body = parse(chargeSchema, await readJson(req));
+ const settling = Boolean(body.quote_token && body.tx_signature);
+
+ // Reuse the token-rail limiters: settle is the money-moving, on-chain-verifying
+ // call (tight, fail-closed); charge issues a signed quote (slightly looser).
+ const rl = settling ? await limits.tokenSettle(user.id) : await limits.tokenQuote(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ // Holder-tier fee discount (Lever 2): higher $THREE holders pay less on
+ // fixed-price compute. Resolved from the user's on-chain balance; degrades to
+ // no discount (full price) if the balance can't be priced — never blocks a charge.
+ const discountBps = settling ? 0 : await holderDiscountBps(user);
+
+ const result = await requireThreePayment({
+ action: body.action,
+ user,
+ usd: body.usd,
+ discountBps,
+ sellerWallet: body.seller_wallet ?? null,
+ refType: body.ref_type ?? null,
+ refId: body.ref_id ?? null,
+ network: body.network,
+ settle: settling
+ ? {
+ quoteToken: body.quote_token,
+ txSignature: body.tx_signature,
+ payerWallet: body.payer_wallet ?? user.wallet_address ?? null,
+ }
+ : null,
+ });
+
+ return json(res, result.paid ? 200 : 201, result);
+}
+
+// ── dispatcher ────────────────────────────────────────────────────────────────────
+
+const DISPATCH = {
+ catalog: handleCatalog,
+ charge: handleCharge,
+};
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();
+ const fn = DISPATCH[action];
+ if (!fn) return error(res, 404, 'not_found', `unknown three action: ${action}`);
+ return fn(req, res);
+});
diff --git a/pages/avatar-studio.html b/pages/avatar-studio.html
index 2a8c4b266..1671a714b 100644
--- a/pages/avatar-studio.html
+++ b/pages/avatar-studio.html
@@ -962,6 +962,7 @@
<div class="as-chips" id="as-chips" aria-label="Selected items"></div>
<div class="as-panel" id="as-panel" role="tabpanel" tabindex="0"></div>
<div class="as-status" id="as-status">Choose a style below to get started.</div>
+ <avatar-actions id="as-actions" mode="wallet" style="display:none;margin-top:12px"></avatar-actions>
<a href="/pricing" class="upgrade-banner" style="margin:12px 16px;text-decoration:none;">
<div class="upgrade-banner-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg></div>
<div class="upgrade-banner-text">
@@ -972,6 +973,7 @@
</a>
</aside>
</main>
+ <script src="/avatar-actions.js" type="module"></script>
<script src="/src/avatar-studio.js" type="module"></script>
<script src="/brand.js" defer></script>
</body>
diff --git a/pages/dashboard-next/referrals.html b/pages/dashboard-next/referrals.html
new file mode 100644
index 000000000..fa36e455f
--- /dev/null
+++ b/pages/dashboard-next/referrals.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Referrals · Dashboard · three.ws</title>
+ <meta name="robots" content="noindex" />
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/dashboard-next/shell.css" />
+ </head>
+ <body>
+ <script type="module" src="/src/dashboard-next/pages/referrals.js"></script>
+ </body>
+</html>
diff --git a/public/avatar-actions.js b/public/avatar-actions.js
index 7e0c455bb..b8d598250 100644
--- a/public/avatar-actions.js
+++ b/public/avatar-actions.js
@@ -171,9 +171,15 @@ class AvatarActions extends HTMLElement {
? `<span class="forks">⑂ ${a.fork_count} ${a.fork_count === 1 ? 'fork' : 'forks'}</span>`
: '';
+ // mode: "full" (default) shows wallet to owners + fork to others;
+ // "wallet" shows only the wallet panel; "fork" shows only the save/fork
+ // affordance (use on surfaces that already manage the wallet elsewhere).
+ const mode = this.getAttribute('mode') || 'full';
let body = '';
if (this.isOwner) {
- body = this._walletBlock();
+ body = mode === 'fork' ? '' : this._walletBlock();
+ } else if (mode === 'wallet') {
+ body = '';
} else if (this._me) {
body = `<button class="primary" data-act="fork" title="Save a copy to your own avatars">
⑂ Save to my avatars</button>
@@ -182,6 +188,13 @@ class AvatarActions extends HTMLElement {
body = `<a class="manage" href="/login.html?next=${encodeURIComponent(location.pathname + location.search)}">Sign in to save this avatar →</a>`;
}
+ // Nothing to show for this viewer/mode combo — stay invisible rather than
+ // render an empty card.
+ if (!body && !lineage && !forks) {
+ this.shadowRoot.innerHTML = '';
+ return;
+ }
+
this.shadowRoot.innerHTML = `${css}
<div class="card">
${lineage || forks ? `<div class="row spread">${lineage}${forks}</div>` : ''}
diff --git a/public/login.html b/public/login.html
index 8bb2fad3f..16a1bbf2c 100644
--- a/public/login.html
+++ b/public/login.html
@@ -2,6 +2,7 @@
<html lang="en">
<head>
<script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <script src="/referral-capture.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Sign in · three.ws</title>
diff --git a/public/referral-capture.js b/public/referral-capture.js
new file mode 100644
index 000000000..0d214467f
--- /dev/null
+++ b/public/referral-capture.js
@@ -0,0 +1,47 @@
+/* three.ws — referral capture (zero-dep, static).
+ *
+ * Loaded on the public auth pages (/login, /register). Reads a `?ref=CODE`
+ * query param, validates it against the referral-code alphabet, and parks it
+ * in localStorage so the dashboard can attribute the referral once the user
+ * has a session (see src/dashboard-next/referral-claim.js).
+ *
+ * Captured here rather than threaded through every auth handshake (email,
+ * Privy, SIWS, SIWE) so a single replay covers all of them.
+ */
+(function () {
+ var KEY = 'tw:ref';
+ var CODE_RE = /^[A-Z2-9]{4,20}$/;
+ // A captured code older than this is stale — drop it rather than attribute a
+ // signup to a link the user clicked weeks ago.
+ var MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
+
+ function readParam() {
+ try {
+ var params = new URLSearchParams(window.location.search);
+ var raw = params.get('ref') || params.get('r');
+ if (!raw) return null;
+ var code = raw.trim().toUpperCase();
+ return CODE_RE.test(code) ? code : null;
+ } catch (e) {
+ return null;
+ }
+ }
+
+ try {
+ var code = readParam();
+ if (code) {
+ localStorage.setItem(KEY, JSON.stringify({ code: code, ts: Date.now() }));
+ } else {
+ // Expire a stale capture so it never attributes a much later signup.
+ var existing = localStorage.getItem(KEY);
+ if (existing) {
+ var parsed = JSON.parse(existing);
+ if (!parsed || !parsed.ts || Date.now() - parsed.ts > MAX_AGE_MS) {
+ localStorage.removeItem(KEY);
+ }
+ }
+ }
+ } catch (e) {
+ /* private mode / disabled storage — referral capture is best-effort */
+ }
+})();
diff --git a/public/register.html b/public/register.html
index 2d3ec90a9..45c0c01a6 100644
--- a/public/register.html
+++ b/public/register.html
@@ -2,6 +2,7 @@
<html lang="en">
<head>
<script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <script src="/referral-capture.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Create account · three.ws</title>
diff --git a/src/avatar-studio.js b/src/avatar-studio.js
index df1e77ff3..a800ee001 100644
--- a/src/avatar-studio.js
+++ b/src/avatar-studio.js
@@ -153,6 +153,8 @@ async function init() {
if (titleEl) titleEl.textContent = 'Edit Avatar';
const backEl = $('as-back');
if (backEl) backEl.href = `/avatars/${encodeURIComponent(editAvatarId)}`;
+ // Editing an existing avatar → surface its agent-wallet panel.
+ mountAvatarWallet(editAvatar);
} else {
// Offer to restore a saved draft (only in create mode, not edit)
maybeSuggestDraft();
@@ -195,6 +197,15 @@ async function fetchEditAvatar(id) {
return avatar;
}
+// Surface the avatar's agent-wallet panel (create / manage) in the studio rail.
+function mountAvatarWallet(avatar) {
+ const el = $('as-actions');
+ if (!el || !avatar?.id) return;
+ el.style.display = 'block';
+ if (customElements.get('avatar-actions')) el.avatar = avatar;
+ else el.setAttribute('avatar-id', avatar.id);
+}
+
// ── Draft autosave ───────────────────────────────────────────────────
let _draftTimer = null;
diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.js
index 1c1f95d46..ca4db9c64 100644
--- a/src/dashboard-next/nav.js
+++ b/src/dashboard-next/nav.js
@@ -50,6 +50,7 @@ export const NAV = [
// ── Account ─────────────────────────────────────────────────────────
{ path: '/dashboard/account', label: 'Account', icon: 'user', group: 'Account', tags: ['wallets', 'sns', 'delegation', 'profile', 'action log', 'provider keys'] },
+ { path: '/dashboard/referrals', label: 'Referrals', icon: 'gift', group: 'Account', tags: ['referral', 'invite', 'membership', 'card', 'refer a friend', 'share', 'rewards', 'position', 'score'] },
{ path: '/dashboard/wallet-grinder', label: 'Wallet Grinder', icon: 'sparkle', group: 'Account', tags: ['vanity', 'grind', 'keypair', 'wallet', 'solana', 'evm', 'ethereum', 'base', 'polygon', 'address', 'prefix', 'suffix'] },
{ path: '/dashboard/settings', label: 'Settings', icon: 'settings', group: 'Account', tags: ['sessions', 'notifications', 'preferences', 'storage', 'llm usage', 'vanity'] },
{ path: '/onchain', label: 'On-chain (ERC-8004)', icon: 'chain', group: 'Account', tags: ['erc8004', 'registry', 'onchain', 'identity'], external: true },
@@ -87,6 +88,7 @@ export const ICONS = {
devhub: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="16" height="12" rx="2"/><path d="M6 7l-2 2.5L6 12M14 7l2 2.5L14 12M9 13l2-8"/></svg>',
landscape: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="8" r="2"/><circle cx="14" cy="6" r="2"/><circle cx="10" cy="14" r="2"/><path d="M8 8l2 5M12 7l-2 6"/><path d="M3 3h14v14H3z" stroke-dasharray="2 2" opacity="0.3"/></svg>',
bounty: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="7.5"/><path d="M10 6v8M7 8l3-2 3 2M7 12l3 2 3-2"/></svg>',
+ gift: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="8" width="14" height="9" rx="1.5"/><path d="M3 11h14M10 8v9"/><path d="M10 8S8.5 4.5 6.5 4.5a2 2 0 000 4H10zM10 8s1.5-3.5 3.5-3.5a2 2 0 010 4H10z"/></svg>',
};
/** Resolve the route for the current pathname (exact match wins; falls back to startsWith). */
diff --git a/src/dashboard-next/referral-claim.js b/src/dashboard-next/referral-claim.js
new file mode 100644
index 000000000..00c0f848a
--- /dev/null
+++ b/src/dashboard-next/referral-claim.js
@@ -0,0 +1,55 @@
+// dashboard-next — replay a captured referral once the user is signed in.
+//
+// public/referral-capture.js parks an inbound `?ref=CODE` in localStorage at
+// the auth door. This module replays it against /api/users/referral-claim the
+// first time the user reaches any authenticated dashboard page, then clears it
+// so it never fires twice. Fire-and-forget: a failed claim never blocks the UI.
+
+import { post } from './api.js';
+
+const KEY = 'tw:ref';
+const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
+
+function readPending() {
+ try {
+ const raw = localStorage.getItem(KEY);
+ if (!raw) return null;
+ const parsed = JSON.parse(raw);
+ if (!parsed?.code) return null;
+ if (!parsed.ts || Date.now() - parsed.ts > MAX_AGE_MS) {
+ localStorage.removeItem(KEY);
+ return null;
+ }
+ return parsed.code;
+ } catch {
+ return null;
+ }
+}
+
+function clearPending() {
+ try { localStorage.removeItem(KEY); } catch { /* ignore */ }
+}
+
+/**
+ * Attempt to attribute a captured referral. Resolves to the claim status
+ * string ('claimed' | 'already' | 'invalid' | 'expired') or null when there
+ * was nothing to claim. Safe to call on every page load — it no-ops without a
+ * pending code and clears the code on any definitive outcome.
+ *
+ * @returns {Promise<string|null>}
+ */
+export async function claimPendingReferral() {
+ const code = readPending();
+ if (!code) return null;
+ try {
+ const res = await post('/api/users/referral-claim', { code });
+ // Any definitive server outcome means we should stop retrying.
+ clearPending();
+ return res?.status || null;
+ } catch (err) {
+ // 401 = not signed in yet (page hadn't gated). Leave the code in place so
+ // a later, authenticated load can retry. Any other error is terminal.
+ if (err?.status && err.status !== 401) clearPending();
+ return null;
+ }
+}
diff --git a/src/dashboard-next/shell.js b/src/dashboard-next/shell.js
index 087882413..c7eea29bf 100644
--- a/src/dashboard-next/shell.js
+++ b/src/dashboard-next/shell.js
@@ -15,6 +15,7 @@ import { renderSidebar, mountSidebarBehavior, mountMobileNavBehavior } from './
import { renderTopbar, mountTopbarBehavior } from './components/topbar.js';
import { renderDrawer, mountDrawerBehavior } from './components/drawer.js';
import { mountPaletteBehavior } from './components/palette.js';
+import { claimPendingReferral } from './referral-claim.js';
/**
* Build the shell, mount its behaviour, and resolve to the <main> slot
@@ -62,6 +63,10 @@ export async function mountShell() {
mountPaletteBehavior();
mountDrawerPulse(shell);
+ // If the user arrived via a referral link, attribute it now that they have a
+ // session. No-ops without a pending code; never blocks the page.
+ claimPendingReferral().catch(() => {});
+
// Light-up touch — the sidebar item we land on gets a brief accent
// pulse so users see "you are here" without having to track the
// indicator bar. Tasteful, not festive.