Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add account tier endpoint, migration, and schema updates
nirholas119e7735a079
diff --git a/api/_lib/account-tier.js b/api/_lib/account-tier.jsnew file mode 100644index 000000000..f67b9e57b--- /dev/null+++ b/api/_lib/account-tier.js@@ -0,0 +1,203 @@+// Account tiers — a member's "mode" on three.ws.+//+// These are coarse membership modes shown on the dashboard membership card:+// the badge that says who you are on the platform. They are deliberately+// DISTINCT from the $THREE holder-VALUE ladder (api/_lib/three-tier.js:+// Member→Bronze→Silver→Gold→Genesis), which grades how much $THREE a wallet+// holds. A user can wear several modes at once, so a mode is really a badge;+// the highest-ranked active badge is the member's "primary" tier for display.+//+// Where each mode comes from (`source`):+// • default — 'user', everyone. The floor.+// • grant — assigned by an admin and stored on users.account_tier+// ('beta', 'pro', 'three-dimensional').+// • holder — derived live from on-chain $THREE; never stored. Holding any+// $THREE earns the badge and unlocks the holder-value ladder.+// • plan — derived from a paid subscription (users.plan in pro/team/+// enterprise). Granting 'pro' reaches the same badge without a+// plan, so both paths converge on one Pro badge.+//+// The resolver is a pure function over (user, { holder }) so it unit-tests+// without a wallet RPC; detectHolder() does the (fail-closed) on-chain read.++import { holderUsd } from './three-tier.js';++/**+ * The mode ladder, ordered low→high by `rank`. `rank` only decides which badge+ * is "primary" when a member wears several — it is not a spend threshold.+ */+export const ACCOUNT_TIERS = Object.freeze([+ Object.freeze({+ id: 'user',+ label: 'User',+ rank: 0,+ source: 'default',+ color: '#94a3b8',+ tagline: 'Free forever',+ description:+ 'Everyone on three.ws. Full free-forever access to create avatars and agents, discover, embed, and earn referral commission.',+ perks: Object.freeze([+ 'Create avatars & agents',+ 'Discover, embed & share',+ 'Earn 5% referral commission in USDC',+ ]),+ }),+ Object.freeze({+ id: 'beta',+ label: 'Beta',+ rank: 10,+ source: 'grant',+ color: '#38bdf8',+ tagline: 'Early access',+ description:+ 'Early-access program member. Try new surfaces before they ship and help shape what gets built next.',+ perks: Object.freeze([+ 'Early access to new features',+ 'Beta-only experiments',+ 'A direct line into the roadmap',+ ]),+ }),+ Object.freeze({+ id: 'pro',+ label: 'Pro',+ rank: 20,+ source: 'plan',+ color: '#f59e0b',+ tagline: 'Paid plan',+ description:+ 'On a paid plan. Higher limits and priority routing across the platform.',+ perks: Object.freeze([+ 'Higher storage & generation quotas',+ 'Priority MCP & render routing',+ 'Pro profile badge',+ ]),+ }),+ Object.freeze({+ id: 'holder',+ label: 'Holder',+ rank: 30,+ source: 'holder',+ color: '#a78bfa',+ tagline: 'Holds $THREE',+ description:+ 'Holds $THREE. Unlocks the hold-to-access ladder — fee discounts on compute, higher free quotas, and private/branded worlds. The more you hold, the higher your Bronze→Genesis tier.',+ perks: Object.freeze([+ 'Fee discounts on $THREE compute',+ 'Higher free generation quotas',+ 'Private & branded worlds',+ 'Holder profile badge',+ ]),+ }),+ Object.freeze({+ id: 'three-dimensional',+ label: 'Three Dimensional',+ rank: 40,+ source: 'grant',+ color: '#f472b6',+ tagline: 'Top tier',+ description:+ 'The top tier — founders, partners, and standout builders. Everything on the platform, unlocked, with a direct line to the team.',+ perks: Object.freeze([+ 'Everything in Pro & Holder',+ 'Founder profile badge',+ 'Direct line to the team',+ 'First dibs on rare names & drops',+ ]),+ }),+]);++const BY_ID = new Map(ACCOUNT_TIERS.map((t) => [t.id, t]));++/** The default mode every member starts with. */+export const DEFAULT_TIER_ID = 'user';++/** Modes an admin can grant on users.account_tier. Derived modes are excluded. */+export const GRANTABLE_TIER_IDS = Object.freeze(+ ACCOUNT_TIERS.filter((t) => t.source === 'grant' || t.id === 'pro').map((t) => t.id),+);++/** Look up a mode definition by id, or null. */+export function tierById(id) {+ return BY_ID.get(String(id || '')) || null;+}++/** True if `id` is a mode an admin is allowed to grant. */+export function isGrantableTier(id) {+ return GRANTABLE_TIER_IDS.includes(String(id || ''));+}++/**+ * Normalize a stored/admin-supplied grant to a valid grantable id, or null.+ * Empty string and the sentinel 'none' both clear the grant (→ null).+ */+export function normalizeTierGrant(input) {+ if (input == null) return null;+ const id = String(input).trim().toLowerCase();+ if (id === '' || id === 'none' || id === 'user') return null;+ return isGrantableTier(id) ? id : null;+}++/**+ * Read whether any of a set of wallets holds $THREE. Fail-closed: a wallet that+ * can't be read (RPC hiccup, non-Solana address) counts as 0, so a hiccup shows+ * "not a holder" rather than falsely awarding the badge. Returns the best+ * (largest) holding found across the wallets.+ *+ * @param {string[]} walletAddresses+ * @returns {Promise<{ isHolder: boolean, amount: number, usd: number }>}+ */+export async function detectHolder(walletAddresses = []) {+ const seen = new Set();+ let amount = 0;+ let usd = 0;+ for (const w of walletAddresses) {+ if (!w || seen.has(w)) continue;+ seen.add(w);+ const held = await holderUsd(w); // validates Solana addr + fails closed to 0+ if (held.amount > amount) amount = held.amount;+ if (held.usd > usd) usd = held.usd;+ }+ return { isHolder: amount > 0, amount, usd };+}++/**+ * Resolve a member's active modes from their record plus a (precomputed) holder+ * read. Pure — no I/O — so it tests without a wallet RPC.+ *+ * @param {{ account_tier?: string|null, plan?: string|null }} user+ * @param {{ holder?: { isHolder: boolean, amount: number, usd: number } }} [opts]+ * @returns {{+ * primary: object,+ * badges: object[],+ * granted: string|null,+ * holder: { isHolder: boolean, amount: number, usd: number },+ * plan: string,+ * next: object|null,+ * tiers: object[],+ * }}+ */+export function resolveAccountTier(user, { holder = { isHolder: false, amount: 0, usd: 0 } } = {}) {+ const active = new Map();+ const add = (id) => {+ const t = BY_ID.get(id);+ if (t) active.set(id, t);+ };++ add('user'); // floor — always present++ const granted = normalizeTierGrant(user?.account_tier);+ if (granted) add(granted);++ if (holder.isHolder) add('holder');++ const plan = String(user?.plan || 'free').toLowerCase();+ if (plan === 'pro' || plan === 'team' || plan === 'enterprise') add('pro');++ const badges = [...active.values()].sort((a, b) => a.rank - b.rank);+ const primary = badges[badges.length - 1];++ // The lowest mode the member hasn't reached yet — the natural "what's next".+ const next = ACCOUNT_TIERS.find((t) => t.rank > primary.rank && !active.has(t.id)) || null;++ return { primary, badges, granted, holder, plan, next, tiers: ACCOUNT_TIERS };+}diff --git a/api/_lib/migrations/2026-06-21-account-tier.sql b/api/_lib/migrations/2026-06-21-account-tier.sqlnew file mode 100644index 000000000..ac559ec94--- /dev/null+++ b/api/_lib/migrations/2026-06-21-account-tier.sql@@ -0,0 +1,25 @@+-- Migration: add users.account_tier — the granted account "mode" shown on a+-- member's card (api/_lib/account-tier.js). NULL = the default 'user' tier.+-- 'holder' is derived live from on-chain $THREE and is never stored here, so it+-- is intentionally absent from the CHECK list. Idempotent.+begin;++alter table users+ add column if not exists account_tier text;++-- Constrain to the admin-grantable modes. Added separately (not inline) so the+-- constraint lands on deployments where the column already exists from a prior+-- partial run. NOT VALID keeps the lock light; existing NULLs already satisfy it.+do $$+begin+ if not exists (+ select 1 from pg_constraint where conname = 'users_account_tier_check'+ ) then+ alter table users+ add constraint users_account_tier_check+ check (account_tier is null or account_tier in ('beta', 'pro', 'three-dimensional'))+ not valid;+ end if;+end $$;++commit;diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex c0f17a4ef..fb2270bda 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -40,6 +40,13 @@ alter table users add column if not exists website text;alter table users add column if not exists location text;alter table users add column if not exists banner_url text;+-- Account tier ("mode"): the coarse membership mode shown on a member's card.+-- NULL = the default 'user' tier. Granted modes are assigned by an admin+-- (api/admin/user/[id].js); 'holder' is derived live from on-chain $THREE and is+-- never stored here. See api/_lib/account-tier.js for the resolver + perk curve.+alter table users add column if not exists account_tier text+ check (account_tier is null or account_tier in ('beta', 'pro', 'three-dimensional'));+-- ── user_follows — the social graph ──────────────────────────────────────────-- A directed follow edge: follower_id follows following_id. Composite PK makes-- a follow idempotent (one edge per pair) and the toggle a single upsert/delete.diff --git a/api/users/me/tier.js b/api/users/me/tier.jsnew file mode 100644index 000000000..659b01f01--- /dev/null+++ b/api/users/me/tier.js@@ -0,0 +1,66 @@+// GET /api/users/me/tier — the signed-in member's account tier ("mode").+//+// Returns the member's primary mode plus every badge they wear (user, beta,+// pro, holder, three-dimensional), the next mode to aim for, and the full+// ladder so the dashboard can render the whole progression. 'holder' is derived+// live from on-chain $THREE across every Solana wallet the user has linked;+// every other mode comes from the user record (granted on account_tier, or+// derived from a paid plan). See api/_lib/account-tier.js.+//+// Auth: session cookie OR Bearer token. Powers the tier panel on+// /dashboard/referrals and the membership-card badge.++import { sql } from '../../_lib/db.js';+import { authenticateBearer, extractBearer, getSessionUser } from '../../_lib/auth.js';+import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';+import { clientIp, limits } from '../../_lib/rate-limit.js';+import { ACCOUNT_TIERS, detectHolder, resolveAccountTier } from '../../_lib/account-tier.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ const userId = session?.id || bearer?.userId;+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const [user] = await sql`+ select id, plan, account_tier, wallet_address, display_name, username+ from users+ where id = ${userId} and deleted_at is null+ limit 1+ `;+ if (!user) return error(res, 404, 'not_found', 'user not found');++ // Holder status is read across every Solana wallet the user controls — the+ // login wallet plus any linked ones — since they may hold $THREE in any of+ // them. detectHolder() fails closed, so an RPC hiccup never falsely awards+ // the badge.+ const linked = await sql`+ select address from user_wallets+ where user_id = ${userId} and chain_type = 'solana'+ `;+ const wallets = [user.wallet_address, ...linked.map((w) => w.address)].filter(Boolean);+ const holder = await detectHolder(wallets);++ const resolved = resolveAccountTier(user, { holder });++ return json(+ res,+ 200,+ {+ tier: resolved.primary,+ badges: resolved.badges,+ granted: resolved.granted,+ holder: resolved.holder,+ plan: resolved.plan,+ next: resolved.next,+ tiers: ACCOUNT_TIERS,+ },+ { 'cache-control': 'no-store' },+ );+});diff --git a/pages/profile.html b/pages/profile.htmlindex 9a3161806..67c375d71 100644--- a/pages/profile.html+++ b/pages/profile.html@@ -1100,6 +1100,31 @@color: rgba(255, 255, 255, 0.3);}+ /* ── Fork action on agent rows ───────────────────────────────────── */+ .up-card-row-wrap { display: flex; flex-direction: column; }+ .up-agent-fork-bar {+ display: flex;+ align-items: center;+ gap: 0.6rem;+ padding: 0.4rem 0.25rem 0;+ }+ .up-agent-fork-btn {+ display: inline-flex;+ align-items: center;+ gap: 0.3rem;+ background: transparent;+ border: 1px solid rgba(255, 255, 255, 0.14);+ color: rgba(255, 255, 255, 0.6);+ font-family: inherit;+ font-size: 0.6rem;+ padding: 0.22rem 0.55rem;+ border-radius: 999px;+ cursor: pointer;+ transition: border-color 0.15s, color 0.15s, background 0.15s;+ }+ .up-agent-fork-btn:hover { border-color: rgba(154, 140, 255, 0.5); color: #9a8cff; }+ .up-agent-fork-btn[disabled] { opacity: 0.5; cursor: default; }+/* ── Share menu ──────────────────────────────────────────────────── */.profile-share-wrap { position: relative; }.profile-share-menu {@@ -1873,6 +1898,49 @@}});+ // Fork an agent (clones it into the viewer's account via the+ // marketplace fork endpoint). Only published agents render the button.+ rootEl.addEventListener('click', async (e) => {+ const btn = e.target.closest('.up-agent-fork-btn');+ if (!btn) return;+ e.preventDefault();+ if (!viewer) {+ location.href = `/login?return=${encodeURIComponent('/u/' + user.username)}`;+ return;+ }+ const agentId = btn.dataset.agent;+ btn.disabled = true;+ const label = btn.querySelector('.up-agent-fork-label');+ const prev = label ? label.textContent : '';+ if (label) label.textContent = 'Forking…';+ try {+ const r = await apiFetch(+ `/api/marketplace/agents/${encodeURIComponent(agentId)}/fork`,+ { method: 'POST', credentials: 'include' },+ );+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error_description || j.error || 'Fork failed');+ const newId = j.data?.agent?.id || j.agent?.id || j.id;+ showToast(+ newId+ ? `Forked. <a href="/agent/${esc(newId)}">Open your copy →</a>`+ : 'Forked to your account.',+ 'ok',+ );+ const countEl = btn.parentElement?.querySelector('.up-fork-count');+ if (countEl) {+ const n = (parseInt(countEl.dataset.count || '0', 10) || 0) + 1;+ countEl.dataset.count = String(n);+ countEl.textContent = `${formatStat(n)} fork${n === 1 ? '' : 's'}`;+ }+ } catch (err) {+ showToast(esc(err.message || 'Could not fork.'), 'err');+ } finally {+ btn.disabled = false;+ if (label) label.textContent = prev || 'Fork';+ }+ });+// Lazy-load on-chain collectibles (NFTs, accessories, wallets). Kept// out of the main payload because the NFT providers are slow + billed;// the profile paints first, these fill in after.@@ -2339,18 +2407,36 @@meta.push(`<a href="https://warpcast.com/${attr(a.farcaster_fname)}" target="_blank" rel="noopener">/${esc(a.farcaster_fname)}</a>`,);+ // Forkable agents (published) expose a Fork button that clones the+ // agent into the viewer's account. The button sits OUTSIDE the card+ // link so it isn't a nested interactive element.+ const forkBar = a.is_published+ ? `<div class="up-agent-fork-bar">+ <button class="up-agent-fork-btn" type="button" data-agent="${attr(a.id)}" title="Fork this agent into your account">+ <svg width="11" height="11" viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M5 3.25a1.75 1.75 0 1 0-2.5 1.58v6.34A1.75 1.75 0 1 0 5 12.75v-1.06a3 3 0 0 1 3-3h.59a1.75 1.75 0 1 0 0-1.5H8a4.5 4.5 0 0 0-3 1.14V4.83A1.75 1.75 0 0 0 5 3.25"/></svg>+ <span class="up-agent-fork-label">Fork</span>+ </button>+ <span class="up-fork-count" data-count="${a.forks_count || 0}">${a.forks_count ? `${formatStat(a.forks_count)} fork${a.forks_count === 1 ? '' : 's'}` : ''}</span>+ ${a.is_fork ? '<span class="up-tag">forked</span>' : ''}+ </div>`+ : a.is_fork+ ? `<div class="up-agent-fork-bar"><span class="up-tag">forked</span></div>`+ : '';return `- <a class="up-card-row" href="/agent/${attr(a.id)}">- <div class="up-card-row-thumb">${thumb}</div>- <div class="up-card-row-body">- <div class="up-card-row-head">- <h3 class="up-card-row-name">${esc(a.name)}</h3>- ${onchainBadgeHTML(a, { link: false })}+ <div class="up-card-row-wrap">+ <a class="up-card-row" href="/agent/${attr(a.id)}">+ <div class="up-card-row-thumb">${thumb}</div>+ <div class="up-card-row-body">+ <div class="up-card-row-head">+ <h3 class="up-card-row-name">${esc(a.name)}</h3>+ ${onchainBadgeHTML(a, { link: false })}+ </div>+ ${a.description ? `<p class="up-card-row-desc">${esc(a.description)}</p>` : ''}+ ${meta.length ? `<div class="up-card-row-meta">${meta.map((m) => `<span>${m}</span>`).join('')}</div>` : ''}</div>- ${a.description ? `<p class="up-card-row-desc">${esc(a.description)}</p>` : ''}- ${meta.length ? `<div class="up-card-row-meta">${meta.map((m) => `<span>${m}</span>`).join('')}</div>` : ''}- </div>- </a>+ </a>+ ${forkBar}+ </div>`;}).join('');