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 pricing catalog + charge-three helper, referral attribution

nirholas27e47bb68193
diff --git a/.gitignore b/.gitignore
index 1520a0cb4..ccf1d046d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -239,3 +239,4 @@ scripts/.corr-*
/space_smugglers_club_house_-_dark_version.glb
/im-in-love-wit-a-stripper-fast.mp3
/alleyway.glb
+/tour.glb
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 8d6360a82..58a796bce 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -801,6 +801,14 @@ export const env = {
get THREE_TREASURY_WALLET() {
return opt('THREE_TREASURY_WALLET');
},
+ // Holder-rewards (reflections) wallet that receives the `rewards` share of every
+ // split. The rewards cron (api/cron/rewards-distribute.js) drains this pool back
+ // to holders pro-rata. REQUIRED in production — token/config.js fails closed
+ // (mirrors THREE_TREASURY_WALLET) rather than silently routing rewards to a
+ // placeholder. This is the platform's deflation-free alternative to burning.
+ get THREE_REWARDS_WALLET() {
+ return opt('THREE_REWARDS_WALLET');
+ },
// Burn address — defaults to the Solana incinerator, whose associated token
// account is unspendable (no key exists), so tokens transferred there are
// permanently removed from circulation. Verifiable as a plain destination.
diff --git a/api/_lib/pricing/catalog.js b/api/_lib/pricing/catalog.js
new file mode 100644
index 000000000..980902c4a
--- /dev/null
+++ b/api/_lib/pricing/catalog.js
@@ -0,0 +1,226 @@
+// Pricing catalog — the single source of truth for every paid action on the
+// platform, denominated in USD and settled in $THREE.
+//
+// WHY THIS EXISTS: before this file, prices lived scattered across endpoints
+// (forge-tiers.js, per-endpoint x402 challenges) and in two currencies. The
+// platform now charges in ONE currency, $THREE, through ONE rail
+// (api/_lib/token: quote → settle). Each action here names:
+// • usd — the retail price in USD (the quote unit; $THREE is the settle
+// unit, converted at the live price by the token rail). `null`
+// means the price is supplied per-call (auctions, variable mints).
+// • policy — a key of SPLIT_POLICIES (api/_lib/token/config.js). No policy
+// burns; every spend routes to treasury + holder rewards (+ seller
+// on a marketplace sale). See the economy-policy note there.
+// • category— for grouping in the /three economy page + dashboards.
+//
+// Forge tier prices are READ from forge-tiers.js (their existing source of truth)
+// rather than copied, so a tier price is defined in exactly one place.
+//
+// This module is pure (no network, no DB, no env beyond forge-tiers' constants)
+// so it is safe to import on the client for display and on the server for pricing.
+
+import { TIERS, priceUsdcForTier } from '../forge-tiers.js';
+
+// ── Split-policy aliases ───────────────────────────────────────────────────────
+// Names map 1:1 to SPLIT_POLICIES keys; aliased here so call sites read in
+// product terms and a policy rename is a one-line change.
+export const POLICY = Object.freeze({
+ CONSUMPTION: 'consumption', // pay-per-use compute → treasury + rewards
+ MARKETPLACE: 'marketplace_sale', // creator/seller sale → seller + treasury + rewards
+ SCARCITY: 'scarcity_mint', // limited drops / auctions / pay-to-mint → treasury + rewards
+});
+
+// Forge: draft is FREE (the NVIDIA NIM lane). Standard/High are paid in $THREE.
+// Prices come from forge-tiers.js so they're never duplicated.
+const FORGE_STANDARD_USD = Number(priceUsdcForTier(TIERS.standard)); // 0.15
+const FORGE_HIGH_USD = Number(priceUsdcForTier(TIERS.high)); // 0.50
+
+// ── The catalog ─────────────────────────────────────────────────────────────────
+// id → { label, category, policy, usd }. `usd: null` ⇒ price set per-call.
+export const CATALOG = Object.freeze({
+ // ── Generation & compute (real GPU / vendor cost) — POLICY.CONSUMPTION ──────
+ 'forge.standard': {
+ label: 'Forge — Standard generation',
+ category: 'generation',
+ policy: POLICY.CONSUMPTION,
+ usd: FORGE_STANDARD_USD,
+ },
+ 'forge.high': {
+ label: 'Forge — High generation (PBR)',
+ category: 'generation',
+ policy: POLICY.CONSUMPTION,
+ usd: FORGE_HIGH_USD,
+ },
+ 'mcp3d.text_to_3d': {
+ label: 'MCP-3D — text → 3D',
+ category: 'generation',
+ policy: POLICY.CONSUMPTION,
+ usd: FORGE_STANDARD_USD,
+ },
+ 'mcp3d.image_to_3d': {
+ label: 'MCP-3D — image → 3D',
+ category: 'generation',
+ policy: POLICY.CONSUMPTION,
+ usd: FORGE_STANDARD_USD,
+ },
+ 'mcp3d.auto_rig': {
+ label: 'MCP-3D — auto-rig',
+ category: 'generation',
+ policy: POLICY.CONSUMPTION,
+ usd: 0.1,
+ },
+ 'mcp3d.stylize': {
+ label: 'MCP-3D — stylize',
+ category: 'generation',
+ policy: POLICY.CONSUMPTION,
+ usd: 0.1,
+ },
+ 'mcp3d.retexture': {
+ label: 'MCP-3D — retexture',
+ category: 'generation',
+ policy: POLICY.CONSUMPTION,
+ usd: FORGE_STANDARD_USD,
+ },
+ 'voice.clone': {
+ label: 'Voice Lab — custom voice clone',
+ category: 'generation',
+ policy: POLICY.CONSUMPTION,
+ usd: 0.5,
+ },
+ 'selfie.reconstruct': {
+ label: 'Selfie → Avatar reconstruction',
+ category: 'generation',
+ policy: POLICY.CONSUMPTION,
+ usd: 0.25,
+ },
+ 'granite.forecast': {
+ label: 'Granite Oracle — forecast',
+ category: 'data',
+ policy: POLICY.CONSUMPTION,
+ usd: 0.05,
+ },
+ 'granite.vision': {
+ label: 'Granite Vision — image → identity',
+ category: 'data',
+ policy: POLICY.CONSUMPTION,
+ usd: 0.05,
+ },
+ 'granite.proof': {
+ label: 'Granite Proof — notarized forecast',
+ category: 'data',
+ policy: POLICY.CONSUMPTION,
+ usd: 0.1,
+ },
+
+ // ── Scarcity & collectibles — POLICY.SCARCITY (price often per-call) ─────────
+ 'name.auction': {
+ label: 'Rare *.threews.sol name',
+ category: 'scarcity',
+ policy: POLICY.SCARCITY,
+ usd: null, // set per name by rarity tier (see api/threews/auction.js)
+ },
+ 'collectible.mint': {
+ label: 'Limited-edition collectible mint',
+ category: 'scarcity',
+ policy: POLICY.SCARCITY,
+ usd: null, // set per drop
+ },
+ 'genesis.id': {
+ label: 'Genesis / numbered agent ID',
+ category: 'scarcity',
+ policy: POLICY.SCARCITY,
+ usd: null, // set per number rarity
+ },
+ 'land.plot': {
+ label: 'City land plot',
+ category: 'scarcity',
+ policy: POLICY.SCARCITY,
+ usd: null, // set per plot
+ },
+
+ // ── Creator marketplace — POLICY.MARKETPLACE (requires a seller wallet) ──────
+ 'skill.call': {
+ label: 'Skill call (creator-priced)',
+ category: 'marketplace',
+ policy: POLICY.MARKETPLACE,
+ usd: null,
+ },
+ 'animation.purchase': {
+ label: 'Animation purchase',
+ category: 'marketplace',
+ policy: POLICY.MARKETPLACE,
+ usd: null,
+ },
+ 'avatar.purchase': {
+ label: 'Avatar purchase',
+ category: 'marketplace',
+ policy: POLICY.MARKETPLACE,
+ usd: null,
+ },
+ 'asset.download': {
+ label: 'Asset download',
+ category: 'marketplace',
+ policy: POLICY.MARKETPLACE,
+ usd: null,
+ },
+ 'collectible.resale': {
+ label: 'Collectible resale (creator royalty)',
+ category: 'marketplace',
+ policy: POLICY.MARKETPLACE,
+ usd: null,
+ },
+});
+
+/** Look up a catalog entry. Throws a typed 404 if the action id is unknown. */
+export function catalogEntry(actionId) {
+ const e = CATALOG[actionId];
+ if (!e) {
+ const err = new Error(`unknown paid action: ${actionId}`);
+ err.status = 404;
+ err.code = 'unknown_action';
+ throw err;
+ }
+ return e;
+}
+
+/**
+ * Resolve the USD price for an action.
+ * @param {string} actionId a key of CATALOG
+ * @param {object} [opts]
+ * @param {number} [opts.usd] per-call price for variable actions (usd:null)
+ * @param {number} [opts.discountBps] holder-tier fee discount in bps (0–10000),
+ * applied only to fixed-price actions; ignored
+ * for marketplace/scarcity prices the seller set.
+ * @returns {{ actionId, label, category, policy, usd }}
+ */
+export function priceForAction(actionId, { usd: usdOverride, discountBps = 0 } = {}) {
+ const entry = catalogEntry(actionId);
+ let usd = entry.usd;
+ if (usd == null) {
+ // Variable-price action: the caller MUST supply the per-call price.
+ if (!(Number(usdOverride) > 0)) {
+ const err = new Error(`action ${actionId} requires a per-call usd price`);
+ err.status = 400;
+ err.code = 'price_required';
+ throw err;
+ }
+ usd = Number(usdOverride);
+ } else if (discountBps > 0) {
+ // Fixed-price action: apply the holder-tier discount. Discount never makes
+ // a paid action free — clamp to a 1-cent floor so the rail still settles.
+ const clamped = Math.max(0, Math.min(10000, Math.floor(discountBps)));
+ usd = Math.max(0.01, Math.round(usd * (10000 - clamped)) / 10000);
+ }
+ return { actionId, label: entry.label, category: entry.category, policy: entry.policy, usd };
+}
+
+/** Public, display-safe view of the catalog (fixed prices only; variable shown as null). */
+export function publicCatalog() {
+ return Object.entries(CATALOG).map(([id, e]) => ({
+ id,
+ label: e.label,
+ category: e.category,
+ policy: e.policy,
+ usd: e.usd,
+ }));
+}
diff --git a/api/_lib/pricing/charge-three.js b/api/_lib/pricing/charge-three.js
new file mode 100644
index 000000000..0d6448336
--- /dev/null
+++ b/api/_lib/pricing/charge-three.js
@@ -0,0 +1,165 @@
+// charge-three — the one helper every paid surface uses to charge in $THREE.
+//
+// It wraps the token rail (api/_lib/token: issueQuote → verifyAndSettlePayment)
+// so an endpoint never reimplements quoting or on-chain verification. Two phases:
+//
+// 1. CHARGE — no payment yet → price the action from the catalog, issue a
+// signed $THREE quote, return { paid:false, quote }. The client
+// pays it (src/token-pay.js builds the multi-leg tx) and retries
+// with the quote token + tx signature.
+// 2. SETTLE — payment present → verify the on-chain tx satisfies the quote,
+// record it, return { paid:true, payment }. Only then does the
+// endpoint do the real (costly) work.
+//
+// FREE-FOREVER GUARDRAIL: a hard allowlist of growth surfaces that must NEVER be
+// gated. requireThreePayment() refuses to gate any of them — a misconfiguration
+// that tries to charge for one throws a loud developer error rather than quietly
+// putting a paywall in front of the funnel.
+
+import { issueQuote, verifyAndSettlePayment } from '../token/index.js';
+import { catalogEntry, priceForAction, POLICY } from './catalog.js';
+
+// Surfaces that are free forever (the growth funnel). These are NOT catalog
+// actions — they have no price — but they're listed explicitly so the guardrail
+// is self-documenting and a stray charge attempt fails fast and obviously.
+export const FREE_SURFACES = Object.freeze(
+ new Set([
+ // Creation & configuration
+ 'agent.create',
+ 'agent.configure',
+ // Discovery
+ 'marketplace.browse',
+ 'gallery.browse',
+ 'launches.feed',
+ 'community.browse',
+ 'agent.lookup',
+ 'visualizer.view',
+ // Embedding
+ 'embed.web_component',
+ 'widget.studio',
+ 'examples.view',
+ // Social
+ 'friends',
+ 'presence',
+ 'dm',
+ 'chat.free', // the free LLM tier (Groq / free-first)
+ // Basic worlds (baseline access)
+ 'world.walk',
+ 'world.city',
+ 'world.communities',
+ // Free generation lane (NVIDIA NIM draft) — the always-free draft tier
+ 'forge.draft',
+ 'mcp3d.generate.free',
+ // Developer surfaces
+ 'docs',
+ 'tutorials',
+ 'sdk',
+ 'openapi',
+ 'status',
+ 'vanity.grinder',
+ // Common (non-rare) names mint free; only rare names are auctioned.
+ 'name.common',
+ ]),
+);
+
+/** True when the surface is on the free-forever allowlist. */
+export function isFreeSurface(surfaceId) {
+ return FREE_SURFACES.has(surfaceId);
+}
+
+/**
+ * Charge (or settle) a $THREE payment for a catalog action.
+ *
+ * @param {object} params
+ * @param {string} params.action a CATALOG key (api/_lib/pricing/catalog.js)
+ * @param {object|null} [params.user] the authenticated session user
+ * @param {number} [params.usd] per-call price for variable actions (usd:null in catalog)
+ * @param {number} [params.discountBps] holder-tier fee discount in bps (Lever 2 supplies this)
+ * @param {string|null} [params.sellerWallet] required for POLICY.MARKETPLACE actions
+ * @param {string|null} [params.refType] audit link (e.g. 'forge', 'skill')
+ * @param {string|null} [params.refId] audit id (e.g. the job / listing id)
+ * @param {'mainnet'|'devnet'} [params.network]
+ * @param {{ quoteToken?: string, txSignature?: string, payerWallet?: string }} [params.settle]
+ * when present with both fields, verifies + records the on-chain payment.
+ * @returns {Promise<
+ * | { paid: false, quote: object }
+ * | { paid: true, payment: object }
+ * >}
+ */
+export async function requireThreePayment({
+ action,
+ user = null,
+ usd,
+ discountBps = 0,
+ sellerWallet = null,
+ refType = null,
+ refId = null,
+ network = 'mainnet',
+ settle = null,
+}) {
+ // Guardrail: never gate a free-forever surface, even by mistake.
+ if (FREE_SURFACES.has(action)) {
+ throw Object.assign(
+ new Error(
+ `[charge-three] refusing to gate "${action}" — it is on the free-forever allowlist. ` +
+ 'Free surfaces must never require payment.',
+ ),
+ { status: 500, code: 'free_surface_gated' },
+ );
+ }
+
+ const entry = catalogEntry(action); // throws 404 unknown_action for non-catalog ids
+ const priced = priceForAction(action, { usd, discountBps });
+ const requiresSeller = entry.policy === POLICY.MARKETPLACE;
+ if (requiresSeller && !sellerWallet) {
+ throw Object.assign(new Error(`action ${action} requires a seller wallet`), {
+ status: 400,
+ code: 'seller_required',
+ });
+ }
+
+ // ── SETTLE phase ────────────────────────────────────────────────────────────
+ if (settle && settle.quoteToken && settle.txSignature) {
+ const result = await verifyAndSettlePayment({
+ quoteToken: settle.quoteToken,
+ txSignature: settle.txSignature,
+ payerWallet: settle.payerWallet ?? user?.wallet_address ?? null,
+ userId: user?.id ?? null,
+ network,
+ });
+ return { paid: true, payment: result };
+ }
+
+ // ── CHARGE phase ──────────────────────────────────────────────────────────────
+ const { token, quote, expiresAt } = await issueQuote({
+ purpose: action,
+ usd: priced.usd,
+ splitPolicy: priced.policy,
+ sellerWallet,
+ network,
+ refType: refType ?? action,
+ refId,
+ });
+
+ return {
+ paid: false,
+ quote: {
+ quote_token: token,
+ action,
+ label: priced.label,
+ category: priced.category,
+ policy: priced.policy,
+ network: quote.network,
+ mint: quote.mint,
+ symbol: quote.symbol,
+ decimals: quote.decimals,
+ usd: quote.usd,
+ price_usd: quote.priceUsd,
+ price_source: quote.priceSource,
+ total_atomics: quote.total,
+ legs: quote.legs,
+ memo: quote.nonce,
+ expires_at: expiresAt,
+ },
+ };
+}
diff --git a/api/_lib/referrals.js b/api/_lib/referrals.js
index 30196a9d4..baed9665e 100644
--- a/api/_lib/referrals.js
+++ b/api/_lib/referrals.js
@@ -1,4 +1,5 @@
import { randomBytes } from 'crypto';
+import { sql } from './db.js';
/**
* Generates a random, human-readable referral code.
@@ -17,3 +18,96 @@ export function generateReferralCode(length = 8) {
return code;
}
+
+// Every user is a potential referrer, but only the email + SAML signup paths
+// mint a `referral_code` up front. Privy / SIWS / SIWE sign-ups (and any
+// pre-existing account) land with a NULL code. This lazily assigns one the
+// first time the user needs it — idempotent and race-safe via the UNIQUE
+// constraint + `WHERE referral_code IS NULL` guard.
+//
+// @param {string|number} userId
+// @returns {Promise<string>} the user's referral code
+export async function ensureReferralCode(userId) {
+ const [existing] = await sql`SELECT referral_code FROM users WHERE id = ${userId}`;
+ if (existing?.referral_code) return existing.referral_code;
+
+ for (let attempt = 0; attempt < 6; attempt++) {
+ const code = generateReferralCode();
+ try {
+ const [row] = await sql`
+ UPDATE users SET referral_code = ${code}
+ WHERE id = ${userId} AND referral_code IS NULL
+ RETURNING referral_code
+ `;
+ if (row?.referral_code) return row.referral_code;
+ // A concurrent request assigned one first — read it back.
+ const [now] = await sql`SELECT referral_code FROM users WHERE id = ${userId}`;
+ if (now?.referral_code) return now.referral_code;
+ } catch (err) {
+ // 23505 = unique_violation: this random code collided with another user's.
+ // Retry with a fresh code.
+ if (err && err.code === '23505') continue;
+ throw err;
+ }
+ }
+ throw new Error('referral_code_generation_exhausted');
+}
+
+// Points awarded per confirmed referral and per whole USD of referral earnings.
+// Kept here (not inlined) so the score formula has a single, documented home.
+const POINTS_PER_REFERRAL = 100;
+const POINTS_PER_USD = 1;
+
+/**
+ * Assemble the full membership-card payload for a user: signup position,
+ * referral code + count, lifetime referral earnings, and a derived score.
+ *
+ * `position` is the account's 1-based signup ordinal ("member #N"), a real,
+ * monotonic number — not a synthetic rank. `score` is derived purely from
+ * real referral activity so it can never drift from the underlying ledger.
+ *
+ * @param {string|number} userId
+ * @returns {Promise<object|null>} card payload, or null if the user is gone
+ */
+export async function getMembershipCard(userId) {
+ const [user] = await sql`
+ SELECT id, display_name, username, created_at, referral_code, referral_earnings_total
+ FROM users
+ WHERE id = ${userId} AND deleted_at IS NULL
+ `;
+ if (!user) return null;
+
+ const referralCode = user.referral_code || (await ensureReferralCode(userId));
+
+ const [{ count: referralCount }] = await sql`
+ SELECT COUNT(*)::int AS count FROM users
+ WHERE referred_by_id = ${userId} AND deleted_at IS NULL
+ `;
+ const [{ position }] = await sql`
+ 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
+ `;
+
+ // `referral_earnings_total` accumulates atomic USDC units (6 decimals),
+ // written by api/_lib/purchase-confirm.js.
+ const earningsAtomics = Math.max(0, Math.round(Number(user.referral_earnings_total || 0)));
+ const earningsUsd = earningsAtomics / 1_000_000;
+ const referrals = Number(referralCount || 0);
+ const score = referrals * POINTS_PER_REFERRAL + Math.floor(earningsUsd) * POINTS_PER_USD;
+
+ return {
+ referral_code: referralCode,
+ referred_users_count: referrals,
+ referral_earnings_total: earningsAtomics,
+ referral_earnings_usd: earningsUsd,
+ position,
+ total_members: Number(total || 0),
+ score,
+ display_name: user.display_name || user.username || null,
+ username: user.username || null,
+ member_since: user.created_at,
+ };
+}
diff --git a/api/_lib/token/config.js b/api/_lib/token/config.js
index 5ac9beef2..62c0ba3d8 100644
--- a/api/_lib/token/config.js
+++ b/api/_lib/token/config.js
@@ -1,10 +1,18 @@
// $THREE on-chain token layer — shared config + split policy.
//
-// Centralizes the mint, decimals, treasury wallet, and burn address so no
-// literal addresses are scattered across the paid-action endpoints (Task 19
-// paid spins, Task 20 token-priced listings). Mirrors the HOLDER_PASS_SECRET
-// boot guard: a value that, if wrong/unset, would route real funds to the
-// wrong place fails loudly in production rather than silently mis-paying.
+// Centralizes the mint, decimals, treasury wallet, and rewards (reflections)
+// wallet so no literal addresses are scattered across the paid-action endpoints.
+// Mirrors the HOLDER_PASS_SECRET boot guard: a value that, if wrong/unset, would
+// route real funds to the wrong place fails loudly in production rather than
+// silently mis-paying.
+//
+// ECONOMY POLICY — NO PLATFORM BURNS. Every $THREE the platform charges routes to
+// the treasury, a holder-rewards (reflections) pool, and — on a sale — the
+// seller/creator. Supply is never destroyed; the treasury funds buybacks instead,
+// which creates buy pressure without deflation. The `burn` role and burn address
+// remain ONLY for the user-invoked burn primitive (three_burn in three-token-mcp,
+// where a holder may choose to burn their own bag). No platform split policy below
+// includes a burn leg.
import { env } from '../env.js';
@@ -66,7 +74,46 @@ export function treasuryWalletOrNull() {
return env.THREE_TREASURY_WALLET || null;
}
-/** The burn sink. Defaults to the Solana incinerator (unspendable ATA). */
+let _rewardsWarned = false;
+/**
+ * Rewards (reflections) wallet that receives the `rewards` share of every split.
+ * This is the pool distributed back to $THREE holders pro-rata (Lever: treasury
+ * loop). Same fail-closed contract as the treasury: production MUST set
+ * THREE_REWARDS_WALLET or fund-routing refuses; dev falls back to the burn sink so
+ * the split still has a valid destination and no real wallet is silently credited.
+ */
+export function rewardsWallet() {
+ const w = env.THREE_REWARDS_WALLET;
+ if (w) return w;
+ if (process.env.NODE_ENV === 'production') {
+ const e = new Error(
+ '[token] THREE_REWARDS_WALLET is required in production — refusing to route holder-rewards funds to an unset address.',
+ );
+ e.status = 503;
+ e.code = 'rewards_unavailable';
+ throw e;
+ }
+ if (!_rewardsWarned) {
+ _rewardsWarned = true;
+ console.warn(
+ '[token] THREE_REWARDS_WALLET is not set — falling back to the burn sink for dev. ' +
+ 'Set THREE_REWARDS_WALLET in production or the holder-rewards share is burned.',
+ );
+ }
+ return burnAddress();
+}
+
+/** Non-throwing rewards lookup for READ paths (public config, status). */
+export function rewardsWalletOrNull() {
+ return env.THREE_REWARDS_WALLET || null;
+}
+
+/**
+ * The burn sink (Solana incinerator, unspendable ATA). Retained ONLY for the
+ * user-invoked burn primitive (three_burn) and as the dev fallback for unset
+ * fund-routing wallets. NO platform split policy routes here — see the economy
+ * policy note at the top of this file.
+ */
export function burnAddress() {
return env.THREE_BURN_ADDRESS;
}
@@ -74,30 +121,50 @@ export function burnAddress() {
// ── Split policy ────────────────────────────────────────────────────────────
//
// Each policy is an ordered list of legs { role, bps }. bps across legs must
-// sum to 10_000. Roles 'burn' and 'treasury' resolve to the config addresses
-// above; 'seller' resolves to a per-call address (a marketplace listing's
-// payout wallet). Tasks 19/20 reuse the same verified-payment path by naming a
-// different policy here — the split ratio is a parameter, not a fork of logic.
+// sum to 10_000. Roles resolve to addresses:
+// 'treasury' → THREE_TREASURY_WALLET (the platform cut, funds buybacks)
+// 'rewards' → THREE_REWARDS_WALLET (the holder reflections pool)
+// 'seller' → a per-call address (a marketplace listing's / creator's payout)
+// No platform policy routes to 'burn' — supply is never destroyed (see top note).
+// Every paid surface reuses the same verified-payment path by naming a policy
+// here; the split ratio is a parameter, not a fork of logic.
export const SPLIT_POLICIES = Object.freeze({
- // Task 19 — paid wheel spins: half burned, half to treasury.
+ // Pay-per-use compute (Forge paid tiers, voice clone, MCP-3D, Granite,
+ // selfie→avatar). 70% funds the platform/buybacks, 30% reflects to holders.
+ consumption: [
+ { role: 'treasury', bps: 7000 },
+ { role: 'rewards', bps: 3000 },
+ ],
+ // Paid game spins (in-app wheel / actions). Former burn half now reflects to
+ // holders instead of being destroyed.
spin: [
- { role: 'burn', bps: 5000 },
{ role: 'treasury', bps: 5000 },
+ { role: 'rewards', bps: 5000 },
],
- // Task 20 — token-priced marketplace sales: seller keeps 95%, 5% to treasury.
+ // Token-priced marketplace sales (skills, animations, avatars, assets,
+ // collectible resales). Seller/creator keeps 90%, 5% treasury, 5% rewards.
marketplace_sale: [
- { role: 'seller', bps: 9500 },
+ { role: 'seller', bps: 9000 },
{ role: 'treasury', bps: 500 },
+ { role: 'rewards', bps: 500 },
+ ],
+ // Scarcity drops + rare-name auctions + pay-to-mint. No seller leg (the
+ // platform mints the scarce good); 80% treasury, 20% reflects to holders.
+ scarcity_mint: [
+ { role: 'treasury', bps: 8000 },
+ { role: 'rewards', bps: 2000 },
],
});
function resolveRole(role, { sellerWallet } = {}) {
- if (role === 'burn') return burnAddress();
if (role === 'treasury') return treasuryWallet();
+ if (role === 'rewards') return rewardsWallet();
if (role === 'seller') {
if (!sellerWallet) throw badRequest('sellerWallet is required for this split policy');
return sellerWallet;
}
+ // 'burn' intentionally has no platform route — the user-invoked burn primitive
+ // resolves its own destination from burnAddress() directly, not via a policy.
throw new Error(`[token] unknown split role: ${role}`);
}
@@ -146,15 +213,21 @@ export function applySplit(totalAtomics, legs) {
/** Public, non-secret config for clients to display and build transactions. */
export function publicConfig() {
- // Read path: surface the treasury as null when unset rather than throwing.
- // The strict treasuryWallet() guard stays on the fund-routing path only.
+ // Read path: surface treasury/rewards as null when unset rather than throwing.
+ // The strict treasuryWallet()/rewardsWallet() guards stay on fund-routing only.
const treasury = treasuryWalletOrNull();
+ const rewards = rewardsWalletOrNull();
return {
mint: TOKEN_MINT,
symbol: TOKEN_SYMBOL,
decimals: TOKEN_DECIMALS,
treasury,
treasury_configured: treasury != null,
+ // Holder reflections pool — receives the `rewards` leg of every split and is
+ // distributed back to holders pro-rata by the rewards cron.
+ rewards_wallet: rewards,
+ rewards_configured: rewards != null,
+ // Retained for the user-invoked burn primitive only; no platform split burns.
burn_address: burnAddress(),
quote_ttl_seconds: env.THREE_QUOTE_TTL_S,
split_policies: Object.fromEntries(
diff --git a/api/_lib/token/payments.js b/api/_lib/token/payments.js
index 3f29611d5..dad28d3c1 100644
--- a/api/_lib/token/payments.js
+++ b/api/_lib/token/payments.js
@@ -77,7 +77,7 @@ export async function verifyOnChain({ quote, txSignature, network = 'mainnet' })
}
// Every split leg must have received at least its share. Underpaying any leg
- // (including the burn) voids the whole payment.
+ // (treasury, rewards, or seller) voids the whole payment.
const credited = {};
for (const leg of quote.legs) {
const need = BigInt(leg.atomics);
diff --git a/api/token/[action].js b/api/token/[action].js
index 733fee17f..d5f40fc91 100644
--- a/api/token/[action].js
+++ b/api/token/[action].js
@@ -27,6 +27,13 @@ import { issueQuote, verifyAndSettlePayment, listPayments } from '../_lib/token/
const PURPOSES = {
spin: { policy: 'spin', maxUsd: 100, requiresSeller: false },
marketplace_sale: { policy: 'marketplace_sale', maxUsd: 1_000_000, requiresSeller: true },
+ // Pay-per-use compute (Forge paid tiers, voice clone, MCP-3D, Granite, selfie).
+ // Priced server-side from the pricing catalog; the ceiling guards the generic
+ // surface against an absurd client-supplied amount.
+ consumption: { policy: 'consumption', maxUsd: 100, requiresSeller: false },
+ // Scarcity drops, rare-name auctions, pay-to-mint. Platform mints the scarce
+ // good (no seller leg); the high ceiling allows premium auctions.
+ scarcity_mint: { policy: 'scarcity_mint', maxUsd: 1_000_000, requiresSeller: false },
};
const SOLANA_ADDRESS = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'invalid Solana address');
diff --git a/api/users/referral-claim.js b/api/users/referral-claim.js
new file mode 100644
index 000000000..92bd35202
--- /dev/null
+++ b/api/users/referral-claim.js
@@ -0,0 +1,93 @@
+// POST /api/users/referral-claim — attribute a pending referral to the
+// signed-in user.
+//
+// The email signup path attributes referrals inline (api/auth/[action].js),
+// but the Privy / SIWS / SIWE wallet flows don't carry a referral code through
+// their verify handshakes. This endpoint closes that gap: the client captures
+// `?ref=CODE` at the door (public/referral-capture.js) and replays it here once
+// the user has a session, regardless of which auth method they used.
+//
+// Attribution is one-shot and guarded:
+// • only when the account has no referrer yet (`referred_by_id IS NULL`)
+// • only for genuinely new accounts (created within ATTRIBUTION_WINDOW)
+// • never a self-referral, never an unknown code
+//
+// body: { code: string }
+// → { status: 'claimed' | 'already' | 'invalid' | 'expired', referrer?: { name } }
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { cors, json, error, method, wrap, rateLimited, readJson } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { insertNotification } from '../_lib/notify.js';
+
+// Referral codes use a base32-like alphabet (api/_lib/referrals.js).
+const CODE_RE = /^[A-Z2-9]{4,20}$/;
+
+// How long after signup a referral can still be attributed. The once-only
+// `referred_by_id IS NULL` guard does the heavy lifting; this window simply
+// stops a long-time member from being credited to whoever's link they happen
+// to click months later.
+const ATTRIBUTION_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (!(await requireCsrf(req, res, session.id))) return;
+
+ const body = await readJson(req);
+ const code = String(body?.code || '').trim().toUpperCase();
+ if (!CODE_RE.test(code)) return error(res, 400, 'invalid_code', 'malformed referral code');
+
+ const [me] = await sql`
+ SELECT id, referred_by_id, created_at, referral_code
+ FROM users WHERE id = ${session.id} AND deleted_at IS NULL
+ `;
+ if (!me) return error(res, 404, 'not_found', 'user not found');
+
+ // Already attributed — idempotent success, nothing to do.
+ if (me.referred_by_id != null) return json(res, 200, { status: 'already' });
+
+ // You can't refer yourself.
+ if (me.referral_code && me.referral_code.toUpperCase() === code) {
+ return json(res, 200, { status: 'invalid' });
+ }
+
+ // Only fresh accounts can be attributed.
+ const ageMs = Date.now() - new Date(me.created_at).getTime();
+ if (!Number.isFinite(ageMs) || ageMs > ATTRIBUTION_WINDOW_MS) {
+ return json(res, 200, { status: 'expired' });
+ }
+
+ const [referrer] = await sql`
+ SELECT id, display_name, username
+ FROM users
+ WHERE referral_code = ${code} AND id <> ${me.id} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!referrer) return json(res, 200, { status: 'invalid' });
+
+ // Atomic set-once: the WHERE guard means a concurrent claim can't double-set.
+ const [updated] = await sql`
+ UPDATE users SET referred_by_id = ${referrer.id}
+ WHERE id = ${me.id} AND referred_by_id IS NULL
+ RETURNING id
+ `;
+ if (!updated) return json(res, 200, { status: 'already' });
+
+ insertNotification(referrer.id, 'referral_signup', {
+ referred_user_id: me.id,
+ referred_name: me.display_name || null,
+ });
+
+ const referrerName = referrer.display_name || referrer.username || null;
+ return json(res, 200, { status: 'claimed', referrer: { name: referrerName } });
+});
diff --git a/api/users/referrals.js b/api/users/referrals.js
index 7476fc290..12fb6c8b1 100644
--- a/api/users/referrals.js
+++ b/api/users/referrals.js
@@ -1,8 +1,12 @@
-import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getMembershipCard } from '../_lib/referrals.js';
+// GET /api/users/referrals — the signed-in user's membership card payload:
+// referral code (lazily minted if absent), referral count + lifetime earnings,
+// signup position ("member #N"), and a derived score. Powers the 3D referral
+// card on /dashboard/referrals.
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
@@ -15,27 +19,8 @@ export default wrap(async (req, res) => {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const [user] = await sql`
- SELECT
- referral_code,
- referral_earnings_total
- FROM users
- WHERE id = ${userId}
- `;
+ const card = await getMembershipCard(userId);
+ if (!card) return error(res, 404, 'not_found', 'user not found');
- if (!user) {
- return error(res, 404, 'not_found', 'user not found');
- }
-
- const [referralCount] = await sql`
- SELECT COUNT(*) as count
- FROM users
- WHERE referred_by_id = ${userId}
- `;
-
- return json(res, 200, {
- referral_code: user.referral_code,
- referral_earnings_total: user.referral_earnings_total,
- referred_users_count: parseInt(referralCount.count, 10),
- });
+ return json(res, 200, card);
});
diff --git a/multiplayer/src/game-token.js b/multiplayer/src/game-token.js
index 4d5f45e1b..e430538ff 100644
--- a/multiplayer/src/game-token.js
+++ b/multiplayer/src/game-token.js
@@ -26,12 +26,18 @@ export const TOKEN_MINT = process.env.GAME_TOKEN_MINT || 'FeMbDoX7R1Psc4GEcvJdsb
export const TOKEN_DECIMALS = Number(process.env.GAME_TOKEN_DECIMALS || 6);
export const TOKEN_SYMBOL = '$THREE';
-// The burn sink for paid-spin splits. Defaults to the canonical Solana
-// incinerator (an unspendable address) — sending $THREE to its ATA removes the
-// tokens from circulation. Matches api/_lib/token/config.js's burn address so
-// both token layers burn to the same place.
-export const BURN_ADDRESS =
- process.env.GAME_TOKEN_BURN || process.env.THREE_BURN_ADDRESS || '1nc1nerator11111111111111111111111111111111';
+// The holder-rewards (reflections) sink for paid-spin and boutique splits. The
+// platform NEVER burns supply — the share that historically went to the
+// incinerator now routes to the rewards pool, which is distributed back to
+// holders pro-rata. Defaults to the configured rewards wallet, falling back to
+// the treasury so the split always has a real, spendable destination (never the
+// incinerator). Mirrors api/_lib/token/config.js's rewards wallet.
+export const REWARDS_SINK =
+ process.env.GAME_TOKEN_REWARDS ||
+ process.env.THREE_REWARDS_WALLET ||
+ process.env.GAME_TOKEN_TREASURY ||
+ process.env.PAYMENT_RECIPIENT_SOLANA ||
+ '';
const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
const BIRDEYE_BASE = 'https://public-api.birdeye.so';
@@ -278,39 +284,40 @@ function accountKeyAt(tx, index) {
// --- paid wheel spins (Task 19) ---------------------------------------------
//
-// A spin costs $3 in $THREE, split 50% burned / 50% to treasury. The flow
-// mirrors marketplace settlement but with two fixed destinations (burn +
-// treasury) and a memo binding the on-chain tx to the exact quote it settles:
+// A spin costs $3 in $THREE, split 50% to holder rewards / 50% to treasury (no
+// supply is burned). The flow mirrors marketplace settlement but with two fixed
+// destinations (rewards + treasury) and a memo binding the tx to the quote it settles:
// buildSpinPayment() → client signs+broadcasts → verifySpinPayment().
// Replay protection (a settled signature/nonce can't roll a second prize) is the
// caller's responsibility — the caller tracks consumed nonces per process and
// the short quote TTL bounds the window.
-// Split a total into burn + treasury legs by basis points. Treasury absorbs the
-// rounding remainder so the two legs always sum to exactly the total.
-export function splitBurnTreasury(rawTotal, burnBps = 5000) {
+// Split a total into rewards + treasury legs by basis points. Treasury absorbs the
+// rounding remainder so the two legs always sum to exactly the total. `rewardsBps`
+// is the share that reflects to holders (was the burn share — no supply is destroyed).
+export function splitTreasuryRewards(rawTotal, rewardsBps = 5000) {
const total = BigInt(rawTotal);
- const burn = (total * BigInt(burnBps)) / 10000n;
- const treasury = total - burn;
- return { burn, treasury };
+ const rewards = (total * BigInt(rewardsBps)) / 10000n;
+ const treasury = total - rewards;
+ return { rewards, treasury };
}
// Three-leg split for a coin-tied sale (R25): the creator share comes off the top
-// (by `creatorBps`), then the remainder splits burn/treasury by `burnBps`. The
-// creator leg is taken FIRST so the platform's burn/treasury split is computed on
-// what's left — i.e. a 50% creator share over a 50/50 burn/treasury remainder
-// pays the creator 50%, burns 25%, treasuries 25%. Treasury absorbs every rounding
-// remainder so the three legs always sum to exactly the total. `creatorBps` is
-// clamped to [0,10000]; 0 (or a falsy creator wallet upstream) degenerates to the
-// plain burn/treasury split with a zero creator leg.
-export function splitCreatorTreasuryBurn(rawTotal, creatorBps = 0, burnBps = 5000) {
+// (by `creatorBps`), then the remainder splits treasury/rewards by `rewardsBps`. The
+// creator leg is taken FIRST so the platform's treasury/rewards split is computed on
+// what's left — i.e. a 50% creator share over a 50/50 treasury/rewards remainder
+// pays the creator 50%, treasuries 25%, reflects 25% to holders. Treasury absorbs
+// every rounding remainder so the three legs always sum to exactly the total.
+// `creatorBps` is clamped to [0,10000]; 0 (or a falsy creator wallet upstream)
+// degenerates to the plain treasury/rewards split with a zero creator leg.
+export function splitCreatorTreasuryRewards(rawTotal, creatorBps = 0, rewardsBps = 5000) {
const total = BigInt(rawTotal);
const cbps = BigInt(Math.max(0, Math.min(10000, Number(creatorBps) | 0)));
const creator = (total * cbps) / 10000n;
const remainder = total - creator;
- const burn = (remainder * BigInt(burnBps)) / 10000n;
- const treasury = remainder - burn;
- return { creator, burn, treasury };
+ const rewards = (remainder * BigInt(rewardsBps)) / 10000n;
+ const treasury = remainder - rewards;
+ return { creator, rewards, treasury };
}
function memoInstruction(nonce) {
@@ -328,28 +335,29 @@ export async function buildSpinPayment({ buyerWallet, usd }) {
if (!tokenConfigured()) return null;
const priced = await quoteTokenForUsd(usd);
if (!priced || !(priced.raw > 0n)) return null;
- const { burn: burnRaw, treasury: treasuryRaw } = splitBurnTreasury(priced.raw, 5000);
+ const { rewards: rewardsRaw, treasury: treasuryRaw } = splitTreasuryRewards(priced.raw, 5000);
const treasuryAddr = treasuryWallet();
+ const rewardsAddr = REWARDS_SINK || treasuryAddr;
const nonce = crypto.randomBytes(16).toString('hex');
const conn = new Connection(SOLANA_RPC, 'confirmed');
const mint = new PublicKey(TOKEN_MINT);
const buyer = new PublicKey(buyerWallet);
- const burn = new PublicKey(BURN_ADDRESS);
+ const rewards = new PublicKey(rewardsAddr);
const treasury = new PublicKey(treasuryAddr);
const buyerATA = await getAssociatedTokenAddress(mint, buyer);
- const burnATA = await getAssociatedTokenAddress(mint, burn);
+ const rewardsATA = await getAssociatedTokenAddress(mint, rewards);
const treasuryATA = await getAssociatedTokenAddress(mint, treasury);
const tx = new Transaction();
- const [burnAcct, treasuryAcct] = await Promise.all([
- conn.getAccountInfo(burnATA),
+ const [rewardsAcct, treasuryAcct] = await Promise.all([
+ conn.getAccountInfo(rewardsATA),
conn.getAccountInfo(treasuryATA),
]);
- if (!burnAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, burnATA, burn, mint));
+ if (!rewardsAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, rewardsATA, rewards, mint));
if (!treasuryAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, treasuryATA, treasury, mint));
- tx.add(createTransferInstruction(buyerATA, burnATA, buyer, burnRaw));
+ tx.add(createTransferInstruction(buyerATA, rewardsATA, buyer, rewardsRaw));
tx.add(createTransferInstruction(buyerATA, treasuryATA, buyer, treasuryRaw));
tx.add(memoInstruction(nonce));
@@ -368,8 +376,8 @@ export async function buildSpinPayment({ buyerWallet, usd }) {
priceUsd: priced.price,
total: priced.raw.toString(),
tokens: priced.tokens,
- burnAddr: BURN_ADDRESS,
- burnRaw: burnRaw.toString(),
+ rewardsAddr,
+ rewardsRaw: rewardsRaw.toString(),
treasuryAddr,
treasuryRaw: treasuryRaw.toString(),
nonce,
@@ -380,7 +388,7 @@ export async function buildSpinPayment({ buyerWallet, usd }) {
/**
* Verify a settled paid spin on-chain: the quote is untampered + unexpired, the
- * tx carries the quote's memo nonce, the buyer matches, and both the burn and
+ * tx carries the quote's memo nonce, the buyer matches, and both the rewards and
* treasury legs received at least their share. Pre/post token-balance deltas
* make this robust to how the wallet assembled the transfers.
* @param {{ quoteToken: string, txSig: string, buyerWallet?: string }} params
@@ -410,14 +418,14 @@ export async function verifySpinPayment({ quoteToken, txSig, buyerWallet }) {
if (!memo || memo !== q.nonce) return { ok: false, reason: 'memo_mismatch' };
const mint = TOKEN_MINT;
- const burnATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.burnAddr))).toBase58();
+ const rewardsATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.rewardsAddr))).toBase58();
const treasuryATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.treasuryAddr))).toBase58();
const delta = (ownerATA) => {
const pre = (tx.meta?.preTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);
const post = (tx.meta?.postTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);
return BigInt(post?.uiTokenAmount?.amount || '0') - BigInt(pre?.uiTokenAmount?.amount || '0');
};
- if (delta(burnATA) < BigInt(q.burnRaw)) return { ok: false, reason: 'burn_underpaid' };
+ if (delta(rewardsATA) < BigInt(q.rewardsRaw)) return { ok: false, reason: 'rewards_underpaid' };
if (delta(treasuryATA) < BigInt(q.treasuryRaw)) return { ok: false, reason: 'treasury_underpaid' };
// Creator leg (R25): when the quote sealed a creator transfer, the on-chain tx
// must have moved at least that share to the creator's $THREE account — else the
@@ -434,8 +442,8 @@ export async function verifySpinPayment({ quoteToken, txSig, buyerWallet }) {
//
// The boutique — and any future fixed-price $THREE sink — settles through this pair,
// the spin flow's sibling generalised over an arbitrary token amount and `purpose`.
-// The player signs ONE transaction that splits a FIXED $THREE amount between the burn
-// sink and the treasury, carrying a memo nonce that binds the on-chain tx to this
+// The player signs ONE transaction that splits a FIXED $THREE amount between the holder
+// rewards pool and the treasury, carrying a memo nonce that binds the on-chain tx to this
// exact quote. The server prices the charge (never the client), then re-fetches the
// confirmed tx from RPC and checks both legs landed before releasing the unlock.
// Replay protection is the caller's responsibility (track consumed nonces) AND, for
@@ -443,7 +451,7 @@ export async function verifySpinPayment({ quoteToken, txSig, buyerWallet }) {
/**
* Build the unsigned $THREE purchase the buyer signs. `amountRaw` is the total in
- * base units (string|bigint), split burn/treasury by `burnBps` (default 50/50).
+ * base units (string|bigint), split treasury/rewards by `rewardsBps` (default 50/50).
* `extra` is sealed into the quote verbatim (e.g. the boutique listing id) so settle
* can act on it without trusting the client. Returns null when no treasury is
* configured, the buyer isn't a real wallet, or the amount is non-positive.
@@ -452,13 +460,13 @@ export async function verifySpinPayment({ quoteToken, txSig, buyerWallet }) {
* of the SAME signed transaction to a coin creator's wallet. The creator leg is a
* real third SPL transfer the buyer signs — no platform float, no second payout —
* so the split is enforced on-chain atomically. The creator share comes off the
- * top; the remainder splits burn/treasury by `burnBps` as before. A falsy/invalid
- * creator wallet or a zero `bps` degenerates to the plain two-leg split.
+ * top; the remainder splits treasury/rewards by `rewardsBps` as before. A
+ * falsy/invalid creator wallet or a zero `bps` degenerates to the plain two-leg split.
*
- * @param {{ buyerWallet: string, amountRaw: string|bigint, purpose: string, burnBps?: number, creator?: { wallet?: string, bps?: number }, extra?: object }} params
+ * @param {{ buyerWallet: string, amountRaw: string|bigint, purpose: string, rewardsBps?: number, creator?: { wallet?: string, bps?: number }, extra?: object }} params
* @returns {Promise<null | { quoteToken: string, txBase64: string, quote: object }>}
*/
-export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, burnBps = 5000, creator = null, extra = {} }) {
+export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, rewardsBps = 5000, creator = null, extra = {} }) {
if (!tokenConfigured()) return null;
if (!isWalletAddress(buyerWallet)) return null;
let total;
@@ -467,7 +475,7 @@ export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, burn
// A creator leg only applies when both a valid wallet and a positive share are
// supplied (and the creator isn't the buyer — a no-op self-transfer). Otherwise
- // fall back to the plain burn/treasury split, the creator leg zeroed.
+ // fall back to the plain treasury/rewards split, the creator leg zeroed.
const creatorBpsIn = Math.max(0, Math.min(10000, Number(creator?.bps) | 0));
const creatorWallet = creator?.wallet;
const creatorActive = creatorBpsIn > 0
@@ -475,36 +483,37 @@ export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, burn
&& creatorWallet !== buyerWallet;
const effectiveCreatorBps = creatorActive ? creatorBpsIn : 0;
- const { creator: creatorRaw, burn: burnRaw, treasury: treasuryRaw } =
- splitCreatorTreasuryBurn(total, effectiveCreatorBps, burnBps);
+ const { creator: creatorRaw, rewards: rewardsRaw, treasury: treasuryRaw } =
+ splitCreatorTreasuryRewards(total, effectiveCreatorBps, rewardsBps);
const treasuryAddr = treasuryWallet();
+ const rewardsAddr = REWARDS_SINK || treasuryAddr;
const nonce = crypto.randomBytes(16).toString('hex');
const conn = new Connection(SOLANA_RPC, 'confirmed');
const mint = new PublicKey(TOKEN_MINT);
const buyer = new PublicKey(buyerWallet);
- const burn = new PublicKey(BURN_ADDRESS);
+ const rewards = new PublicKey(rewardsAddr);
const treasury = new PublicKey(treasuryAddr);
const buyerATA = await getAssociatedTokenAddress(mint, buyer);
- const burnATA = await getAssociatedTokenAddress(mint, burn);
+ const rewardsATA = await getAssociatedTokenAddress(mint, rewards);
const treasuryATA = await getAssociatedTokenAddress(mint, treasury);
const creatorATA = creatorActive
? await getAssociatedTokenAddress(mint, new PublicKey(creatorWallet))
: null;
const tx = new Transaction();
- const accountChecks = [conn.getAccountInfo(burnATA), conn.getAccountInfo(treasuryATA)];
+ const accountChecks = [conn.getAccountInfo(rewardsATA), conn.getAccountInfo(treasuryATA)];
if (creatorActive) accountChecks.push(conn.getAccountInfo(creatorATA));
- const [burnAcct, treasuryAcct, creatorAcct] = await Promise.all(accountChecks);
- if (!burnAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, burnATA, burn, mint));
+ const [rewardsAcct, treasuryAcct, creatorAcct] = await Promise.all(accountChecks);
+ if (!rewardsAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, rewardsATA, rewards, mint));
if (!treasuryAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, treasuryATA, treasury, mint));
if (creatorActive && !creatorAcct) {
tx.add(createAssociatedTokenAccountInstruction(buyer, creatorATA, new PublicKey(creatorWallet), mint));
}
// Order legs largest-intent first for readability; amounts are what matter.
if (creatorActive && creatorRaw > 0n) tx.add(createTransferInstruction(buyerATA, creatorATA, buyer, creatorRaw));
- if (burnRaw > 0n) tx.add(createTransferInstruction(buyerATA, burnATA, buyer, burnRaw));
+ if (rewardsRaw > 0n) tx.add(createTransferInstruction(buyerATA, rewardsATA, buyer, rewardsRaw));
if (treasuryRaw > 0n) tx.add(createTransferInstruction(buyerATA, treasuryATA, buyer, treasuryRaw));
tx.add(memoInstruction(nonce));
@@ -521,8 +530,8 @@ export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, burn
buyer: buyerWallet,
total: total.toString(),
tokens: Number(total) / 10 ** TOKEN_DECIMALS,
- burnAddr: BURN_ADDRESS,
- burnRaw: burnRaw.toString(),
+ rewardsAddr,
+ rewardsRaw: rewardsRaw.toString(),
treasuryAddr,
treasuryRaw: treasuryRaw.toString(),
// Creator leg (R25). Sealed into the quote so settle verifies the on-chain
@@ -539,7 +548,7 @@ export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, burn
/**
* Verify a settled $THREE purchase on-chain: the quote is untampered, unexpired, and
* matches the expected purpose + buyer; the tx carries the quote's memo nonce; and the
- * burn + treasury legs each received at least their share. Pre/post token-balance
+ * rewards + treasury legs each received at least their share. Pre/post token-balance
* deltas make this robust to however the wallet assembled the transfers.
* @param {{ quoteToken: string, txSig: string, buyerWallet?: string, purpose?: string }} params
* @returns {Promise<{ ok: boolean, reason?: string, nonce?: string, quote?: object }>}
@@ -568,14 +577,14 @@ export async function verifyTokenPurchase({ quoteToken, txSig, buyerWallet, purp
if (!memo || memo !== q.nonce) return { ok: false, reason: 'memo_mismatch' };
const mint = TOKEN_MINT;
- const burnATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.burnAddr))).toBase58();
+ const rewardsATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.rewardsAddr))).toBase58();
const treasuryATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.treasuryAddr))).toBase58();
const delta = (ownerATA) => {
const pre = (tx.meta?.preTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);
const post = (tx.meta?.postTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);
return BigInt(post?.uiTokenAmount?.amount || '0') - BigInt(pre?.uiTokenAmount?.amount || '0');
};
- if (delta(burnATA) < BigInt(q.burnRaw)) return { ok: false, reason: 'burn_underpaid' };
+ if (delta(rewardsATA) < BigInt(q.rewardsRaw)) return { ok: false, reason: 'rewards_underpaid' };
if (delta(treasuryATA) < BigInt(q.treasuryRaw)) return { ok: false, reason: 'treasury_underpaid' };
// Creator leg (R25): when the quote sealed a creator transfer, the on-chain tx
// must have moved at least that share to the creator's $THREE account — else the
diff --git a/public/nav-data.js b/public/nav-data.js
index c50c995d9..8461a97fb 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -44,25 +44,6 @@ export const NAV_GROUPS = [
badge: 'New',
desc: 'Guided wizard: name, 3D body, skills, personality → ship it',
},
- {
- title: 'Vanity wallet',
- href: '/vanity-wallet',
- badge: 'New',
- desc: 'Grind a custom Solana address — prefix, suffix, or both',
- },
- {
- title: 'Worlds',
- href: '/play',
- badge: 'New',
- desc: 'Every coin is a 3D world — drop in & hang out',
- },
- {
- title: 'Sniper Arena',
- href: '/play/arena',
- badge: 'New',
- desc: 'Watch AI agents trade pump.fun live — on-chain P&L leaderboard',
- },
- { title: 'Create avatar', href: '/create', desc: 'Pick or upload a 3D body' },
{
title: 'Selfie to avatar',
href: '/create/selfie',
@@ -73,31 +54,6 @@ export const NAV_GROUPS = [
href: '/avatar-studio',
desc: 'Sculpt face + body from scratch → export GLB',
},
- {
- title: 'Scene Studio',
- href: '/scene',
- desc: 'Assemble models into full 3D scenes',
- },
- {
- title: 'Scene Composer',
- href: '/compose',
- badge: 'New',
- desc: 'Forge items & dress your avatar in real time',
- },
- {
- title: 'Voice Lab',
- href: '/voice',
- badge: 'New',
- desc: 'Clone your voice · TTS playground',
- },
- { title: 'Pose Studio', href: '/pose', desc: 'Click-to-pose mannequin + export PNG' },
- { title: 'Viewer', href: '/app', desc: 'Drag-and-drop GLB' },
- {
- title: 'Playground',
- href: '/playground',
- desc: 'Viewer + environment + embed code',
- },
- { title: 'glTF Validator', href: '/validation', desc: 'Khronos spec check' },
],
},
{
@@ -108,43 +64,14 @@ export const NAV_GROUPS = [
href: '/what-is',
desc: 'Plain-English intro + real use-cases — start here',
},
- {
- title: 'Features',
- href: '/features',
- desc: 'Everything an agent gets — interactive tour',
- },
- { title: 'ERC-8004 Agents', href: '/discover', desc: 'On-chain agent directory' },
{ title: 'Agents Index', href: '/agents', desc: 'Browse every registered agent' },
- {
- title: 'Agent Launches',
- href: '/launches',
- badge: 'New',
- desc: 'Every coin launched by an agent — live public feed',
- },
- {
- title: 'Reputation Explorer',
- href: '/reputation',
- desc: 'On-chain scores & attestations',
- },
{ title: 'Marketplace', href: '/marketplace', desc: 'Buy, sell & remix agents' },
{ title: 'Avatar Gallery', href: '/gallery', desc: 'Every public 3D avatar' },
{
- title: 'Skills',
- href: '/skills',
- badge: 'New',
- desc: 'Browse agent tool packs & capabilities',
- },
- { title: 'x402 Bazaar', href: '/bazaar', desc: 'Browse paid APIs and MCP tools' },
- {
- title: 'Community',
- href: '/community',
- desc: 'X, GitHub, and ways to get involved',
- },
- {
- title: 'Labs',
- href: '/labs',
+ title: 'Worlds',
+ href: '/play',
badge: 'New',
- desc: 'Hidden gems — fact-checker, tutor, lipsync & more',
+ desc: 'Every coin is a 3D world — drop in & hang out',
},
{
title: 'All pages',
@@ -161,12 +88,6 @@ export const NAV_GROUPS = [
href: '/launchpad',
desc: 'Create a token for your agent',
},
- {
- title: 'All Launches',
- href: '/launches',
- badge: 'New',
- desc: 'Public feed of every agent coin',
- },
{
title: 'Live Stream',
href: '/pump-live',
@@ -179,27 +100,6 @@ export const NAV_GROUPS = [
href: '/pump-visualizer',
desc: 'Trending tokens in 3D',
},
- {
- title: 'Token in 3D',
- href: '/coin3d',
- desc: 'View any token as a 3D scene',
- },
- ],
- },
- {
- label: 'Embed',
- items: [
- { title: 'Widgets', href: '/widgets', desc: 'Browse + customize embeddable widgets' },
- { title: 'Widget Studio', href: '/studio', desc: 'Pick avatar → copy snippet' },
- { title: 'Embed editor', href: '/embed.html', desc: 'Tune mode, size, position' },
- {
- title: 'Avatar SDK',
- href: '/avatar-sdk',
- badge: 'New',
- desc: 'npm · web component · React · GLB upload',
- },
- { title: 'Embed docs', href: '/docs#embedding', desc: 'iframe + oEmbed' },
- { title: '<agent-3d>', href: '/docs#web-component', desc: 'Web component reference' },
],
},
{
@@ -207,114 +107,13 @@ export const NAV_GROUPS = [
items: [
{ title: 'Docs', href: '/docs', desc: 'SDKs + API reference' },
{ title: 'Tutorials', href: '/tutorials', desc: 'Step-by-step guides' },
- {
- title: 'Brain',
- href: '/brain',
- badge: 'New',
- desc: 'Claude · GPT · DeepSeek · Qwen · Llama',
- },
{ title: 'Chat', href: '/chat', desc: 'Talk to your agent' },
{ title: 'Pay', href: '/pay', desc: 'Agent payments — x402 + USDC' },
- { title: 'Solana SDK', href: '/docs#solana', desc: 'Attestations + agent-kit' },
{
- title: 'Glossary',
- href: '#',
- desc: 'Plain-English definitions for crypto terms',
- attrs: { 'data-glossary-open': '' },
- },
- ],
- },
- {
- label: 'Integrations',
- layout: 'wide',
- note: 'Live partner showcases — built on real platforms, running end-to-end.',
- items: [
- {
- title: 'AWS Marketplace',
- href: '/aws',
- desc: 'three.ws as an AWS Partner listing',
- },
- ],
- },
- {
- label: 'Labs',
- badge: 'Beta',
- layout: 'mega',
- note: 'Experimental features — actively iterating. Expect rough edges.',
- columns: [
- {
- label: 'Avatar & Motion',
- items: [
- { title: 'Lipsync', href: '/lipsync', desc: 'TTS or mic → in-browser viseme → mouth' },
- { title: 'Mocap Studio', href: '/mocap-studio', desc: 'Record face → save clip → replay' },
- { title: 'OBS Overlay', href: '/overlay-control', desc: 'Stream deck — emote hotkeys, mic' },
- { title: 'Walk', href: '/walk', desc: 'Walk your avatar — multiplayer + AR' },
- { title: 'IRL', href: '/irl', desc: 'AR camera + joystick + tap-to-place objects' },
- { title: 'XR', href: '/xr', desc: 'Place your avatar in the real world' },
- ],
- },
- {
- label: 'Markets & Pump',
- items: [
- {
- title: 'Launchpad Studio',
- href: '/launchpad',
- desc: 'Build a 3D launchpad · token · concierge',
- },
- { title: 'GMGN Smart Money', href: '/gmgn', desc: 'Agent narrates smart wallet signals' },
- { title: 'Pump.fun stream', href: '/pumpfun', desc: 'Mint agent tokens' },
- { title: 'Live launches', href: '/pump-live', desc: 'Real-time launch feed' },
- { title: 'Pump Dashboard', href: '/pump-dashboard', desc: 'Watches · scanner · quotes' },
- { title: 'Pump Visualizer', href: '/pump-visualizer', desc: '3D view of trending tokens' },
- {
- title: '$THREE Live',
- href: '/three-live',
- badge: 'New',
- desc: 'Protocol pulse — live trades in 3D',
- },
- { title: 'Strategy Lab', href: '/strategy-lab', desc: 'DCA + subscriptions' },
- ],
- },
- {
- label: 'x402 & Onchain',
- items: [
- {
- title: 'Agent Wallet',
- href: '/play/agent-wallet',
- badge: 'New',
- desc: 'Your avatar pays an endpoint with its agent wallet — USDC on Solana',
- },
- { title: 'Pole Club', href: '/club', desc: 'x402 micro-tip demo — $0.001 / dance' },
- {
- title: 'Endpoint Shopper',
- href: '/shopper',
- desc: 'AI chains x402 endpoints to answer a task',
- },
- {
- title: 'Pay-As-You-Learn Tutor',
- href: '/tutor',
- desc: '$0.01 per answer in USDC over x402',
- },
- {
- title: 'Fact Checker',
- href: '/fact-checker',
- desc: '$0.10 per claim — cited verdict + attestation',
- },
- { title: 'API Arbitrage', href: '/arbitrage', desc: 'Cheapest endpoint per capability, live' },
- {
- title: 'API Providers',
- href: '/providers',
- desc: 'Operator profiles for the paid API catalog',
- },
- {
- title: 'Unstoppable Agent',
- href: '/unstoppable',
- desc: 'Self-funding agent dashboard, live',
- },
- { title: 'Forever', href: '/forever', desc: 'Etch a message into Bitcoin — forever' },
- { title: 'EVM vanity wallet', href: '/evm-wallet', desc: 'Grind an Ethereum / EVM address' },
- { title: 'ETH vanity (CREATE2)', href: '/eth-vanity', desc: 'Grind a smart-contract address' },
- ],
+ title: 'Avatar SDK',
+ href: '/avatar-sdk',
+ badge: 'New',
+ desc: 'npm · web component · React · GLB upload',
},
],
},
@@ -323,7 +122,6 @@ export const NAV_GROUPS = [
// Top-level links rendered after the dropdown groups (no submenu).
export const NAV_LINKS = [
{ label: 'Text → 3D', href: '/forge', highlight: true },
- { label: 'Pricing', href: '/pricing' },
];
// Footer-of-drawer links that have no desktop dropdown home.
diff --git a/src/city/city-world.js b/src/city/city-world.js
index f384ef7c8..4773ed1bc 100644
--- a/src/city/city-world.js
+++ b/src/city/city-world.js
@@ -30,7 +30,7 @@ async function main() {
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ renderer.shadowMap.type = THREE.PCFShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 0.88;
renderer.outputColorSpace = THREE.SRGBColorSpace;
diff --git a/src/club-entrance.js b/src/club-entrance.js
index 08e9d8cf0..d9e85b5ab 100644
--- a/src/club-entrance.js
+++ b/src/club-entrance.js
@@ -21,6 +21,7 @@ import {
AmbientLight,
Box3,
BoxGeometry,
+ Color,
Fog,
Group,
HemisphereLight,
@@ -109,7 +110,10 @@ async function start(canvasEl) {
renderer.toneMappingExposure = 1.12;
const scene = new Scene();
- scene.background = null;
+ // Opaque backdrop (matches the fog) so the pole stage rendering behind this
+ // canvas never shows through the alley's open edges — the club stays hidden
+ // until the walk-through fades this whole canvas out via CSS opacity.
+ scene.background = new Color(0x05030a);
scene.fog = new Fog(0x05030a, 8, 34);
const camera = new PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.05, 200);
@@ -143,7 +147,14 @@ async function start(canvasEl) {
// ── Environment ──────────────────────────────────────────────────────────
let env = mountEnvironment(scene, alleyGltf.scene);
- let path = walkPath(env.box);
+ // Anchor the entrance to the alley's modelled door so the prompt and the
+ // neon frame land on the real doorway, not a guessed end of the footprint.
+ let doorAnchor = findDoorAnchor(env.root);
+ let path = walkPath(env.box, doorAnchor);
+ // Seal the doorway: a dark plane just inside it so the lit interior never
+ // reads from the alley — the club stays hidden until you pay and walk in.
+ let occluder = doorAnchor ? buildDoorOccluder(doorAnchor, path.dir) : null;
+ if (occluder) scene.add(occluder);
// ── Avatar ─────────────────────────────────────────────────────────────
const avatar = avatarGltf.scene;
@@ -170,10 +181,29 @@ async function start(canvasEl) {
let inputEnabled = true;
let autoWalk = false; // forced forward motion during the walk-through
+ // The pavement surface sits above the environment's y=0 origin, so stand the
+ // avatar on the sampled floor rather than the box bottom (feet-through-floor).
+ const groundRay = new Raycaster();
+ const DOWN = new Vector3(0, -1, 0);
+ let floorY = 0;
+ // Ray for camera-wall collision (keeps its own `far`, used in updateCamera).
+ const camRay = new Raycaster();
+
placeSpawn();
+ // Cast straight down from above to the floor at (x, z). Starts at mid-room so
+ // it clears ceilings/awnings and returns the walkable surface height.
+ function sampleFloor(x, z) {
+ groundRay.set(new Vector3(x, ROOM_HEIGHT * 0.6, z), DOWN);
+ groundRay.far = ROOM_HEIGHT;
+ const hit = groundRay.intersectObject(env.root, true)[0];
+ return hit ? hit.point.y : 0;
+ }
+
function placeSpawn() {
rig.position.copy(path.spawn);
+ floorY = sampleFloor(path.spawn.x, path.spawn.z);
+ rig.position.y = floorY;
// Face the door (opposite the walk axis).
rig.rotation.y = Math.atan2(-path.dir.x, -path.dir.z);
doorMarker.group.position.copy(path.door);
@@ -380,9 +410,20 @@ async function start(canvasEl) {
function updateCamera(dt) {
const cosP = Math.cos(camPitch);
- const off = new Vector3(Math.sin(camYaw) * cosP, Math.sin(camPitch) + 0.0, Math.cos(camYaw) * cosP);
- const target = new Vector3(rig.position.x, HEAD_Y, rig.position.z);
- const desired = target.clone().addScaledVector(off, CAM_DIST).setY(CAM_HEIGHT + Math.sin(camPitch) * CAM_DIST);
+ const off = new Vector3(Math.sin(camYaw) * cosP, Math.sin(camPitch), Math.cos(camYaw) * cosP);
+ const target = new Vector3(rig.position.x, rig.position.y + HEAD_Y, rig.position.z);
+ const desired = target.clone().addScaledVector(off, CAM_DIST);
+ desired.y = rig.position.y + CAM_HEIGHT + Math.sin(camPitch) * CAM_DIST;
+ // Pull the camera in front of any wall between it and the avatar, so you
+ // never see through walls or end up buried in geometry (a black frame).
+ const toCam = desired.clone().sub(target);
+ const dist = toCam.length();
+ if (dist > 1e-3) {
+ camRay.set(target, toCam.multiplyScalar(1 / dist));
+ camRay.far = dist;
+ const hit = camRay.intersectObject(env.root, true)[0];
+ if (hit) desired.copy(target).addScaledVector(camRay.ray.direction, Math.max(0.5, hit.distance - 0.2));
+ }
const a = 1 - Math.exp(-9 * dt);
camera.position.lerp(desired, a);
camera.lookAt(target);
@@ -410,11 +451,13 @@ async function start(canvasEl) {
}
scene.remove(doorMarker.group);
disposeObject(doorMarker.group);
+ if (occluder) { scene.remove(occluder); disposeObject(occluder); occluder = null; }
doorGlow.intensity = 0;
disposeObject(env.root);
scene.remove(env.root);
env = mountEnvironment(scene, clubScene);
- path = walkPath(env.box);
+ doorAnchor = findDoorAnchor(env.root);
+ path = walkPath(env.box, doorAnchor);
placeSpawn();
setPhase('entering');
}
@@ -476,10 +519,30 @@ function mountEnvironment(scene, root) {
};
}
-// Spawn point, door point, and walk axis derived from the longer horizontal
-// dimension — independent of the model's authored orientation.
-function walkPath(box) {
+// Where you spawn, where the door is, and which way you face. When the
+// environment ships a modelled door (the alley does — `metal_door`), anchor to
+// it: the approach axis runs from the door toward the room's interior, you
+// spawn back down that axis, and you stand just in front of the door to enter.
+// Otherwise fall back to the longer horizontal dimension so any unlabelled
+// environment (e.g. the club interior) still gets a sane walk path.
+function walkPath(box, anchor) {
const size = box.getSize(new Vector3());
+ const center = box.getCenter(new Vector3());
+
+ if (anchor) {
+ const door = anchor.center.clone().setY(0);
+ let dir = new Vector3(center.x - door.x, 0, center.z - door.z);
+ if (dir.lengthSq() < 1e-4) dir.set(0, 0, 1);
+ dir.normalize();
+ const reach = Math.abs(dir.x) * size.x + Math.abs(dir.z) * size.z;
+ // Spawn a few steps from the door — close enough that the chase camera
+ // stays well inside the alley (never behind the back wall) on load.
+ const spawn = door.clone().addScaledVector(dir, clamp(reach * 0.32, 3.0, 5.0)).setY(0);
+ // Stand just in front of the door (alley side), not inside the wall.
+ const doorP = door.clone().addScaledVector(dir, 0.35).setY(0);
+ return { dir, span: reach / 2, spawn, door: doorP, start: spawn, end: doorP };
+ }
+
const alongX = size.x > size.z;
const span = (alongX ? size.x : size.z) / 2;
const dir = alongX ? new Vector3(1, 0, 0) : new Vector3(0, 0, 1);
@@ -488,6 +551,41 @@ function walkPath(box) {
return { dir, span, spawn, door: doorP, start: spawn, end: doorP };
}
+// Locate the modelled door in an environment by name (matches the alley's
+// `metal_door*` meshes). Returns the largest match's world-space centre + size,
+// or null when the environment has no labelled door.
+function findDoorAnchor(root) {
+ root.updateMatrixWorld(true);
+ let best = null;
+ root.traverse((n) => {
+ if (!n.isMesh) return;
+ if (!/door/i.test(n.name || '') && !/door/i.test(n.parent?.name || '')) return;
+ const box = new Box3().setFromObject(n);
+ if (box.isEmpty()) return;
+ const size = box.getSize(new Vector3());
+ const score = size.x * size.y * size.z;
+ if (!best || score > best.score) best = { center: box.getCenter(new Vector3()), size, score };
+ });
+ return best;
+}
+
+// A dark slab set just inside the doorway, sized to the opening and turned to
+// face the alley. Blocks the line of sight into the lit interior so the club is
+// never visible from outside — paired with the neon frame in front of it, the
+// entrance reads as a shut, glowing door.
+function buildDoorOccluder(anchor, dir) {
+ const { size } = anchor;
+ const widthPerp = Math.abs(dir.z) * size.x + Math.abs(dir.x) * size.z;
+ const geo = new BoxGeometry(Math.max(widthPerp, 1.4) * 1.2 + 0.3, size.y * 1.2, 0.3);
+ const mat = new MeshStandardMaterial({ color: 0x06040b, roughness: 1, metalness: 0 });
+ const mesh = new Mesh(geo, mat);
+ mesh.position.copy(anchor.center);
+ mesh.rotation.y = Math.atan2(dir.x, dir.z);
+ // Nudge to the interior side of the door plane, hiding the recess behind it.
+ mesh.position.addScaledVector(dir, -0.2);
+ return mesh;
+}
+
// A neon doorway: two posts, a lintel, and a glowing infill plane, with a
// gentle emissive pulse. Built from primitives so it works over any alley.
function buildDoorMarker() {
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 67109f0cc..9af24f0b4 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -11,7 +11,7 @@
// Colyseus), reused here so a coin community is a first-class 3D space.
import {
- Scene, WebGLRenderer, PerspectiveCamera, Group, Vector3, PCFSoftShadowMap, SRGBColorSpace,
+ Scene, WebGLRenderer, PerspectiveCamera, Group, Vector3, PCFShadowMap, SRGBColorSpace,
ACESFilmicToneMapping,
Mesh, MeshStandardMaterial, MeshBasicMaterial, CircleGeometry,
CylinderGeometry, PlaneGeometry,
@@ -390,7 +390,7 @@ export class CoinCommunities {
const r = new WebGLRenderer({ canvas: this.canvas, antialias: true });
r.setPixelRatio(Math.min(window.devicePixelRatio, 2));
r.setSize(window.innerWidth, window.innerHeight);
- r.shadowMap.enabled = true; r.shadowMap.type = PCFSoftShadowMap;
+ r.shadowMap.enabled = true; r.shadowMap.type = PCFShadowMap;
r.outputColorSpace = SRGBColorSpace;
// ACES keeps the cool moonlight key and the bright avatars from clipping;
// exposure is tuned for the dark monochrome arena (the LDR gradient backdrop
diff --git a/src/home-pose.js b/src/home-pose.js
index b5a9d5ec7..34a5db688 100644
--- a/src/home-pose.js
+++ b/src/home-pose.js
@@ -19,7 +19,7 @@ import {
HemisphereLight,
Mesh,
MeshBasicMaterial,
- PCFSoftShadowMap,
+ PCFShadowMap,
PerspectiveCamera,
Plane,
Quaternion,
@@ -125,7 +125,7 @@ export function initHomePose(root) {
}
renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));
renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = PCFSoftShadowMap;
+ renderer.shadowMap.type = PCFShadowMap;
const scene = new Scene();
const camera = new PerspectiveCamera(42, 1, 0.05, 100);
diff --git a/src/play-agent-wallet.js b/src/play-agent-wallet.js
index 38b6a37ae..0f82dae4f 100644
--- a/src/play-agent-wallet.js
+++ b/src/play-agent-wallet.js
@@ -15,7 +15,7 @@ import {
HemisphereLight, DirectionalLight, Mesh, MeshStandardMaterial, MeshBasicMaterial,
CircleGeometry, BoxGeometry, PlaneGeometry, RingGeometry, CylinderGeometry,
CanvasTexture, SRGBColorSpace, DoubleSide, GridHelper, Vector3, MathUtils,
- ACESFilmicToneMapping, PCFSoftShadowMap,
+ ACESFilmicToneMapping, PCFShadowMap,
} from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import {
@@ -86,7 +86,7 @@ camera.position.set(-1.6, 2.5, 6.4);
const renderer = new WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
-renderer.shadowMap.type = PCFSoftShadowMap;
+renderer.shadowMap.type = PCFShadowMap;
renderer.toneMapping = ACESFilmicToneMapping;
stageEl.appendChild(renderer.domElement);
diff --git a/src/pose-studio.js b/src/pose-studio.js
index e65bd80b2..4e3aecbf6 100644
--- a/src/pose-studio.js
+++ b/src/pose-studio.js
@@ -18,7 +18,7 @@ import {
Mesh,
MeshBasicMaterial,
MeshStandardMaterial,
- PCFSoftShadowMap,
+ PCFShadowMap,
PerspectiveCamera,
Plane,
Quaternion,
@@ -201,7 +201,7 @@ function setupScene(canvas, hudStatus) {
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = PCFSoftShadowMap;
+ renderer.shadowMap.type = PCFShadowMap;
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;
diff --git a/src/scene-compose.js b/src/scene-compose.js
index 344eabd07..6ab783888 100644
--- a/src/scene-compose.js
+++ b/src/scene-compose.js
@@ -106,7 +106,7 @@ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1;
renderer.shadowMap.enabled = true;
-renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+renderer.shadowMap.type = THREE.PCFShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
const scene = new THREE.Scene();
diff --git a/src/walk-embed-preview.js b/src/walk-embed-preview.js
index cd9996836..f4fb4f2c8 100644
--- a/src/walk-embed-preview.js
+++ b/src/walk-embed-preview.js
@@ -14,7 +14,7 @@ import {
MeshBasicMaterial,
MeshStandardMaterial,
CanvasTexture,
- PCFSoftShadowMap,
+ PCFShadowMap,
PerspectiveCamera,
PlaneGeometry,
PMREMGenerator,
@@ -80,7 +80,7 @@ export function initWalkPreview(container) {
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = PCFSoftShadowMap;
+ renderer.shadowMap.type = PCFShadowMap;
// Count this context against the shared budget so <agent-3d> grids on the
// same page leave room for it (see webgl-budget.js / element.js).
reserveWebGLContext();
diff --git a/src/walk-embed.js b/src/walk-embed.js
index d4236e7d0..cb911b31b 100644
--- a/src/walk-embed.js
+++ b/src/walk-embed.js
@@ -24,7 +24,7 @@ import {
HemisphereLight,
Mesh,
MeshStandardMaterial,
- PCFSoftShadowMap,
+ PCFShadowMap,
PerspectiveCamera,
PMREMGenerator,
Scene,
@@ -145,7 +145,7 @@ const HAS_SOLID_BG = !!(BG_PARAM && BG_PARAM !== 'transparent');
// requested color. Transparent embeds keep alpha 0 so the host shows through.
renderer.setClearColor(HAS_SOLID_BG ? new Color(BG_PARAM) : 0x000000, HAS_SOLID_BG ? 1 : 0);
renderer.shadowMap.enabled = true;
-renderer.shadowMap.type = PCFSoftShadowMap;
+renderer.shadowMap.type = PCFShadowMap;
const scene = new Scene();
diff --git a/src/walk.js b/src/walk.js
index 51d6ea42d..94331e23b 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -29,7 +29,7 @@ import {
MeshStandardMaterial,
Object3D,
OrthographicCamera,
- PCFSoftShadowMap,
+ PCFShadowMap,
PerspectiveCamera,
PlaneGeometry,
PMREMGenerator,
@@ -361,7 +361,7 @@ const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true, prese
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
-renderer.shadowMap.type = PCFSoftShadowMap;
+renderer.shadowMap.type = PCFShadowMap;
const scene = new Scene();
diff --git a/src/xr.js b/src/xr.js
index 3039d4672..c8d0eb242 100644
--- a/src/xr.js
+++ b/src/xr.js
@@ -11,7 +11,7 @@ import {
HemisphereLight,
Mesh,
MeshStandardMaterial,
- PCFSoftShadowMap,
+ PCFShadowMap,
PerspectiveCamera,
PMREMGenerator,
Scene,
@@ -55,7 +55,7 @@ const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
-renderer.shadowMap.type = PCFSoftShadowMap;
+renderer.shadowMap.type = PCFShadowMap;
renderer.outputColorSpace = 'srgb';
const scene = new Scene();
diff --git a/tests/pricing-catalog.test.js b/tests/pricing-catalog.test.js
new file mode 100644
index 000000000..e2f9d7771
--- /dev/null
+++ b/tests/pricing-catalog.test.js
@@ -0,0 +1,154 @@
+// Unit tests for the pricing catalog + the charge-three helper — the foundation
+// of the $THREE economy. The token rail is mocked: these prove the pricing math,
+// the holder-tier discount, the variable-price contract, and the free-forever
+// guardrail without needing a live quote/settle.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the token rail so we can assert what charge-three asks of it without RPC/DB.
+const issueQuote = vi.fn();
+const verifyAndSettlePayment = vi.fn();
+vi.mock('../api/_lib/token/index.js', () => ({
+ issueQuote: (...a) => issueQuote(...a),
+ verifyAndSettlePayment: (...a) => verifyAndSettlePayment(...a),
+}));
+
+import { CATALOG, POLICY, priceForAction, catalogEntry, publicCatalog } from '../api/_lib/pricing/catalog.js';
+import {
+ requireThreePayment,
+ isFreeSurface,
+ FREE_SURFACES,
+} from '../api/_lib/pricing/charge-three.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('pricing catalog', () => {
+ it('every fixed-price action carries a positive usd and a known policy', () => {
+ const policies = new Set(Object.values(POLICY));
+ for (const [id, e] of Object.entries(CATALOG)) {
+ expect(policies.has(e.policy), `${id} policy`).toBe(true);
+ if (e.usd != null) expect(e.usd, `${id} usd`).toBeGreaterThan(0);
+ }
+ });
+
+ it('forge draft is NOT in the catalog (free-forever lane)', () => {
+ expect(CATALOG['forge.draft']).toBeUndefined();
+ expect(CATALOG['forge.standard']).toBeDefined();
+ expect(CATALOG['forge.high']).toBeDefined();
+ });
+
+ it('forge prices are read from forge-tiers (0.15 / 0.50)', () => {
+ expect(CATALOG['forge.standard'].usd).toBe(0.15);
+ expect(CATALOG['forge.high'].usd).toBe(0.5);
+ });
+
+ it('catalogEntry throws a typed 404 for unknown actions', () => {
+ expect(() => catalogEntry('nope.nope')).toThrowError(/unknown paid action/);
+ try {
+ catalogEntry('nope.nope');
+ } catch (e) {
+ expect(e.status).toBe(404);
+ expect(e.code).toBe('unknown_action');
+ }
+ });
+
+ it('priceForAction applies a holder-tier discount to fixed prices', () => {
+ const full = priceForAction('forge.high');
+ expect(full.usd).toBe(0.5);
+ const discounted = priceForAction('forge.high', { discountBps: 2000 }); // 20% off
+ expect(discounted.usd).toBe(0.4);
+ });
+
+ it('discount never drops a paid action below the 1-cent floor', () => {
+ const p = priceForAction('forge.standard', { discountBps: 10000 });
+ expect(p.usd).toBe(0.01);
+ });
+
+ it('variable-price actions require a per-call usd', () => {
+ expect(() => priceForAction('name.auction')).toThrowError(/per-call usd/);
+ const p = priceForAction('name.auction', { usd: 1000 });
+ expect(p.usd).toBe(1000);
+ expect(p.policy).toBe(POLICY.SCARCITY);
+ });
+
+ it('publicCatalog exposes id/label/category/policy/usd for every action', () => {
+ const pub = publicCatalog();
+ expect(pub.length).toBe(Object.keys(CATALOG).length);
+ for (const row of pub) {
+ expect(row).toHaveProperty('id');
+ expect(row).toHaveProperty('policy');
+ }
+ });
+});
+
+describe('charge-three free-forever guardrail', () => {
+ it('flags known free surfaces', () => {
+ expect(isFreeSurface('forge.draft')).toBe(true);
+ expect(isFreeSurface('chat.free')).toBe(true);
+ expect(isFreeSurface('agent.create')).toBe(true);
+ expect(isFreeSurface('forge.standard')).toBe(false);
+ });
+
+ it('refuses to gate a free-forever surface', async () => {
+ await expect(requireThreePayment({ action: 'forge.draft' })).rejects.toMatchObject({
+ code: 'free_surface_gated',
+ });
+ expect(issueQuote).not.toHaveBeenCalled();
+ });
+
+ it('the free lane and the paid lane never overlap', () => {
+ for (const id of FREE_SURFACES) expect(CATALOG[id]).toBeUndefined();
+ });
+});
+
+describe('charge-three charge + settle', () => {
+ it('CHARGE: issues a $THREE quote priced from the catalog', async () => {
+ issueQuote.mockResolvedValue({
+ token: 'qtok.sig',
+ quote: {
+ network: 'mainnet',
+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ symbol: '$THREE',
+ decimals: 6,
+ usd: 0.15,
+ priceUsd: 0.001,
+ priceSource: 'jupiter',
+ total: '150000000',
+ legs: [{ role: 'treasury', atomics: '105000000' }, { role: 'rewards', atomics: '45000000' }],
+ nonce: 'abc',
+ },
+ expiresAt: '2026-06-15T00:01:30Z',
+ });
+
+ const out = await requireThreePayment({ action: 'forge.standard' });
+ expect(out.paid).toBe(false);
+ expect(out.quote.usd).toBe(0.15);
+ expect(out.quote.quote_token).toBe('qtok.sig');
+ expect(issueQuote).toHaveBeenCalledWith(
+ expect.objectContaining({ purpose: 'forge.standard', usd: 0.15, splitPolicy: 'consumption' }),
+ );
+ });
+
+ it('CHARGE: marketplace action without a seller wallet is rejected', async () => {
+ await expect(
+ requireThreePayment({ action: 'skill.call', usd: 0.01 }),
+ ).rejects.toMatchObject({ code: 'seller_required' });
+ expect(issueQuote).not.toHaveBeenCalled();
+ });
+
+ it('SETTLE: verifies the on-chain payment and returns it', async () => {
+ verifyAndSettlePayment.mockResolvedValue({ ok: true, payment_id: 'pid-1' });
+ const out = await requireThreePayment({
+ action: 'forge.standard',
+ user: { id: 'u1', wallet_address: 'WALLET' },
+ settle: { quoteToken: 'qtok.sig', txSignature: 'x'.repeat(88) },
+ });
+ expect(out.paid).toBe(true);
+ expect(out.payment.payment_id).toBe('pid-1');
+ expect(verifyAndSettlePayment).toHaveBeenCalledWith(
+ expect.objectContaining({ payerWallet: 'WALLET', userId: 'u1' }),
+ );
+ });
+});
diff --git a/tests/token-layer.test.js b/tests/token-layer.test.js
index 15154d834..869e7d0df 100644
--- a/tests/token-layer.test.js
+++ b/tests/token-layer.test.js
@@ -111,10 +111,21 @@ describe('token config', () => {
expect(c.mint).toBe(TOKEN_MINT);
expect(c.symbol).toBe('$THREE');
expect(c.decimals).toBe(6);
+ // Burn address is retained for the user-invoked burn primitive only.
expect(c.burn_address).toBe('1nc1nerator11111111111111111111111111111111');
+ // Rewards (reflections) pool is the deflation-free alternative to burning.
+ expect('rewards_wallet' in c).toBe(true);
expect(c.quote_ttl_seconds).toBeGreaterThan(0);
+ expect(c.split_policies.consumption).toBeDefined();
expect(c.split_policies.spin).toBeDefined();
expect(c.split_policies.marketplace_sale).toBeDefined();
+ expect(c.split_policies.scarcity_mint).toBeDefined();
+ });
+
+ it('no platform split policy routes to a burn leg', () => {
+ for (const [name, legs] of Object.entries(SPLIT_POLICIES)) {
+ expect(legs.some((l) => l.role === 'burn'), `${name} must not burn`).toBe(false);
+ }
});
it('treasuryWallet warns in dev when unset and falls back to burn', () => {
@@ -139,27 +150,47 @@ describe('token config', () => {
// ── Split policy ───────────────────────────────────────────────────────────────
describe('resolveSplitLegs', () => {
- it('spin policy yields burn + treasury legs summing to 10000 bps', () => {
+ it('every policy sums to exactly 10000 bps', () => {
+ for (const name of Object.keys(SPLIT_POLICIES)) {
+ const opts = SPLIT_POLICIES[name].some((l) => l.role === 'seller')
+ ? { sellerWallet: 'So11111111111111111111111111111111111111112' }
+ : {};
+ const legs = resolveSplitLegs(name, opts);
+ expect(legs.reduce((s, l) => s + l.bps, 0), `${name}`).toBe(10_000);
+ }
+ });
+
+ it('consumption policy yields treasury + rewards legs (no burn)', () => {
+ const legs = resolveSplitLegs('consumption');
+ expect(legs).toHaveLength(2);
+ expect(legs.find((l) => l.role === 'treasury').bps).toBe(7000);
+ expect(legs.find((l) => l.role === 'rewards').bps).toBe(3000);
+ expect(legs.find((l) => l.role === 'burn')).toBeUndefined();
+ });
+
+ it('spin policy routes the former burn half to rewards instead', () => {
const legs = resolveSplitLegs('spin');
expect(legs).toHaveLength(2);
- const total = legs.reduce((s, l) => s + l.bps, 0);
- expect(total).toBe(10_000);
- const burnLeg = legs.find((l) => l.role === 'burn');
- const treasuryLeg = legs.find((l) => l.role === 'treasury');
- expect(burnLeg.bps).toBe(5000);
- expect(treasuryLeg.bps).toBe(5000);
- expect(burnLeg.address).toBe(burnAddress());
+ expect(legs.find((l) => l.role === 'treasury').bps).toBe(5000);
+ expect(legs.find((l) => l.role === 'rewards').bps).toBe(5000);
+ expect(legs.find((l) => l.role === 'burn')).toBeUndefined();
});
- it('marketplace_sale policy yields seller + treasury legs summing to 10000 bps', () => {
+ it('marketplace_sale yields seller + treasury + rewards legs', () => {
const seller = 'So11111111111111111111111111111111111111112';
const legs = resolveSplitLegs('marketplace_sale', { sellerWallet: seller });
- expect(legs).toHaveLength(2);
- const sellerLeg = legs.find((l) => l.role === 'seller');
- const treasuryLeg = legs.find((l) => l.role === 'treasury');
- expect(sellerLeg.bps).toBe(9500);
- expect(treasuryLeg.bps).toBe(500);
- expect(sellerLeg.address).toBe(seller);
+ expect(legs).toHaveLength(3);
+ expect(legs.find((l) => l.role === 'seller').bps).toBe(9000);
+ expect(legs.find((l) => l.role === 'treasury').bps).toBe(500);
+ expect(legs.find((l) => l.role === 'rewards').bps).toBe(500);
+ expect(legs.find((l) => l.role === 'seller').address).toBe(seller);
+ });
+
+ it('scarcity_mint yields treasury + rewards legs (no seller, no burn)', () => {
+ const legs = resolveSplitLegs('scarcity_mint');
+ expect(legs.find((l) => l.role === 'treasury').bps).toBe(8000);
+ expect(legs.find((l) => l.role === 'rewards').bps).toBe(2000);
+ expect(legs.find((l) => l.role === 'seller')).toBeUndefined();
});
it('marketplace_sale throws when sellerWallet is missing', () => {
@@ -179,7 +210,7 @@ describe('applySplit', () => {
expect(result[1].atomics).toBe(1_000_000n);
});
- it('spin: odd total — remainder goes to the highest-bps leg (burn=treasury tie → first higher-index wins)', () => {
+ it('spin: odd total — remainder goes to the highest-bps leg (treasury=rewards tie)', () => {
const legs = resolveSplitLegs('spin');
const result = applySplit(1_000_001n, legs);
const total = result.reduce((s, l) => s + l.atomics, 0n);
@@ -187,13 +218,14 @@ describe('applySplit', () => {
// Both legs are 50/50; either may absorb the 1-atom remainder — just verify sum
});
- it('marketplace_sale: 95/5 split is exact on 1_000_000', () => {
+ it('marketplace_sale: 90/5/5 split is exact on 1_000_000', () => {
const legs = resolveSplitLegs('marketplace_sale', {
sellerWallet: 'So11111111111111111111111111111111111111112',
});
const result = applySplit(1_000_000n, legs);
- expect(result.find((l) => l.role === 'seller').atomics).toBe(950_000n);
+ expect(result.find((l) => l.role === 'seller').atomics).toBe(900_000n);
expect(result.find((l) => l.role === 'treasury').atomics).toBe(50_000n);
+ expect(result.find((l) => l.role === 'rewards').atomics).toBe(50_000n);
});
it('marketplace_sale: 95/5 split on odd total sums exactly', () => {
@@ -385,14 +417,16 @@ describe('issueQuote + verifyQuote', () => {
});
const sellerLeg = quote.legs.find((l) => l.role === 'seller');
const treasuryLeg = quote.legs.find((l) => l.role === 'treasury');
+ const rewardsLeg = quote.legs.find((l) => l.role === 'rewards');
expect(sellerLeg).toBeDefined();
expect(treasuryLeg).toBeDefined();
+ expect(rewardsLeg).toBeDefined();
expect(sellerLeg.address).toBe(seller);
- // seller gets 95%
+ // seller gets 90%
const sellerAtomics = BigInt(sellerLeg.atomics);
const total = BigInt(quote.total);
- expect(sellerAtomics * 100n).toBeGreaterThanOrEqual(total * 94n);
- expect(sellerAtomics * 100n).toBeLessThanOrEqual(total * 96n);
+ expect(sellerAtomics * 100n).toBeGreaterThanOrEqual(total * 89n);
+ expect(sellerAtomics * 100n).toBeLessThanOrEqual(total * 91n);
});
it('different quotes produce different nonces', async () => {
@@ -414,7 +448,7 @@ describe('issueQuote + verifyQuote', () => {
// ── On-chain verification ─────────────────────────────────────────────────────
describe('verifyOnChain', () => {
- const BURN_ADDR = '1nc1nerator11111111111111111111111111111111';
+ const REWARDS = 'RewardsXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const TREASURY = 'TreasuryXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const MEMO_PROGRAM = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';
const NONCE = 'test-nonce-abc123';
@@ -429,8 +463,8 @@ describe('verifyOnChain', () => {
mint: TOKEN_MINT,
total: '2000',
legs: legs ?? [
- { role: 'burn', address: BURN_ADDR, bps: 5000, atomics: '1000' },
{ role: 'treasury', address: TREASURY, bps: 5000, atomics: '1000' },
+ { role: 'rewards', address: REWARDS, bps: 5000, atomics: '1000' },
],
};
}
@@ -474,12 +508,12 @@ describe('verifyOnChain', () => {
});
it('rejects when a split leg receives less than required', async () => {
- // Only burn gets credited; treasury receives nothing → delta 0 < 1000 required
+ // Only treasury gets credited; rewards receives nothing → delta 0 < 1000 required
_mockTxResponse = makeTx({
postBalances: [
{
mint: TOKEN_MINT,
- owner: BURN_ADDR,
+ owner: TREASURY,
accountIndex: 0,
uiTokenAmount: { amount: '1000' },
},
@@ -495,13 +529,13 @@ describe('verifyOnChain', () => {
postBalances: [
{
mint: TOKEN_MINT,
- owner: BURN_ADDR,
+ owner: TREASURY,
accountIndex: 0,
uiTokenAmount: { amount: '1000' },
},
{
mint: TOKEN_MINT,
- owner: TREASURY,
+ owner: REWARDS,
accountIndex: 1,
uiTokenAmount: { amount: '1000' },
},
@@ -521,13 +555,13 @@ describe('verifyOnChain', () => {
postBalances: [
{
mint: TOKEN_MINT,
- owner: BURN_ADDR,
+ owner: TREASURY,
accountIndex: 0,
uiTokenAmount: { amount: '2000' },
},
{
mint: TOKEN_MINT,
- owner: TREASURY,
+ owner: REWARDS,
accountIndex: 1,
uiTokenAmount: { amount: '2000' },
},