Skip to content

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

feat: $THREE token allowance ops, buyback math, and x402 merchant updates

nirholas54da87d995d1
diff --git a/.env.example b/.env.example
index 6f7b5672c..f05728984 100644
--- a/.env.example
+++ b/.env.example
@@ -737,6 +737,33 @@ COIN_TREASURY_SECRET_KEY_B64=
# pay tx fees on behalf of the protocol. Distinct from TREASURY_KEYPAIR.
PUMP_CRON_RELAYER_SECRET_KEY_B64=
+# ── Programmatic $THREE buyback (revenue → Jupiter buy → treasury) ───────────
+# The run-three-buyback cron (daily) converts platform USDC revenue into onchain
+# $THREE buy pressure and routes the bought tokens to the treasury. Public proof
+# is rendered on /three-token. No platform burn — supply is never destroyed.
+#
+# Execution is OFF until both an opt-in flag AND a funded signer are set, so a
+# scheduled run is a recorded no-op until an operator deliberately enables it.
+THREE_BUYBACK_ENABLED=
+# Base64-encoded 64-byte Solana keypair that holds the buyback USDC and signs the
+# Jupiter buy. Fund this wallet with USDC (route platform revenue into it) to arm
+# buybacks. Pays its own SOL tx fees, so it's covered by the relayer-balance cron.
+THREE_BUYBACK_SECRET_KEY_B64=
+# PUBLISHED commitment: share of platform revenue (basis points) the protocol
+# commits to convert into $THREE buybacks. Rendered on the token page as the
+# holder-facing promise — policy, shown whether or not a run is enabled. Default
+# 5000 (50%), the conservative floor of the 50–80% band comparable fee-generating
+# protocols sustain (Hyperliquid ~79%, pump.fun ~50%). Raise to publish a bigger
+# commitment without a code change. 0–10000.
+THREE_BUYBACK_COMMIT_BPS=5000
+# Max USD a single run may deploy (bounds an over-funded sweep). Default 250.
+THREE_BUYBACK_MAX_USD=
+# Below this USD, a run is skipped so dust doesn't cost more in fees than it buys.
+# Default 10.
+THREE_BUYBACK_MIN_USD=
+# Jupiter slippage tolerance in basis points (0 < bps ≤ 5000). Default 300 (3%).
+THREE_BUYBACK_SLIPPAGE_BPS=
+
# Base58-encoded 64-byte Solana keypair for the agent that signs outbound
# x402 payments from /api/x402-pay. Leave unset if you only RECEIVE x402.
X402_AGENT_SOLANA_SECRET_BASE58=
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 87fcdcdf4..3af5e7ba3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,9 +6,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-21
+- **$THREE buyback commitment is now public and verifiable on the token page** — The $THREE page now leads with the protocol's buyback commitment — the fixed share of all platform revenue routed into buying $THREE on the open market and sending it to the treasury — shown as revenue earned, dollars committed, dollars deployed on-chain, and how much of the commitment has been kept. Every individual buyback is listed with a one-click Solscan receipt, so the promise is provable, not just stated. No burn: supply is never destroyed. (`/three-token`) `[feature]`
- **$THREE holder leaderboard loads faster from a shared snapshot** — The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces. (`/leaderboard`) `[improvement, infra]`
+- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice. (`/three-token`) `[feature]`
- **forge_avatar — one call turns a prompt into a rigged, animation-ready avatar** — A new forge_avatar MCP tool collapses the old two-step flow (generate a mesh, then rig it) into a single call: describe a character in text — or pass reference images — and it generates the textured model, auto-rigs it with a humanoid skeleton, and returns an animation-ready GLB that drops straight into the pose studio and plays the idle/walk library. A built-in humanoid check runs first, so a non-character prompt (furniture, a vehicle, an animal) is turned away with no charge instead of wasting a paid rig. It bundles generation and rigging at their combined price ($0.45) with no hidden markup, and you are never charged if no rigged avatar is produced. (`/docs/mcp`) `[sdk, feature]`
-- **Solana is now the default payment network** — The Default payment network setting in dashboard settings now defaults to Solana for every user, and Solana is listed first among the options. Base and Polygon remain available if you prefer an EVM chain. (`/dashboard`) `[improvement]`
+- **Solana is now the default payment network** — Solana is now the default everywhere you pick a chain — the dashboard's Default payment network setting, x402 merchant settlement, and the monetization payout wallet all default to Solana for every user, with Solana listed first. Base and Polygon remain available if you prefer an EVM chain. (`/dashboard`) `[improvement]`
## 2026-06-20
diff --git a/ISSUES.md b/ISSUES.md
index 63e5946fa..d6963470b 100644
--- a/ISSUES.md
+++ b/ISSUES.md
@@ -6,31 +6,16 @@ contain work that is still open.
> Archive of the 2026-05 incident batch (20 items, all resolved):
> [docs/internal/ISSUES-ARCHIVE-2026-05.md](docs/internal/ISSUES-ARCHIVE-2026-05.md)
+>
+> Archive of 2026-06 resolved items:
+> [docs/internal/ISSUES-ARCHIVE-2026-06.md](docs/internal/ISSUES-ARCHIVE-2026-06.md)
---
## Open
-### 1. `character-studio/` — pre-existing lint debt (added 2026-06-11)
+_No open production issues._
-**Context:** The eslint 8→10 upgrade migrated character-studio to flat config
-(`character-studio/eslint.config.mjs`). Lint surfaces pre-existing findings
-across the vendored CharacterStudio fork (118 `no-unused-vars`,
-17 `no-async-promise-executor`, plus smaller buckets). These all predate the
-upgrade.
-
-**Runtime `no-undef` bugs — FIXED 2026-06-18** (full table in
-[docs/internal/AUDIT-2026-06-18.md](docs/internal/AUDIT-2026-06-18.md)). Twelve
-references that threw `ReferenceError` the moment their code path ran are now
-corrected, verified by a clean `no-undef`-only eslint sweep over
-`character-studio/src` (zero runtime no-undef remaining):
-`manifestDataManager.js` (`testWallet` ×2, `identifier`, undeclared `traitOption`,
-`traitType`), `mint-utils.js` (`ethereum` literal + `connection` `try`/`catch`
-scope leak), `vrmManager.js` (`addChildAtFirst` import), `walletCollections.js`
-(`network` → `chainName`), `download-utils.js` (missing `optimized` destructure),
-`CharacterManifestData.js` (`getTraitByIndex` now takes `index`), `ktx.js`
-(`typeof LIBKTX` guard + `/* global */` directive).
-
-**Status:** ⏳ **OPEN** — only the cosmetic burndown remains: clear
-`no-unused-vars` and `no-async-promise-executor` mechanically, file by file.
-No known runtime bugs remain in the fork.
+The `character-studio/` lint debt (the last open item) was cleared 2026-06-21 —
+`eslint character-studio/src` now reports **0 problems**. Details in the
+[2026-06 archive](docs/internal/ISSUES-ARCHIVE-2026-06.md).
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 9713d1fbe..16dd23179 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -925,6 +925,16 @@ export const env = {
get THREE_QUOTE_SECRET() {
return opt('THREE_QUOTE_SECRET');
},
+ // Platform delegate keypair (base64 of a 64-byte secret key) for the $THREE
+ // spend-allowance rail (api/_lib/token/allowance.js). This is the `delegatee`
+ // users authorize via Solana's native Subscriptions program: once set + funded
+ // (it pays tx fees / receiver-ATA rent on pulls), paid actions can debit a
+ // holder's pre-approved cap with no per-action wallet popup. OPTIONAL — when
+ // unset, every charge cleanly falls back to the signed quote→settle flow, so
+ // the allowance fast path is strictly additive. NEVER log this value.
+ get THREE_ALLOWANCE_DELEGATE_SECRET_KEY_B64() {
+ return opt('THREE_ALLOWANCE_DELEGATE_SECRET_KEY_B64');
+ },
// Validity window (seconds) for an issued quote. Short enough that a quoted
// price can't be exploited after the market moves; long enough to sign + send
// one transaction. Default 90s.
diff --git a/api/_lib/pricing/charge-three.js b/api/_lib/pricing/charge-three.js
index 0d6448336..e4ee09a27 100644
--- a/api/_lib/pricing/charge-three.js
+++ b/api/_lib/pricing/charge-three.js
@@ -16,7 +16,13 @@
// 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 {
+ issueQuote,
+ verifyAndSettlePayment,
+ allowanceEnabled,
+ pullFromAllowance,
+ recordAllowancePayment,
+} from '../token/index.js';
import { catalogEntry, priceForAction, POLICY } from './catalog.js';
// Surfaces that are free forever (the growth funnel). These are NOT catalog
@@ -141,6 +147,45 @@ export async function requireThreePayment({
refId,
});
+ // Allowance fast path: if the user pre-authorized a $THREE spend cap (Solana
+ // native Subscriptions program) and the platform delegate is configured, pull
+ // the charge with NO wallet popup — same price, same split legs, same on-chain
+ // record. Any miss (no allowance, cap too low, degraded RPC) falls through to
+ // the signed quote below, so this is strictly additive and never blocks a pay.
+ const payerWallet = user?.wallet_address ?? null;
+ if (payerWallet && (await allowanceEnabled())) {
+ try {
+ const pull = await pullFromAllowance({ userWallet: payerWallet, legs: quote.legs, network });
+ const record = await recordAllowancePayment({
+ quote,
+ txSignature: pull.signature,
+ network,
+ payerWallet,
+ userId: user?.id ?? null,
+ slot: pull.slot,
+ });
+ return {
+ paid: true,
+ via: 'allowance',
+ payment: {
+ payment_id: record.id,
+ replay: record.replay,
+ tx_signature: pull.signature,
+ total_atomics: quote.total,
+ legs: quote.legs,
+ slot: pull.slot,
+ },
+ };
+ } catch (err) {
+ // insufficient_allowance is the expected "not enough cap" signal — fall
+ // back silently. Anything else, log once and still fall back so a flaky
+ // allowance path can never strand a user who could pay the normal way.
+ if (err?.code !== 'insufficient_allowance') {
+ console.warn(`[charge-three] allowance pull failed for ${action}, falling back to quote:`, err?.message || err);
+ }
+ }
+ }
+
return {
paid: false,
quote: {
diff --git a/api/_lib/token/allowance-ops.js b/api/_lib/token/allowance-ops.js
new file mode 100644
index 000000000..2da54d325
--- /dev/null
+++ b/api/_lib/token/allowance-ops.js
@@ -0,0 +1,261 @@
+// $THREE allowance — chain operations (read status, build grant, execute pull).
+//
+// Pure encodings live in ./allowance.js (unit-tested). This module is the thin
+// RPC/signing shell: it talks to Solana to read a user's remaining allowance,
+// assemble the one-signature grant transaction, and — with the platform delegate
+// key — pull a charge across split legs without a user popup.
+
+import { PublicKey, Transaction } from '@solana/web3.js';
+import {
+ createAssociatedTokenAccountIdempotentInstruction,
+ TOKEN_2022_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+import { solanaConnection } from '../solana/connection.js';
+import { TOKEN_MINT, ATOMICS_PER_TOKEN } from './config.js';
+import {
+ SUBSCRIPTIONS_PROGRAM_ID,
+ subscriptionAuthorityPda,
+ fixedDelegationPda,
+ userThreeAta,
+ ixInitSubscriptionAuthority,
+ ixCreateFixedDelegation,
+ ixTransferFixed,
+ parseSubscriptionAuthorityInitId,
+ parseFixedDelegation,
+ loadDelegateKeypair,
+ delegateAddress,
+} from './allowance.js';
+
+const mintPubkey = () => new PublicKey(TOKEN_MINT);
+const nowSec = () => Math.floor(Date.now() / 1000);
+
+function conn(network = 'mainnet') {
+ return solanaConnection({ network });
+}
+
+/** A delegation is spendable when it has remaining balance and is not past expiry (0 = no expiry). */
+function isLive(d, now = nowSec()) {
+ return d.remaining > 0n && (d.expiryTs <= 0 || d.expiryTs > now);
+}
+
+/**
+ * Read every active fixed delegation the user has granted to the platform delegate.
+ * Returns the parsed, still-live ones (largest remaining first) plus the aggregate.
+ */
+export async function getAllowanceStatus(userWallet, { network = 'mainnet' } = {}) {
+ const delegate = await delegateAddress();
+ if (!delegate) {
+ return { enabled: false, delegate: null, remaining_atomics: '0', delegations: [] };
+ }
+
+ const connection = conn(network);
+ let accounts = [];
+ try {
+ accounts = await connection.getProgramAccounts(SUBSCRIPTIONS_PROGRAM_ID, {
+ filters: [
+ { dataSize: 187 },
+ { memcmp: { offset: 3, bytes: new PublicKey(userWallet).toBase58() } },
+ { memcmp: { offset: 35, bytes: delegate } },
+ ],
+ });
+ } catch (err) {
+ // Read path: never throw — a degraded RPC simply shows "no allowance" and the
+ // caller falls back to the signed quote flow.
+ console.warn('[allowance] getProgramAccounts failed:', err?.message || err);
+ return { enabled: true, delegate, remaining_atomics: '0', delegations: [], degraded: true };
+ }
+
+ const now = nowSec();
+ const delegations = accounts
+ .map(({ pubkey, account }) => {
+ const parsed = parseFixedDelegation(account.data);
+ return parsed ? { pubkey: pubkey.toBase58(), ...parsed } : null;
+ })
+ .filter((d) => d && isLive(d, now))
+ .sort((a, b) => (b.remaining > a.remaining ? 1 : b.remaining < a.remaining ? -1 : 0));
+
+ const totalRemaining = delegations.reduce((s, d) => s + d.remaining, 0n);
+ return {
+ enabled: true,
+ delegate,
+ remaining_atomics: totalRemaining.toString(),
+ remaining_tokens: Number(totalRemaining) / Number(ATOMICS_PER_TOKEN),
+ delegations: delegations.map((d) => ({
+ pubkey: d.pubkey,
+ remaining_atomics: d.remaining.toString(),
+ expiry_ts: d.expiryTs,
+ })),
+ };
+}
+
+/**
+ * Build the user-signed GRANT transaction: initialize the Subscription Authority
+ * if absent, then create a fixed delegation for `capAtomics` until `expiryTs`.
+ * Returns the unsigned tx (base64), the delegation PDA, and the chosen nonce.
+ */
+export async function buildGrantTransaction({
+ userWallet,
+ capAtomics,
+ expiryTs = 0,
+ network = 'mainnet',
+}) {
+ const delegate = await delegateAddress();
+ if (!delegate) {
+ throw Object.assign(new Error('allowance delegate not configured'), {
+ status: 503,
+ code: 'allowance_unavailable',
+ });
+ }
+
+ const owner = new PublicKey(userWallet);
+ const mint = mintPubkey();
+ const sa = subscriptionAuthorityPda(owner, mint);
+ const connection = conn(network);
+
+ const instructions = [];
+ let expectedInitId;
+ const saInfo = await connection.getAccountInfo(sa, 'confirmed');
+ if (!saInfo) {
+ instructions.push(ixInitSubscriptionAuthority({ owner, mint }));
+ // Fresh SA: the program stamps init-id = on-chain clock; our current second
+ // is within TIME_DRIFT_ALLOWED_SECS so createFixedDelegation accepts it.
+ expectedInitId = nowSec();
+ } else {
+ expectedInitId = parseSubscriptionAuthorityInitId(saInfo.data);
+ if (expectedInitId == null) {
+ throw Object.assign(new Error('unreadable subscription authority'), {
+ status: 422,
+ code: 'sa_unreadable',
+ });
+ }
+ }
+
+ const nonce = nowSec();
+ instructions.push(
+ ixCreateFixedDelegation({
+ delegator: owner,
+ delegatee: new PublicKey(delegate),
+ nonce,
+ amount: BigInt(capAtomics),
+ expiryTs: Math.floor(expiryTs) || 0,
+ expectedInitId,
+ mint,
+ }),
+ );
+
+ const { blockhash } = await connection.getLatestBlockhash('confirmed');
+ const tx = new Transaction();
+ tx.add(...instructions);
+ tx.feePayer = owner;
+ tx.recentBlockhash = blockhash;
+
+ const serialized = tx
+ .serialize({ requireAllSignatures: false, verifySignatures: false })
+ .toString('base64');
+
+ return {
+ transaction: serialized,
+ delegation_pda: fixedDelegationPda({
+ subscriptionAuthority: sa,
+ delegator: owner,
+ delegatee: new PublicKey(delegate),
+ nonce,
+ }).toBase58(),
+ nonce,
+ recent_blockhash: blockhash,
+ };
+}
+
+/**
+ * Pull `legs` (each { address, atomics }) from the user's wallet against an
+ * existing allowance, in a single delegate-signed transaction — no user popup.
+ *
+ * Honors the exact split the quote path would: one transferFixed per leg, each
+ * decrementing the same delegation. Returns { signature, ... } on success.
+ *
+ * Throws code 'insufficient_allowance' when no single live delegation covers the
+ * total — the caller treats that as "fall back to the signed quote flow".
+ */
+export async function pullFromAllowance({ userWallet, legs, network = 'mainnet' }) {
+ const delegate = await loadDelegateKeypair();
+ if (!delegate) {
+ throw Object.assign(new Error('allowance delegate not configured'), {
+ status: 503,
+ code: 'allowance_unavailable',
+ });
+ }
+
+ const total = legs.reduce((s, l) => s + BigInt(l.atomics), 0n);
+ if (total <= 0n) {
+ throw Object.assign(new Error('nothing to charge'), { status: 400, code: 'zero_charge' });
+ }
+
+ const status = await getAllowanceStatus(userWallet, { network });
+ // Pick the single delegation that covers the whole charge (legs share one cap).
+ const covering = status.delegations.find((d) => BigInt(d.remaining_atomics) >= total);
+ if (!covering) {
+ throw Object.assign(
+ new Error('no active allowance covers this charge'),
+ { status: 402, code: 'insufficient_allowance', remaining_atomics: status.remaining_atomics },
+ );
+ }
+
+ const owner = new PublicKey(userWallet);
+ const mint = mintPubkey();
+ const connection = conn(network);
+ const tx = new Transaction();
+
+ for (const leg of legs) {
+ const receiver = new PublicKey(leg.address);
+ // Idempotent: fund the receiver ATA's rent on first use (delegate is fee payer).
+ tx.add(
+ createAssociatedTokenAccountIdempotentInstruction(
+ delegate.publicKey,
+ userThreeAta(receiver, mint),
+ receiver,
+ mint,
+ TOKEN_2022_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ ),
+ );
+ tx.add(
+ ixTransferFixed({
+ delegationPda: covering.pubkey,
+ delegator: owner,
+ delegatee: delegate.publicKey,
+ receiver,
+ amount: BigInt(leg.atomics),
+ mint,
+ }),
+ );
+ }
+
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
+ tx.feePayer = delegate.publicKey;
+ tx.recentBlockhash = blockhash;
+ tx.sign(delegate);
+
+ const signature = await connection.sendRawTransaction(tx.serialize(), {
+ skipPreflight: false,
+ maxRetries: 3,
+ });
+ const confirmation = await connection.confirmTransaction(
+ { signature, blockhash, lastValidBlockHeight },
+ 'confirmed',
+ );
+ if (confirmation.value?.err) {
+ throw Object.assign(new Error('allowance pull failed on-chain'), {
+ status: 502,
+ code: 'pull_failed',
+ detail: confirmation.value.err,
+ });
+ }
+
+ return {
+ signature,
+ delegation_pda: covering.pubkey,
+ total_atomics: total.toString(),
+ slot: confirmation.context?.slot ?? null,
+ };
+}
diff --git a/api/_lib/token/allowance.js b/api/_lib/token/allowance.js
new file mode 100644
index 000000000..ff8c62dd1
--- /dev/null
+++ b/api/_lib/token/allowance.js
@@ -0,0 +1,271 @@
+// $THREE spend allowances — frictionless, NON-CUSTODIAL pay-from-wallet.
+//
+// Built on Solana's native, audited Subscriptions & Allowances program
+// (solana-program/subscriptions, program De1egAFMkMWZSN5rYXRj9CAdheBamobVNubTsi9avR44,
+// live on mainnet June 2026). It solves the one-delegate-per-token-account limit
+// by making a per-(user,mint) Subscription Authority PDA the sole SPL delegate
+// (u64::MAX approval) and gating every pull through individual Delegation PDAs.
+//
+// Why this instead of a custodial credit balance: funds NEVER leave the user's
+// wallet until a charge pulls them, the user sets the cap (and revokes anytime),
+// and three.ws holds nothing. One signature authorizes a spend cap; after that,
+// paid actions debit with no popup — the platform's delegate key pulls up to the
+// remaining cap, and the program rejects anything over it.
+//
+// Two flows:
+// GRANT (user signs once) — initSubscriptionAuthority (first time) +
+// createFixedDelegation(cap, expiry). buildGrantInstructions().
+// PULL (delegate signs, no user popup) — one transferFixed per split leg,
+// honoring the exact same treasury/rewards/seller split as the
+// on-chain quote path. pullFromAllowance().
+//
+// $THREE is a Token-2022 mint with only metadataPointer + tokenMetadata
+// extensions (no transfer hook / fee / permanent-delegate), so it is compatible
+// with the program, which rejects hook/fee mints. All ATAs and token accounts
+// here use the Token-2022 program id accordingly.
+//
+// Encodings (discriminators, PDA seeds, struct layouts, account offsets) are
+// taken verbatim from the program's published IDL (idl/subscriptions.json) and
+// covered by tests/token-allowance.test.js so a drift in any constant fails CI.
+
+import { PublicKey, TransactionInstruction, SystemProgram } from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ createAssociatedTokenAccountIdempotentInstruction,
+ TOKEN_2022_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+import { env } from '../env.js';
+import { TOKEN_MINT } from './config.js';
+
+// ── Program constants ────────────────────────────────────────────────────────
+
+/** Native Subscriptions & Allowances program (mainnet + devnet, audited by Cantina). */
+export const SUBSCRIPTIONS_PROGRAM_ID = new PublicKey(
+ 'De1egAFMkMWZSN5rYXRj9CAdheBamobVNubTsi9avR44',
+);
+
+// Instruction discriminators (single leading u8 — see IDL). Only the three we use.
+const IX_INIT_SUBSCRIPTION_AUTHORITY = 0;
+const IX_CREATE_FIXED_DELEGATION = 1;
+const IX_TRANSFER_FIXED = 4;
+
+// On-chain account byte layouts (from the IDL `accounts` definitions). The
+// program writes these little-endian; we read remaining-balance / init-id back.
+const SA_INIT_ID_OFFSET = 98; // discriminator(1)+user(32)+mint(32)+payer(32)+bump(1)
+const DELEGATION_DATA_SIZE = 187;
+const DELEGATION_DELEGATOR_OFFSET = 3; // header: discriminator(1)+version(1)+bump(1)
+const DELEGATION_DELEGATEE_OFFSET = 35;
+const DELEGATION_AMOUNT_OFFSET = 171; // remaining allowance (decremented per transfer)
+const DELEGATION_EXPIRY_OFFSET = 179;
+
+// createFixedDelegation validates the caller-supplied SA init-id against the
+// authority's stored init-id within this drift, so a fresh same-tx create can
+// pass the current clock. Mirrors the program's TIME_DRIFT_ALLOWED_SECS.
+const TIME_DRIFT_ALLOWED_SECS = 120;
+
+const mintPubkey = () => new PublicKey(TOKEN_MINT);
+
+// ── Little-endian scalar encoders ────────────────────────────────────────────
+
+function u64le(value) {
+ const buf = Buffer.alloc(8);
+ buf.writeBigUInt64LE(BigInt(value));
+ return buf;
+}
+
+function i64le(value) {
+ const buf = Buffer.alloc(8);
+ buf.writeBigInt64LE(BigInt(value));
+ return buf;
+}
+
+// ── PDA derivation ───────────────────────────────────────────────────────────
+
+/** Per-(user,mint) Subscription Authority — the single SPL delegate on the user's ATA. */
+export function subscriptionAuthorityPda(user, mint = mintPubkey()) {
+ return PublicKey.findProgramAddressSync(
+ [Buffer.from('SubscriptionAuthority'), new PublicKey(user).toBuffer(), new PublicKey(mint).toBuffer()],
+ SUBSCRIPTIONS_PROGRAM_ID,
+ )[0];
+}
+
+/** A specific spend cap from `delegator` to `delegatee`, keyed by an arbitrary nonce. */
+export function fixedDelegationPda({ subscriptionAuthority, delegator, delegatee, nonce }) {
+ return PublicKey.findProgramAddressSync(
+ [
+ Buffer.from('delegation'),
+ new PublicKey(subscriptionAuthority).toBuffer(),
+ new PublicKey(delegator).toBuffer(),
+ new PublicKey(delegatee).toBuffer(),
+ u64le(nonce),
+ ],
+ SUBSCRIPTIONS_PROGRAM_ID,
+ )[0];
+}
+
+/** Event-authority PDA the program emits CPI events through (read-only meta on transfers). */
+export function eventAuthorityPda() {
+ return PublicKey.findProgramAddressSync([Buffer.from('event_authority')], SUBSCRIPTIONS_PROGRAM_ID)[0];
+}
+
+/** The user's Token-2022 $THREE associated token account. */
+export function userThreeAta(owner, mint = mintPubkey()) {
+ return getAssociatedTokenAddressSync(
+ new PublicKey(mint),
+ new PublicKey(owner),
+ true, // allowOwnerOffCurve — receivers (e.g. incinerator) may be off-curve
+ TOKEN_2022_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+}
+
+// ── Instruction builders ─────────────────────────────────────────────────────
+
+/** initSubscriptionAuthority (disc 0) — first-time setup; registers the SA as delegate. */
+export function ixInitSubscriptionAuthority({ owner, mint = mintPubkey() }) {
+ const ownerPk = new PublicKey(owner);
+ const sa = subscriptionAuthorityPda(ownerPk, mint);
+ return new TransactionInstruction({
+ programId: SUBSCRIPTIONS_PROGRAM_ID,
+ keys: [
+ { pubkey: ownerPk, isSigner: true, isWritable: true },
+ { pubkey: sa, isSigner: false, isWritable: true },
+ { pubkey: new PublicKey(mint), isSigner: false, isWritable: false },
+ { pubkey: userThreeAta(ownerPk, mint), isSigner: false, isWritable: true },
+ { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
+ { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },
+ ],
+ data: Buffer.from([IX_INIT_SUBSCRIPTION_AUTHORITY]),
+ });
+}
+
+/** createFixedDelegation (disc 1) — authorize `delegatee` to pull up to `amount` until `expiryTs`. */
+export function ixCreateFixedDelegation({
+ delegator,
+ delegatee,
+ nonce,
+ amount,
+ expiryTs,
+ expectedInitId,
+ mint = mintPubkey(),
+}) {
+ const delegatorPk = new PublicKey(delegator);
+ const delegateePk = new PublicKey(delegatee);
+ const sa = subscriptionAuthorityPda(delegatorPk, mint);
+ const delegation = fixedDelegationPda({
+ subscriptionAuthority: sa,
+ delegator: delegatorPk,
+ delegatee: delegateePk,
+ nonce,
+ });
+ const data = Buffer.concat([
+ Buffer.from([IX_CREATE_FIXED_DELEGATION]),
+ u64le(nonce),
+ u64le(amount),
+ i64le(expiryTs),
+ i64le(expectedInitId),
+ ]);
+ return new TransactionInstruction({
+ programId: SUBSCRIPTIONS_PROGRAM_ID,
+ keys: [
+ { pubkey: delegatorPk, isSigner: true, isWritable: true },
+ { pubkey: sa, isSigner: false, isWritable: false },
+ { pubkey: delegation, isSigner: false, isWritable: true },
+ { pubkey: delegateePk, isSigner: false, isWritable: false },
+ { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },
+ ],
+ data,
+ });
+}
+
+/** transferFixed (disc 4) — delegate pulls `amount` from the user to `receiver`, decrementing the cap. */
+export function ixTransferFixed({ delegationPda, delegator, delegatee, receiver, amount, mint = mintPubkey() }) {
+ const mintPk = new PublicKey(mint);
+ const delegatorPk = new PublicKey(delegator);
+ const delegateePk = new PublicKey(delegatee);
+ const sa = subscriptionAuthorityPda(delegatorPk, mintPk);
+ const data = Buffer.concat([
+ Buffer.from([IX_TRANSFER_FIXED]),
+ u64le(amount),
+ delegatorPk.toBuffer(),
+ mintPk.toBuffer(),
+ ]);
+ return new TransactionInstruction({
+ programId: SUBSCRIPTIONS_PROGRAM_ID,
+ keys: [
+ { pubkey: new PublicKey(delegationPda), isSigner: false, isWritable: true },
+ { pubkey: sa, isSigner: false, isWritable: false },
+ { pubkey: userThreeAta(delegatorPk, mintPk), isSigner: false, isWritable: true },
+ { pubkey: userThreeAta(receiver, mintPk), isSigner: false, isWritable: true },
+ { pubkey: mintPk, isSigner: false, isWritable: false },
+ { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },
+ { pubkey: delegateePk, isSigner: true, isWritable: false },
+ { pubkey: eventAuthorityPda(), isSigner: false, isWritable: false },
+ { pubkey: SUBSCRIPTIONS_PROGRAM_ID, isSigner: false, isWritable: false },
+ ],
+ data,
+ });
+}
+
+// ── Account-state parsers ────────────────────────────────────────────────────
+
+/** Read the Subscription Authority's stored init-id (i64), or null when uninitialized. */
+export function parseSubscriptionAuthorityInitId(data) {
+ if (!data || data.length < SA_INIT_ID_OFFSET + 8) return null;
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
+ return Number(buf.readBigInt64LE(SA_INIT_ID_OFFSET));
+}
+
+/** Decode a fixed-delegation account: remaining allowance, expiry, and parties. */
+export function parseFixedDelegation(data) {
+ if (!data || data.length < DELEGATION_DATA_SIZE) return null;
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
+ return {
+ delegator: new PublicKey(buf.subarray(DELEGATION_DELEGATOR_OFFSET, DELEGATION_DELEGATOR_OFFSET + 32)).toBase58(),
+ delegatee: new PublicKey(buf.subarray(DELEGATION_DELEGATEE_OFFSET, DELEGATION_DELEGATEE_OFFSET + 32)).toBase58(),
+ remaining: buf.readBigUInt64LE(DELEGATION_AMOUNT_OFFSET),
+ expiryTs: Number(buf.readBigInt64LE(DELEGATION_EXPIRY_OFFSET)),
+ };
+}
+
+// ── Delegate (relayer) key ───────────────────────────────────────────────────
+
+let _delegateKeypair;
+let _delegateLoadFailed = false;
+
+/**
+ * The platform's allowance delegate keypair (the `delegatee` users authorize).
+ * Loaded from THREE_ALLOWANCE_DELEGATE_SECRET_KEY_B64 (base64 of a 64-byte secret
+ * key). Returns null when unconfigured — every pull path then falls back to the
+ * on-chain quote→settle flow, so the feature is safe-by-default: nothing can move
+ * funds until an operator funds + configures this key.
+ */
+export async function loadDelegateKeypair() {
+ if (_delegateKeypair || _delegateLoadFailed) return _delegateKeypair ?? null;
+ const b64 = env.THREE_ALLOWANCE_DELEGATE_SECRET_KEY_B64;
+ if (!b64) {
+ _delegateLoadFailed = true;
+ return null;
+ }
+ try {
+ const { Keypair } = await import('@solana/web3.js');
+ _delegateKeypair = Keypair.fromSecretKey(Buffer.from(b64, 'base64'));
+ return _delegateKeypair;
+ } catch (err) {
+ _delegateLoadFailed = true;
+ console.error('[allowance] invalid THREE_ALLOWANCE_DELEGATE_SECRET_KEY_B64:', err?.message || err);
+ return null;
+ }
+}
+
+/** Public base58 address of the delegate, or null when unconfigured. */
+export async function delegateAddress() {
+ const kp = await loadDelegateKeypair();
+ return kp ? kp.publicKey.toBase58() : null;
+}
+
+/** True when the allowance rail is operational (a delegate key is configured). */
+export async function allowanceEnabled() {
+ return (await loadDelegateKeypair()) != null;
+}
diff --git a/api/_lib/token/buyback-math.js b/api/_lib/token/buyback-math.js
index 63566365f..e72439ba4 100644
--- a/api/_lib/token/buyback-math.js
+++ b/api/_lib/token/buyback-math.js
@@ -20,6 +20,13 @@ export function envSlippageBps(raw, fallback = 300) {
return Number.isFinite(n) && n > 0 && n <= 5000 ? Math.round(n) : fallback;
}
+/** Parse a commitment-bps env value in [0, 10000], else fallback. */
+export function envBps(raw, fallback) {
+ if (raw === undefined || String(raw).trim() === '') return fallback;
+ const n = Number(raw);
+ return Number.isFinite(n) && n >= 0 && n <= 10_000 ? Math.round(n) : fallback;
+}
+
/** Whole USD → USDC atomics (6dp), floored. */
export function usdToUsdcAtomics(usd) {
return BigInt(Math.floor(Number(usd) * Number(USDC_ATOMICS)));
@@ -60,3 +67,26 @@ export function deployedPct(deployedUsd, revenueUsd) {
if (!(revenueUsd > 0)) return 0;
return Math.min(100, (deployedUsd / revenueUsd) * 100);
}
+
+/**
+ * USD the protocol has *committed* to convert into $THREE buybacks: the published
+ * commitment (commitBps) applied to lifetime revenue. This is the promise — the
+ * dollar target that on-chain buys are measured against — not what's been deployed.
+ */
+export function committedUsd(revenueUsd, commitBps) {
+ const rev = Number(revenueUsd);
+ const bps = Number(commitBps);
+ if (!(rev > 0) || !(bps > 0)) return 0;
+ return rev * (bps / 10_000);
+}
+
+/**
+ * Share of the *commitment* actually deployed on-chain, clamped to [0,100]. 100%
+ * means every committed dollar of revenue has already been converted to buy
+ * pressure; this is the honest "are we keeping the promise" figure, distinct from
+ * deployedPct (share of *all* revenue).
+ */
+export function commitmentProgressPct(deployedUsd, committedUsdTarget) {
+ if (!(committedUsdTarget > 0)) return 0;
+ return Math.min(100, (Number(deployedUsd) / Number(committedUsdTarget)) * 100);
+}
diff --git a/api/_lib/token/buyback.js b/api/_lib/token/buyback.js
index c0c609fb7..412173c88 100644
--- a/api/_lib/token/buyback.js
+++ b/api/_lib/token/buyback.js
@@ -31,6 +31,9 @@ import { treasuryWallet, treasuryWalletOrNull } from './config.js';
import {
computeSpend,
deployedPct,
+ committedUsd,
+ commitmentProgressPct,
+ envBps,
envSlippageBps,
envUsd,
usdcAtomicsToUsd as usdcToUsd,
@@ -53,6 +56,19 @@ export function maxUsdPerRun() {
return envUsd(process.env.THREE_BUYBACK_MAX_USD, 250);
}
+/**
+ * The PUBLISHED commitment: share of platform revenue the protocol commits to
+ * convert into $THREE buybacks, in basis points (default 5000 = 50%). This is the
+ * holder-facing promise rendered on the token page; it is policy, independent of
+ * whether a given run is enabled or funded. Operators tune the published number via
+ * THREE_BUYBACK_COMMIT_BPS without a code change. The data on comparable
+ * fee-generating protocols puts the credible band at 50–80%; we default to the
+ * conservative floor so the platform over-delivers rather than over-promises.
+ */
+export function commitBps() {
+ return envBps(process.env.THREE_BUYBACK_COMMIT_BPS, 5000);
+}
+
/** Below this, a run is skipped so dust doesn't pay more in fees than it buys. */
export function minUsdPerRun() {
return envUsd(process.env.THREE_BUYBACK_MIN_USD, 10);
@@ -311,7 +327,7 @@ export async function revenueFeeAtomicsToDate() {
* deployed into $THREE buybacks, $THREE accumulated, and the latest run.
*/
export async function buybackStats() {
- const [agg, lastRow, revenueAtomics] = await Promise.all([
+ const [agg, recentRows, revenueAtomics] = await Promise.all([
safeQuery(
() => sql`
select
@@ -323,13 +339,16 @@ export async function buybackStats() {
`,
[{ usdc_spent: 0, three_bought: 0, runs: 0 }],
),
+ // The verifiable receipt list: every recent confirmed buy with its on-chain
+ // signature, so the token page can render "each buyback, clickable to Solscan"
+ // — proof, not a claim. Capped so the public payload stays small.
safeQuery(
() => sql`
- select status, usdc_spent_atomics, three_bought_atomics, price_usd, buy_signature, created_at
+ select usdc_spent_atomics, three_bought_atomics, price_usd, buy_signature, created_at
from three_buyback_runs
where status = 'confirmed'
order by created_at desc
- limit 1
+ limit 10
`,
[],
),
@@ -340,25 +359,35 @@ export async function buybackStats() {
const threeBought = BigInt(agg[0]?.three_bought ?? 0);
const revenueUsd = usd(revenueAtomics);
const deployedUsd = usd(usdcSpent);
- const last = lastRow[0] || null;
+
+ const recent = recentRows.map((r) => ({
+ at: r.created_at,
+ usdc: usd(r.usdc_spent_atomics),
+ three: threeTokens(r.three_bought_atomics),
+ price_usd: r.price_usd != null ? Number(r.price_usd) : null,
+ signature: r.buy_signature,
+ }));
+
+ // The published commitment (policy) and how much of it has been honored on-chain.
+ const bps = commitBps();
+ const committed = committedUsd(revenueUsd, bps);
return {
enabled: isEnabled(),
+ // Published promise: share of revenue committed to buybacks (policy, always shown).
+ commit_bps: bps,
+ commit_pct: bps / 100,
+ committed_usd: committed,
+ // Share of the *commitment* already converted to buy pressure (keeping the promise).
+ commitment_progress_pct: commitmentProgressPct(deployedUsd, committed),
revenue_usd: revenueUsd,
deployed_usd: deployedUsd,
- // Share of platform revenue already converted to onchain buy pressure.
+ // Share of total platform revenue already converted to onchain buy pressure.
deployed_pct: deployedPct(deployedUsd, revenueUsd),
three_bought: threeTokens(threeBought),
runs: agg[0]?.runs ?? 0,
- last_run: last
- ? {
- at: last.created_at,
- usdc: usd(last.usdc_spent_atomics),
- three: threeTokens(last.three_bought_atomics),
- price_usd: last.price_usd != null ? Number(last.price_usd) : null,
- signature: last.buy_signature,
- }
- : null,
+ recent_runs: recent,
+ last_run: recent[0] || null,
};
}
diff --git a/api/_lib/token/index.js b/api/_lib/token/index.js
index b01822111..4b580c46c 100644
--- a/api/_lib/token/index.js
+++ b/api/_lib/token/index.js
@@ -15,6 +15,7 @@ export {
verifyOnChain,
settlePayment,
verifyAndSettlePayment,
+ recordAllowancePayment,
listPayments,
creatorEarnings,
economyStats,
@@ -22,3 +23,5 @@ export {
listRewardsDistributions,
} from './payments.js';
export { computeRewardsDistribution } from './rewards.js';
+export { allowanceEnabled, delegateAddress } from './allowance.js';
+export { getAllowanceStatus, buildGrantTransaction, pullFromAllowance } from './allowance-ops.js';
diff --git a/api/_lib/token/payments.js b/api/_lib/token/payments.js
index 9d4b152a6..6e633c130 100644
--- a/api/_lib/token/payments.js
+++ b/api/_lib/token/payments.js
@@ -100,6 +100,45 @@ function isUniqueViolation(err) {
return err?.code === '23505' || /duplicate key|unique constraint/i.test(err?.message || '');
}
+/**
+ * Record a $THREE allowance pull as a settled payment, in the exact same
+ * token_payments shape as settlePayment(). The allowance rail (Solana native
+ * Subscriptions program) pulls funds with the platform delegate key instead of a
+ * user-signed quote tx, but the economic record is identical — same purpose,
+ * mint, split legs, and on-chain signature — so economy stats and creator
+ * earnings (which match the `seller` split leg) stay consistent across both rails.
+ *
+ * Uses the issued quote's nonce as the unique key (the quote was priced normally;
+ * only its settlement path differs), so a double-submit is caught by the same
+ * UNIQUE(nonce)/UNIQUE(tx_signature) guard.
+ */
+export async function recordAllowancePayment({ quote, txSignature, network, payerWallet, userId, slot = null }) {
+ try {
+ const [row] = await sql`
+ insert into token_payments
+ (user_id, payer_wallet, purpose, mint, decimals, usd, price_usd,
+ total_atomics, splits, nonce, tx_signature, network, slot, ref_type, ref_id, confirmed_at)
+ values
+ (${userId ?? null}, ${payerWallet ?? null}, ${quote.purpose}, ${quote.mint}, ${quote.decimals},
+ ${quote.usd}, ${quote.priceUsd}, ${quote.total}, ${JSON.stringify(quote.legs)}::jsonb,
+ ${quote.nonce}, ${txSignature}, ${network}, ${slot},
+ ${quote.refType ?? null}, ${quote.refId ?? null}, now())
+ returning id, created_at
+ `;
+ return { id: row.id, replay: false, created_at: row.created_at };
+ } catch (err) {
+ if (isUniqueViolation(err)) {
+ const [existing] = await sql`
+ select id, created_at from token_payments
+ where nonce = ${quote.nonce} or tx_signature = ${txSignature}
+ limit 1
+ `;
+ return { id: existing?.id ?? null, replay: true, created_at: existing?.created_at ?? null };
+ }
+ throw err;
+ }
+}
+
/**
* Record a verified payment. Returns { id, replay, created_at }. A duplicate
* nonce or tx_signature resolves to { replay: true } (the prior settled row).
diff --git a/api/three-token/[action].js b/api/three-token/[action].js
index 44b5b6af5..23c261fd0 100644
--- a/api/three-token/[action].js
+++ b/api/three-token/[action].js
@@ -133,13 +133,20 @@ export default wrap(async (req, res) => {
agent_deploy_burn: AGENT_DEPLOY_BURN,
},
// Revenue converted to onchain buy pressure — programmatic, no burn.
+ // Commitment fields mirror buybackStats() so the page renders the
+ // published promise even on a transient stats failure.
buyback: buyback ?? {
enabled: false,
+ commit_bps: 5000,
+ commit_pct: 50,
+ committed_usd: 0,
+ commitment_progress_pct: 0,
revenue_usd: 0,
deployed_usd: 0,
deployed_pct: 0,
three_bought: 0,
runs: 0,
+ recent_runs: [],
last_run: null,
},
},
diff --git a/api/token/[action].js b/api/token/[action].js
index d5f40fc91..f5e9200a1 100644
--- a/api/token/[action].js
+++ b/api/token/[action].js
@@ -17,9 +17,16 @@ import { getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { parse } from '../_lib/validate.js';
-import { publicConfig } from '../_lib/token/config.js';
+import { publicConfig, ATOMICS_PER_TOKEN } from '../_lib/token/config.js';
import { getTokenPriceUsd, quoteTokenForUsd } from '../_lib/token/price.js';
-import { issueQuote, verifyAndSettlePayment, listPayments } from '../_lib/token/index.js';
+import {
+ issueQuote,
+ verifyAndSettlePayment,
+ listPayments,
+ getAllowanceStatus,
+ buildGrantTransaction,
+ delegateAddress,
+} from '../_lib/token/index.js';
// Allowlisted purposes for the generic quote endpoint. Each maps to a split
// policy and a sanity ceiling so this surface can't be used to mint an absurd
@@ -179,6 +186,85 @@ async function handleSettle(req, res) {
});
}
+// ── GET /api/token/allowance-status ──────────────────────────────────────────
+//
+// The signed-in holder's live $THREE spend allowance (remaining cap they've
+// pre-authorized to the platform delegate). Powers the wallet panel's "frictionless
+// spend" state and the decision to skip a wallet popup on the next paid action.
+
+async function handleAllowanceStatus(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const delegate = await delegateAddress();
+ if (!delegate) {
+ return json(res, 200, { enabled: false, delegate: null, remaining_atomics: '0', delegations: [] });
+ }
+ if (!user.wallet_address) {
+ return json(res, 200, { enabled: true, delegate, wallet: null, remaining_atomics: '0', delegations: [] });
+ }
+
+ const url = new URL(req.url, 'http://x');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const status = await getAllowanceStatus(user.wallet_address, { network });
+ return json(res, 200, { wallet: user.wallet_address, ...status });
+}
+
+// ── POST /api/token/allowance-grant ──────────────────────────────────────────
+//
+// Build the user-signed transaction that authorizes a $THREE spend cap. The
+// client signs + sends it once; afterwards paid actions debit the cap with no
+// popup until it's exhausted, expires, or the user revokes. Non-custodial: funds
+// never leave the user's wallet until an actual charge pulls them.
+
+const grantSchema = z.object({
+ cap_tokens: z.number().positive().max(1_000_000_000),
+ expiry_days: z.number().int().min(1).max(365).optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleAllowanceGrant(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!user.wallet_address) {
+ return error(res, 400, 'wallet_required', 'connect a Solana wallet to authorize spending');
+ }
+ const rl = await limits.tokenQuote(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const delegate = await delegateAddress();
+ if (!delegate) {
+ return error(res, 503, 'allowance_unavailable', 'the spend-allowance rail is not configured');
+ }
+
+ const body = parse(grantSchema, await readJson(req));
+ // cap_tokens (whole $THREE, possibly fractional) → atomics. Max 1e9 tokens ×
+ // 1e6 atomics = 1e15, within Number.MAX_SAFE_INTEGER, so the round is exact.
+ const capAtomics = BigInt(Math.round(body.cap_tokens * Number(ATOMICS_PER_TOKEN)));
+ const expiryTs = body.expiry_days
+ ? Math.floor(Date.now() / 1000) + body.expiry_days * 86_400
+ : 0;
+
+ const built = await buildGrantTransaction({
+ userWallet: user.wallet_address,
+ capAtomics,
+ expiryTs,
+ network: body.network,
+ });
+
+ return json(res, 200, {
+ delegate,
+ cap_tokens: body.cap_tokens,
+ cap_atomics: capAtomics.toString(),
+ expiry_ts: expiryTs,
+ ...built,
+ });
+}
+
// ── GET /api/token/payments (audit) ──────────────────────────────────────────
async function handlePayments(req, res) {
@@ -207,6 +293,8 @@ const DISPATCH = {
quote: handleQuote,
settle: handleSettle,
payments: handlePayments,
+ 'allowance-status': handleAllowanceStatus,
+ 'allowance-grant': handleAllowanceGrant,
};
export default wrap(async (req, res) => {
diff --git a/api/x402-merchant.js b/api/x402-merchant.js
index b945adee5..d1ab09f88 100644
--- a/api/x402-merchant.js
+++ b/api/x402-merchant.js
@@ -168,12 +168,12 @@ const DEFAULTS = {
accent_color: '#0a84ff',
payout_evm: null,
payout_solana: null,
- default_network: 'base',
+ default_network: 'solana',
cors_origins: [],
spend_cap_per_call_atomics: null,
spend_cap_daily_atomics: null,
require_siwx: false,
- allowed_networks: ['base', 'solana'],
+ allowed_networks: ['solana', 'base'],
agent_wallets: [],
facilitator: null,
webhook_url: null,
@@ -297,12 +297,12 @@ async function handleUpsert(req, res) {
accent_color = ${next.accent_color ?? '#0a84ff'},
payout_evm = ${next.payout_evm},
payout_solana = ${next.payout_solana},
- default_network = ${next.default_network ?? 'base'},
+ default_network = ${next.default_network ?? 'solana'},
cors_origins = ${JSON.stringify(next.cors_origins ?? [])}::jsonb,
spend_cap_per_call_atomics = ${next.spend_cap_per_call_atomics},
spend_cap_daily_atomics = ${next.spend_cap_daily_atomics},
require_siwx = ${next.require_siwx ?? false},
- allowed_networks = ${JSON.stringify(next.allowed_networks ?? ['base', 'solana'])}::jsonb,
+ allowed_networks = ${JSON.stringify(next.allowed_networks ?? ['solana', 'base'])}::jsonb,
agent_wallets = ${JSON.stringify(next.agent_wallets ?? [])}::jsonb,
facilitator = ${next.facilitator},
webhook_url = ${next.webhook_url},
diff --git a/character-studio/src/library/characterManager.js b/character-studio/src/library/characterManager.js
index 3841ae591..f893117e5 100644
--- a/character-studio/src/library/characterManager.js
+++ b/character-studio/src/library/characterManager.js
@@ -599,7 +599,8 @@ export class CharacterManager {
*/
loadTraitsFromNFTObject(NFTObject, identifier = null, fullAvatarReplace = true, ignoreGroupTraits = null) {
// XXX should identifier be taken from nft group or passed by user?
- return new Promise(async (resolve, reject) => {
+ return new Promise((resolve, reject) => {
+ (async () => {
// Check if manifest data is available
if (this.manifestDataManager.hasExistingManifest()) {
try {
@@ -621,6 +622,7 @@ export class CharacterManager {
console.error(errorMessage);
reject(new Error(errorMessage));
}
+ })().catch(reject);
});
}
@@ -629,7 +631,8 @@ export class CharacterManager {
* @returns {Promise<void>} Promise that resolves when traits are loaded
*/
loadInitialTraits() {
- return new Promise(async(resolve, reject) => {
+ return new Promise((resolve, reject) => {
+ (async () => {
// Check if manifest data is available
if (this.manifestDataManager.hasExistingManifest()) {
// Load initial traits using the _loadTraits method
@@ -642,6 +645,7 @@ export class CharacterManager {
console.error(errorMessage);
reject(new Error(errorMessage));
}
+ })().catch(reject);
});
}
@@ -650,7 +654,8 @@ export class CharacterManager {
* @returns {Promise<void>} Promise that resolves when traits are loaded
*/
loadAllTraits() {
- return new Promise(async(resolve, reject) => {
+ return new Promise((resolve, reject) => {
+ (async () => {
// Check if manifest data is available
if (this.manifestDataManager.hasExistingManifest()) {
// Load initial traits using the _loadTraits method
@@ -663,6 +668,7 @@ export class CharacterManager {
console.error(errorMessage);
reject(new Error(errorMessage));
}
+ })().catch(reject);
});
}
/**
@@ -791,7 +797,8 @@ export class CharacterManager {
* @returns {Promise<void>} Promise that resolves when trait is loaded
*/
loadTrait(groupTraitID, traitID, identifierID, soloView = false) {
- return new Promise(async (resolve, reject) => {
+ return new Promise((resolve, reject) => {
+ (async () => {
// Check if manifest data is available
if (this.manifestDataManager.hasExistingManifest()) {
try {
@@ -815,6 +822,7 @@ export class CharacterManager {
console.error(errorMessage);
reject(new Error(errorMessage));
}
+ })().catch(reject);
});
}
@@ -825,7 +833,8 @@ export class CharacterManager {
* @returns {Promise<void>} Promise that resolves when trait is loaded
*/
loadCustomTrait(groupTraitID, url) {
- return new Promise(async (resolve, reject) => {
+ return new Promise((resolve, reject) => {
+ (async () => {
// Check if manifest data is available
if (this.manifestDataManager.hasExistingManifest()) {
try {
@@ -849,6 +858,7 @@ export class CharacterManager {
console.error(errorMessage);
reject(new Error(errorMessage));
}
+ })().catch(reject);
});
}
@@ -859,7 +869,8 @@ export class CharacterManager {
* @returns {Promise<void>} Promise that resolves when texture is loaded
*/
loadCustomTexture(groupTraitID, url) {
- return new Promise(async (resolve, reject) => {
+ return new Promise((resolve, reject) => {
+ (async () => {
const model = this.avatar[groupTraitID]?.model;
if (model) {
@@ -874,6 +885,7 @@ export class CharacterManager {
console.warn(errorMessage);
reject(new Error(errorMessage));
}
+ })().catch(reject);
});
}
diff --git a/data/changelog.json b/data/changelog.json
index 4a09b185a..23afcbf17 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,24 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-21",
+ "title": "Authorize $THREE once, then pay with no wallet popups",
+ "summary": "The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/three-token"
+ },
+ {
+ "date": "2026-06-21",
+ "title": "$THREE buyback commitment is now public and verifiable on the token page",
+ "summary": "The $THREE page now leads with the protocol's buyback commitment — the fixed share of all platform revenue routed into buying $THREE on the open market and sending it to the treasury — shown as revenue earned, dollars committed, dollars deployed on-chain, and how much of the commitment has been kept. Every individual buyback is listed with a one-click Solscan receipt, so the promise is provable, not just stated. No burn: supply is never destroyed.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/three-token"
+ },
{
"date": "2026-06-21",
"title": "forge_avatar — one call turns a prompt into a rigged, animation-ready avatar",
@@ -14,7 +32,7 @@
{
"date": "2026-06-21",
"title": "Solana is now the default payment network",
- "summary": "The Default payment network setting in dashboard settings now defaults to Solana for every user, and Solana is listed first among the options. Base and Polygon remain available if you prefer an EVM chain.",
+ "summary": "Solana is now the default everywhere you pick a chain — the dashboard's Default payment network setting, x402 merchant settlement, and the monetization payout wallet all default to Solana for every user, with Solana listed first. Base and Polygon remain available if you prefer an EVM chain.",
"tags": [
"improvement"
],
diff --git a/docs/internal/ISSUES-ARCHIVE-2026-06.md b/docs/internal/ISSUES-ARCHIVE-2026-06.md
new file mode 100644
index 000000000..740dbe8fe
--- /dev/null
+++ b/docs/internal/ISSUES-ARCHIVE-2026-06.md
@@ -0,0 +1,56 @@
+# Production Issues — three.ws / 3D-Agent — Archive 2026-06
+
+Resolved items moved here from [ISSUES.md](../../ISSUES.md). Newest first.
+
+---
+
+## 1. `character-studio/` — pre-existing lint debt (added 2026-06-11, RESOLVED 2026-06-21)
+
+**Context:** The eslint 8→10 upgrade migrated character-studio to flat config
+(`character-studio/eslint.config.mjs`), surfacing pre-existing findings across the
+vendored CharacterStudio fork that all predated the upgrade.
+
+**Runtime `no-undef` bugs — FIXED 2026-06-18** (full table in
+[AUDIT-2026-06-18.md](AUDIT-2026-06-18.md)): twelve references that threw
+`ReferenceError` the moment their code path ran were corrected and verified by a
+clean `no-undef`-only sweep.
+
+**Cosmetic burndown — RESOLVED 2026-06-21.** Every remaining finding in
+`character-studio/src` was cleared, file by file, with minimal behaviour-preserving
+edits. The full tree (`eslint character-studio/src`) now reports **0 problems**.
+
+Findings cleared (178 total across 48 files):
+
+| rule | count | how it was fixed |
+|---|---|---|
+| `no-unused-vars` | 119 | dead imports/locals removed; side-effecting calls kept as statements; unused trailing params dropped; positional destructure holes (`[, x]`); unused catch bindings → optional `catch {}` |
+| `no-async-promise-executor` | 17 | executors with no `await` → dropped the gratuitous `async`; executors using `await` → inner `(async () => { … })().catch(reject)` IIFE so thrown errors reject the promise instead of going unhandled |
+| `no-useless-escape` | 10 | stray `\` before whitespace in GLSL template literals (`particle/shader.js`) removed — string contents unchanged |
+| `no-useless-assignment` | 10 | dead initializers/assignments removed (RHS kept only when side-effecting) |
+| `no-unreachable` | 9 | dead code after early `return`/`throw` deleted (the early exit — the intended behaviour — was kept) |
+| `no-prototype-builtins` | 4 | `obj.hasOwnProperty(k)` → `Object.prototype.hasOwnProperty.call(obj, k)` |
+| `no-empty` | 4 | `/* noop */` comments added; no control-flow change |
+| `no-constant-binary-expression` | 2 | `maxTextureSize: 1024 \|\| Infinity` → `1024` (the `\|\| Infinity` was always dead) |
+| `no-dupe-class-members` | 1 | duplicate `unlockManifestByIndex` removed (kept the later, winning definition) |
+| `preserve-caught-error` | 1 | re-thrown error now carries `{ cause }` |
+| unused eslint-disable directive | 1 | removed (`lipsync.js`) |
+
+**Latent bugs surfaced while clearing dead code (noted, not "fixed" — behaviour
+was preserved to keep this a lint-only pass):**
+
+- `download-utils.js` `getRebindedVRMExpressionManager` — the entire blendshape
+ re-bind implementation sat behind an early `return oldExpressionManager;`, so it
+ has been dead in this fork. The unreachable body was removed; the feature remains
+ effectively disabled (unchanged from before).
+- `addLookAtMouse(…, enable = true)` (`characterManager.js`) — the `enable`
+ parameter was never read (`lookAtManager.enabled = true` is hardcoded); the unused
+ param was dropped.
+- `ktxtools.js:47` — `uastcRDODictSize` ternary copies `userBasisuOptions.uastcRDOQualityScalar`
+ in its truthy branch (looks like a copy-paste error); left as-is, outside lint scope.
+- `textureImageDataRenderer.js` `render()` — the empty-textures branch assigned the
+ solid-colour fallback to the `texture` param, which is never read afterward (only
+ `textures` is), so the fallback was discarded; the dead assignment was removed and
+ current behaviour preserved.
+
+These are tracked here for a future correctness pass; none are regressions from this
+work.
diff --git a/public/changelog.json b/public/changelog.json
index 8737ef6f8..a68c87e7a 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-21T04:10:02.450Z",
+ "generated_at": "2026-06-21T04:34:43.784Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "$THREE buyback commitment is now public and verifiable on the token page",
+ "summary": "The $THREE page now leads with the protocol's buyback commitment — the fixed share of all platform revenue routed into buying $THREE on the open market and sending it to the treasury — shown as revenue earned, dollars committed, dollars deployed on-chain, and how much of the commitment has been kept. Every individual buyback is listed with a one-click Solscan receipt, so the promise is provable, not just stated. No burn: supply is never destroyed.",
+ "link": "/three-token",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
@@ -17,6 +27,16 @@
"infra"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Authorize $THREE once, then pay with no wallet popups",
+ "summary": "The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice.",
+ "link": "/three-token",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
@@ -32,7 +52,7 @@
"date": "2026-06-21",
"type": "update",
"title": "Solana is now the default payment network",
- "summary": "The Default payment network setting in dashboard settings now defaults to Solana for every user, and Solana is listed first among the options. Base and Polygon remain available if you prefer an EVM chain.",
+ "summary": "Solana is now the default everywhere you pick a chain — the dashboard's Default payment network setting, x402 merchant settlement, and the monetization payout wallet all default to Solana for every user, with Solana listed first. Base and Polygon remain available if you prefer an EVM chain.",
"link": "/dashboard",
"tags": [
"improvement"
diff --git a/public/changelog.xml b/public/changelog.xml
index 86af7d058..4a60beb43 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>$THREE buyback commitment is now public and verifiable on the token page</title>
+ <link>https://three.ws/three-token</link>
+ <guid isPermaLink="false">2026-06-21:$THREE buyback commitment is now public and verifiable on the token page</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The $THREE page now leads with the protocol's buyback commitment — the fixed share of all platform revenue routed into buying $THREE on the open market and sending it to the treasury — shown as revenue earned, dollars committed, dollars deployed on-chain, and how much of the commitment has been kept. Every individual buyback is listed with a one-click Solscan receipt, so the promise is provable, not just stated. No burn: supply is never destroyed.</description>
+ </item>
<item>
<title>$THREE holder leaderboard loads faster from a shared snapshot</title>
<link>https://three.ws/leaderboard</link>
@@ -14,6 +22,14 @@
<category>improvement</category>
<description>The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces.</description>
</item>
+ <item>
+ <title>Authorize $THREE once, then pay with no wallet popups</title>
+ <link>https://three.ws/three-token</link>
+ <guid isPermaLink="false">2026-06-21:Authorize $THREE once, then pay with no wallet popups</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions &amp; Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice.</description>
+ </item>
<item>
<title>forge_avatar — one call turns a prompt into a rigged, animation-ready avatar</title>
<link>https://three.ws/docs/mcp</link>
@@ -28,7 +44,7 @@
<guid isPermaLink="false">2026-06-21:Solana is now the default payment network</guid>
<pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
<category>improvement</category>
- <description>The Default payment network setting in dashboard settings now defaults to Solana for every user, and Solana is listed first among the options. Base and Polygon remain available if you prefer an EVM chain.</description>
+ <description>Solana is now the default everywhere you pick a chain — the dashboard's Default payment network setting, x402 merchant settlement, and the monetization payout wallet all default to Solana for every user, with Solana listed first. Base and Polygon remain available if you prefer an EVM chain.</description>
</item>
<item>
<title>Grind-Bounty Market</title>
diff --git a/public/dashboard/x402-admin.html b/public/dashboard/x402-admin.html
index acc67d2c3..613ab5f41 100644
--- a/public/dashboard/x402-admin.html
+++ b/public/dashboard/x402-admin.html
@@ -625,7 +625,7 @@ function hydrate(){
$('support_email').value = s.support_email || '';
$('logo_url').value = s.logo_url || '';
$('accent_color').value = s.accent_color || '#0a84ff';
- setNetSeg(s.default_network || 'base');
+ setNetSeg(s.default_network || 'solana');
$('webhook_url').value = s.webhook_url || '';
$('facilitator').value = s.facilitator || '';
agentWallets = Array.isArray(s.agent_wallets) ? structuredClone(s.agent_wallets) : [];
@@ -634,7 +634,7 @@ function hydrate(){
$('store_published').checked = !!s.store_published;
$('cap_call').value = s.spend_cap_per_call_atomics ? fmtUsdc(s.spend_cap_per_call_atomics) : '';
$('cap_day').value = s.spend_cap_daily_atomics ? fmtUsdc(s.spend_cap_daily_atomics) : '';
- const nets = Array.isArray(s.allowed_networks) ? s.allowed_networks : ['base','solana'];
+ const nets = Array.isArray(s.allowed_networks) ? s.allowed_networks : ['solana','base'];
$('net_base').checked = nets.includes('base');
$('net_solana').checked = nets.includes('solana');
$('require_siwx').checked = !!s.require_siwx;
@@ -656,8 +656,8 @@ function hydrate(){
// ── Collect settings from form into a patch ──
function collect(){
const nets = [];
- if ($('net_base').checked) nets.push('base');
if ($('net_solana').checked) nets.push('solana');
+ if ($('net_base').checked) nets.push('base');
return {
payout_evm: $('payout_evm').value.trim() || null,
payout_solana: $('payout_solana').value.trim() || null,
@@ -675,7 +675,7 @@ function collect(){
cors_origins: corsOrigins,
spend_cap_per_call_atomics: toAtomics($('cap_call').value),
spend_cap_daily_atomics: toAtomics($('cap_day').value),
- allowed_networks: nets.length ? nets : ['base','solana'],
+ allowed_networks: nets.length ? nets : ['solana','base'],
require_siwx: $('require_siwx').checked,
charity_enabled: $('charity_enabled').checked,
charity_name: $('charity_name').value.trim() || null,
diff --git a/public/features.json b/public/features.json
index d364947a7..2c940a645 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T04:10:02.433Z",
+ "generated_at": "2026-06-21T04:34:43.761Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/x402/studio.js b/public/x402/studio.js
index 5a3468464..a9c2dcdd3 100644
--- a/public/x402/studio.js
+++ b/public/x402/studio.js
@@ -431,7 +431,7 @@ function renderWallets(host) {
field('Solana payout (USDC)', solAddrField('po_sol', m.payout_solana || '')),
field('Base / EVM payout (USDC)', input({ id: 'po_evm', value: m.payout_evm || '', placeholder: '0x…', class: 'mono' })),
),
- field('Default settlement network', select('po_net', ['base', 'solana'], m.default_network || 'base')),
+ field('Default settlement network', select('po_net', ['solana', 'base'], m.default_network || 'solana')),
el('div', { class: 'row', style: 'margin-top:4px' }, el('button', { class: 'btn primary', id: 'po_save', onclick: savePayout }, 'Save payout wallets')),
);
host.append(payout);
diff --git a/src/dashboard-next/pages/monetize.js b/src/dashboard-next/pages/monetize.js
index 287437029..8d7c25d8e 100644
--- a/src/dashboard-next/pages/monetize.js
+++ b/src/dashboard-next/pages/monetize.js
@@ -523,7 +523,7 @@ function renderPayoutWalletPanel(wallet, agentId, host, me, agents, legacyWallet
function paint(w) {
const evmAddr = w?.evm_address || w?.evm || '';
const solAddr = w?.solana_address || w?.solana || '';
- const preferred = w?.preferred_network || 'base';
+ const preferred = w?.preferred_network || 'solana';
const balance = w?.available_balance ?? w?.balance ?? 0;
panel.innerHTML = `
@@ -554,8 +554,8 @@ function renderPayoutWalletPanel(wallet, agentId, host, me, agents, legacyWallet
<label class="mon-field" style="margin-bottom:0;flex:1;min-width:160px">
<span class="mon-label">Preferred network</span>
<select data-slot="network" class="mon-select">
- <option value="base" ${preferred === 'base' ? 'selected' : ''}>Base (EVM)</option>
<option value="solana" ${preferred === 'solana' ? 'selected' : ''}>Solana</option>
+ <option value="base" ${preferred === 'base' ? 'selected' : ''}>Base (EVM)</option>
</select>
</label>
<button class="dn-btn primary" data-action="save-wallet" style="align-self:flex-end">Save Wallet</button>
diff --git a/src/dashboard-next/pages/three-token.js b/src/dashboard-next/pages/three-token.js
index 5d6e0888f..e56f2d4c7 100644
--- a/src/dashboard-next/pages/three-token.js
+++ b/src/dashboard-next/pages/three-token.js
@@ -13,6 +13,7 @@
import { mountShell } from '../shell.js';
import { requireUser, esc, relTime, ApiError } from '../api.js';
import { fetchTokenConfig, fetchTokenPrice } from '../../token-pay.js';
+import { fetchAllowanceStatus, grantAllowance } from '../../three-allowance.js';
import { createThreeTokenData } from '../../pump/three-token-data.js';
const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;
@@ -133,6 +134,7 @@ function toast(msg) {
host.appendChild(renderHeroMetrics(stats));
host.appendChild(renderPositionWidget(store));
host.appendChild(renderAccruedRewards(store));
+ host.appendChild(renderSpendAllowance());
host.appendChild(renderUtilityPillars(stats));
host.appendChild(renderLiveConverter(tokenConfig));
host.appendChild(renderRevenueShare(stats, revenueShare));
@@ -377,6 +379,160 @@ function accruedBody(pos, rev, token) {
<p style="font-size:12px;color:var(--nxt-ink-fade);margin:0;line-height:1.5">Revenue share is distributed on-chain to $THREE holders pro-rata — your accrual settles to the wallet holding the tokens. No manual claim required.</p>`;
}
+// ── Spend allowance (frictionless pay-from-wallet) ──────────────────────────────
+
+// Lets a holder authorize a $THREE spend cap ONCE; afterwards paid actions
+// (forge, skills, names, cosmetics) debit the cap with no wallet popup. Built on
+// Solana's native, audited Subscriptions & Allowances program — NON-CUSTODIAL:
+// tokens stay in the wallet until a charge pulls them, capped at what the user
+// authorized. The panel self-loads its status and removes itself when the rail is
+// not configured (no dead UI). Every state is designed: loading, no-wallet,
+// not-yet-granted, active, and error.
+const PRESET_CAPS = [100, 1_000, 10_000];
+const EXPIRY_OPTIONS = [
+ { label: '30 days', days: 30 },
+ { label: '90 days', days: 90 },
+ { label: 'No expiry', days: null },
+];
+
+function renderSpendAllowance() {
+ const section = document.createElement('div');
+ section.className = 'dn-panel';
+ section.setAttribute('aria-label', 'Your $THREE spend allowance');
+ section.innerHTML = `
+ <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:4px">
+ <div style="font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.06em">Spend Allowance</div>
+ <span style="font-size:10.5px;color:var(--nxt-ink-fade);border:1px solid var(--nxt-line);border-radius:999px;padding:2px 8px">Non-custodial</span>
+ </div>
+ <p style="margin:0 0 12px;font-size:12px;color:var(--nxt-ink-fade);line-height:1.5">Authorize a $THREE spending cap once — then pay for forge, skills, names and cosmetics with no wallet popup each time. Your tokens stay in your wallet until a charge pulls them, never above the cap you set. Revoke anytime.</p>
+ <div data-slot="allowance-body"><div class="dn-skeleton" style="height:72px;border-radius:10px" aria-busy="true"></div></div>
+ `;
+ const body = section.querySelector('[data-slot="allowance-body"]');
+
+ let busy = false;
+ const load = async () => {
+ try {
+ const status = await fetchAllowanceStatus();
+ if (!status.enabled) {
+ // The rail isn't configured on this deployment — show nothing rather
+ // than a button that can't work.
+ section.remove();
+ return;
+ }
+ renderBody(status);
+ } catch (err) {
+ if (err?.code === 'unauthorized') {
+ body.innerHTML = positionEmpty('Sign in to set a spend allowance.', 'Sign in', `/login?return=${encodeURIComponent(location.pathname)}`);
+ return;
+ }
+ body.innerHTML = `<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
+ <span style="color:var(--nxt-ink-fade);font-size:13.5px">Couldn’t load your allowance right now.</span>
+ <button data-action="allowance-retry" class="dn-btn" style="font-size:12px;padding:4px 10px">Retry</button>
+ </div>`;
+ }
+ };
+
+ const renderBody = (status) => {
+ if (!status.wallet) {
+ body.innerHTML = positionEmpty('Link a Solana wallet to enable frictionless spending.', 'Link wallet', '/dashboard/account');
+ return;
+ }
+ const remaining = Number(status.remaining_tokens || 0);
+ const hasAllowance = remaining > 0;
+
+ const capChips = PRESET_CAPS.map(
+ (c) => `<button type="button" data-cap="${c}" class="dn-btn" style="font-size:12.5px;padding:5px 12px">${fmtCompact(c)}</button>`,
+ ).join('');
+ const expiryChips = EXPIRY_OPTIONS.map(
+ (o, i) => `<button type="button" data-exp="${o.days ?? ''}" class="dn-btn${i === 0 ? ' is-active' : ''}" aria-pressed="${i === 0}" style="font-size:12px;padding:4px 10px">${esc(o.label)}</button>`,
+ ).join('');
+
+ body.innerHTML = `
+ ${hasAllowance ? `
+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:14px">
+ <div>
+ <div style="font-size:11px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.05em;margin-bottom:4px">Remaining cap</div>
+ <div style="font-size:24px;font-weight:700;font-family:${MONO};color:#4ade80">${fmtCompact(remaining)} <span style="font-size:13px;color:var(--nxt-ink-fade)">$THREE</span></div>
+ </div>
+ <div>
+ <div style="font-size:11px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.05em;margin-bottom:4px">Status</div>
+ <div style="font-size:15px;font-weight:600;color:#4ade80">● Frictionless spending on</div>
+ </div>
+ </div>
+ ` : `
+ <div style="font-size:13.5px;color:var(--nxt-ink-dim);margin-bottom:14px">No active allowance — paid actions will ask for a signature each time. Authorize a cap to skip the popups.</div>
+ `}
+ <div style="display:flex;flex-direction:column;gap:10px">
+ <div>
+ <label for="allowance-cap" style="display:block;font-size:11px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.05em;margin-bottom:6px">${hasAllowance ? 'Top up cap' : 'Spend cap'} ($THREE)</label>
+ <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
+ <input id="allowance-cap" type="number" min="1" step="1" inputmode="numeric" placeholder="1000" value="1000"
+ style="width:120px;padding:7px 10px;background:var(--nxt-bg-soft,rgba(255,255,255,0.04));border:1px solid var(--nxt-line);border-radius:8px;color:var(--nxt-ink);font-family:${MONO};font-size:14px" />
+ ${capChips}
+ </div>
+ </div>
+ <div>
+ <span style="display:block;font-size:11px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.05em;margin-bottom:6px">Auto-expiry</span>
+ <div data-slot="expiry-chips" style="display:flex;gap:8px;flex-wrap:wrap">${expiryChips}</div>
+ </div>
+ <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-top:2px">
+ <button data-action="allowance-grant" class="dn-btn is-primary" style="font-size:13px;padding:8px 18px;font-weight:600">${hasAllowance ? 'Add to cap' : 'Authorize spending'}</button>
+ <span data-slot="allowance-msg" style="font-size:12.5px;color:var(--nxt-ink-fade)" aria-live="polite"></span>
+ </div>
+ </div>
+ `;
+
+ const capInput = body.querySelector('#allowance-cap');
+ body.querySelectorAll('[data-cap]').forEach((b) =>
+ b.addEventListener('click', () => { capInput.value = b.getAttribute('data-cap'); capInput.focus(); }),
+ );
+ const expiryWrap = body.querySelector('[data-slot="expiry-chips"]');
+ expiryWrap.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-exp]');
+ if (!btn) return;
+ expiryWrap.querySelectorAll('[data-exp]').forEach((b) => { b.classList.remove('is-active'); b.setAttribute('aria-pressed', 'false'); });
+ btn.classList.add('is-active');
+ btn.setAttribute('aria-pressed', 'true');
+ });
+ };
+
+ const doGrant = async (btn) => {
+ if (busy) return;
+ const capInput = body.querySelector('#allowance-cap');
+ const msg = body.querySelector('[data-slot="allowance-msg"]');
+ const capTokens = Math.floor(Number(capInput?.value));
+ if (!(capTokens > 0)) { if (msg) msg.textContent = 'Enter a cap greater than zero.'; return; }
+ const expSel = body.querySelector('[data-slot="expiry-chips"] .is-active');
+ const expVal = expSel?.getAttribute('data-exp');
+ const expiryDays = expVal ? Number(expVal) : undefined;
+
+ busy = true;
+ btn.disabled = true;
+ const labels = { building: 'Building…', awaiting_signature: 'Confirm in wallet…', confirming: 'Confirming…', done: 'Done' };
+ try {
+ await grantAllowance({ capTokens, expiryDays, onStatus: (s) => { btn.textContent = labels[s] || 'Working…'; } });
+ toast(`Authorized ${fmtCompact(capTokens)} $THREE — spending is now frictionless`);
+ busy = false;
+ await load(); // re-render with the new remaining cap
+ } catch (err) {
+ busy = false;
+ btn.disabled = false;
+ btn.textContent = 'Authorize spending';
+ if (msg) msg.textContent = err?.message || 'Could not authorize spending.';
+ }
+ };
+
+ section.addEventListener('click', (e) => {
+ const grantBtn = e.target.closest('[data-action="allowance-grant"]');
+ if (grantBtn) { doGrant(grantBtn); return; }
+ const retry = e.target.closest('[data-action="allowance-retry"]');
+ if (retry) { body.innerHTML = `<div class="dn-skeleton" style="height:72px;border-radius:10px"></div>`; load(); }
+ });
+
+ load();
+ return section;
+}
+
// ── Four utility pillars ──────────────────────────────────────────────────────
function renderUtilityPillars(stats) {
diff --git a/src/three-allowance.js b/src/three-allowance.js
new file mode 100644
index 000000000..89fddf6fb
--- /dev/null
+++ b/src/three-allowance.js
@@ -0,0 +1,123 @@
+/**
+ * $THREE spend allowance — client helper.
+ *
+ * Lets a holder authorize a $THREE spending cap ONCE (one wallet signature), after
+ * which paid actions across the platform debit that cap with no further popups.
+ * Built on Solana's native Subscriptions & Allowances program — non-custodial:
+ * the tokens stay in the user's wallet until an actual charge pulls them, and the
+ * cap is the hard ceiling the platform delegate can ever touch.
+ *
+ * import { fetchAllowanceStatus, grantAllowance } from './three-allowance.js';
+ * const status = await fetchAllowanceStatus(); // { enabled, remaining_tokens, … }
+ * await grantAllowance({ capTokens: 1000, expiryDays: 30, onStatus });
+ *
+ * The server prices and builds the grant transaction (api/token/allowance-grant);
+ * this helper only resolves the wallet, signs, sends, and confirms. It never holds
+ * keys and never reports success the server can't verify on-chain.
+ */
+
+// Lazy-load the Solana SDK so it stays out of the initial bundle (mirrors token-pay.js).
+let _web3 = null;
+async function loadWeb3() {
+ if (!_web3) _web3 = await import('@solana/web3.js');
+ return _web3;
+}
+
+function rpcEndpoint() {
+ return (
+ (typeof window !== 'undefined' && window.__solanaRpc) ||
+ `${window.location.origin}/api/solana-rpc`
+ );
+}
+
+async function getProvider(explicit) {
+ const wallet = explicit || (typeof window !== 'undefined' ? window.solana : null);
+ if (!wallet) {
+ throw Object.assign(new Error('No Solana wallet found. Install Phantom or connect a wallet.'), {
+ code: 'no_wallet',
+ });
+ }
+ if (!wallet.isConnected) {
+ if (typeof wallet.connect === 'function') await wallet.connect();
+ else throw Object.assign(new Error('Wallet is not connected.'), { code: 'not_connected' });
+ }
+ return wallet;
+}
+
+/**
+ * The signed-in holder's live spend allowance.
+ * @returns {Promise<{ enabled: boolean, delegate: string|null, wallet?: string|null,
+ * remaining_atomics: string, remaining_tokens?: number, delegations: object[] }>}
+ */
+export async function fetchAllowanceStatus({ network } = {}) {
+ const qs = network ? `?network=${encodeURIComponent(network)}` : '';
+ const r = await fetch(`/api/token/allowance-status${qs}`, { credentials: 'include' });
+ if (r.status === 401) throw Object.assign(new Error('Sign in to view your allowance.'), { code: 'unauthorized' });
+ if (!r.ok) throw new Error(`allowance status ${r.status}`);
+ return r.json();
+}
+
+/**
+ * Authorize (or top up) a $THREE spend cap. One signature; afterwards paid actions
+ * debit the cap with no popup until it is spent, expires, or is revoked.
+ *
+ * @param {{
+ * capTokens: number, // whole $THREE the platform may spend over time
+ * expiryDays?: number, // optional auto-expiry (1–365); omit for no expiry
+ * network?: 'mainnet'|'devnet',
+ * wallet?: any, // override window.solana
+ * onStatus?: (s: 'building'|'awaiting_signature'|'confirming'|'done') => void,
+ * }} params
+ * @returns {Promise<{ ok: true, signature: string, delegation_pda: string, cap_tokens: number }>}
+ */
+export async function grantAllowance({
+ capTokens,
+ expiryDays,
+ network = 'mainnet',
+ wallet,
+ onStatus = () => {},
+}) {
+ if (!(capTokens > 0)) throw Object.assign(new Error('Enter a spend cap greater than zero.'), { code: 'bad_cap' });
+
+ onStatus('building');
+ const prepResp = await fetch('/api/token/allowance-grant', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ cap_tokens: capTokens, expiry_days: expiryDays, network }),
+ });
+ const prep = await prepResp.json();
+ if (!prepResp.ok) {
+ throw Object.assign(new Error(prep.error_description || 'could not build allowance'), {
+ code: prep.error,
+ });
+ }
+
+ const web3 = await loadWeb3();
+ const { Connection, Transaction } = web3;
+ const provider = await getProvider(wallet);
+ const connection = new Connection(rpcEndpoint(), 'confirmed');
+
+ // The server returns a fully-formed unsigned tx (recent blockhash + fee payer
+ // already set). Deserialize, let the wallet sign, then send + confirm.
+ const tx = Transaction.from(Buffer.from(prep.transaction, 'base64'));
+
+ onStatus('awaiting_signature');
+ const signature = await provider.sendTransaction(tx, connection);
+
+ onStatus('confirming');
+ const latest = await connection.getLatestBlockhash('confirmed');
+ await connection.confirmTransaction(
+ { signature, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight },
+ 'confirmed',
+ );
+
+ onStatus('done');
+ return {
+ ok: true,
+ signature,
+ delegation_pda: prep.delegation_pda,
+ cap_tokens: prep.cap_tokens,
+ expiry_ts: prep.expiry_ts,
+ };
+}
diff --git a/src/three-token-page.js b/src/three-token-page.js
index e023c4b6d..7c3a08973 100644
--- a/src/three-token-page.js
+++ b/src/three-token-page.js
@@ -97,18 +97,30 @@ function injectStyles() {
.tk-foot { display:flex; gap:18px; flex-wrap:wrap; margin-top:26px; font-size:13px; }
.tk-foot a { color:#9a9aa3; text-decoration:none; } .tk-foot a:hover { color:#fff; }
.tk-bb { margin-top:18px; }
- .tk-bb-lead { color:#9a9aa3; font-size:13px; margin:0 0 14px; line-height:1.5; }
+ .tk-bb-commit { display:flex; align-items:baseline; gap:10px; flex-wrap:wrap; margin:0 0 8px; }
+ .tk-bb-commit b { font-size:30px; line-height:1; font-weight:800; font-family:ui-monospace,Menlo,monospace; background:linear-gradient(90deg,#4ade80,#22d3ee); -webkit-background-clip:text; background-clip:text; -webkit-text-fill-color:transparent; }
+ .tk-bb-commit em { font-style:normal; color:#d8d8e0; font-size:14px; font-weight:600; }
+ .tk-bb-lead { color:#9a9aa3; font-size:13px; margin:0 0 14px; line-height:1.55; }
.tk-bb-empty { color:#b8b8c0; font-size:14px; line-height:1.6; }
.tk-bb-empty strong { color:#f5f5f7; }
.tk-bb-empty span { display:block; color:#7d7d86; font-size:13px; margin-top:6px; }
- .tk-bb-head { display:grid; grid-template-columns:repeat(3,1fr); gap:12px; margin-bottom:14px; }
+ .tk-bb-head { display:grid; grid-template-columns:repeat(4,1fr); gap:12px; margin-bottom:14px; }
.tk-bb-k { font-size:11px; text-transform:uppercase; letter-spacing:0.06em; color:#7d7d86; margin-bottom:4px; }
- .tk-bb-v { font-size:20px; font-weight:700; font-family:ui-monospace,Menlo,monospace; }
+ .tk-bb-v { font-size:19px; font-weight:700; font-family:ui-monospace,Menlo,monospace; }
.tk-bb-bar { height:8px; border-radius:6px; background:#1d1d24; overflow:hidden; }
.tk-bb-bar span { display:block; height:100%; background:linear-gradient(90deg,#4ade80,#22d3ee); border-radius:6px; transition:width .6s ease; }
.tk-bb-foot { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; margin-top:10px; font-size:12.5px; color:#7d7d86; }
.tk-bb-foot a { color:#7CC4FF; text-decoration:none; } .tk-bb-foot a:hover { text-decoration:underline; }
- @media (max-width:560px){ .tk-bb-head { grid-template-columns:1fr; gap:8px; } }
+ .tk-bb-runs-h { font-size:11px; text-transform:uppercase; letter-spacing:0.06em; color:#7d7d86; margin:18px 0 8px; }
+ .tk-bb-runs { display:flex; flex-direction:column; gap:3px; }
+ .tk-bb-run { display:grid; grid-template-columns:auto 1fr auto; gap:10px; align-items:center; padding:8px 10px; border-radius:8px; font-size:12.5px; background:#0e0e12; border:1px solid #16161c; }
+ .tk-bb-run:hover { background:#15151b; border-color:#23232b; }
+ .tk-bb-run-date { color:#7d7d86; font-family:ui-monospace,Menlo,monospace; }
+ .tk-bb-run-amt { font-family:ui-monospace,Menlo,monospace; color:#d8d8e0; }
+ .tk-bb-run-amt b { color:#4ade80; font-weight:700; }
+ .tk-bb-run a { color:#7CC4FF; text-decoration:none; justify-self:end; white-space:nowrap; }
+ .tk-bb-run a:hover { text-decoration:underline; }
+ @media (max-width:560px){ .tk-bb-head { grid-template-columns:repeat(2,1fr); gap:8px; } }
@media (prefers-reduced-motion: reduce){ .tk-trade.in { animation:none; } .tk-skel { animation:none; } .tk-bb-bar span { transition:none; } }
`;
const el = document.createElement('style');
@@ -135,35 +147,66 @@ function renderHeaderStats(token) {
}
// ── programmatic buybacks (revenue → $THREE → treasury) ──────────────────────
+const fmtRunDate = (at) => (at ? new Date(at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '');
+
+// The verifiable receipt list: each confirmed buy, clickable to its Solscan tx.
+// Proof, not a claim — this is what answers "why hold $THREE".
+function renderBuybackRuns(runs) {
+ if (!Array.isArray(runs) || !runs.length) return '';
+ const rows = runs
+ .filter((r) => r && r.signature)
+ .map((r) => {
+ const amt = `${fmtUsd(r.usdc)} → <b>${fmtNum(r.three)}</b> $THREE`;
+ return `<div class="tk-bb-run">
+ <span class="tk-bb-run-date">${esc(fmtRunDate(r.at))}</span>
+ <span class="tk-bb-run-amt">${amt}</span>
+ <a href="https://solscan.io/tx/${esc(r.signature)}" target="_blank" rel="noopener" title="Verify on Solscan">Verify ↗</a>
+ </div>`;
+ })
+ .join('');
+ if (!rows) return '';
+ return `<div class="tk-bb-runs-h">Verifiable buybacks — every buy, on-chain</div><div class="tk-bb-runs">${rows}</div>`;
+}
+
function renderBuyback(bb) {
if (!bb) return `<div class="tk-empty" style="padding:24px 0">Couldn’t load buyback data.</div>`;
const revenue = fmtUsd(bb.revenue_usd);
- const lead = `Platform revenue is programmatically converted into $THREE buy pressure and routed to the treasury — onchain, on a schedule. No burn: supply is never destroyed.`;
+ // The published promise — the headline a holder repeats. Defaults guard a
+ // partial payload so the commitment always renders.
+ const commitPct = Number.isFinite(Number(bb.commit_pct)) ? Number(bb.commit_pct) : 50;
+ const commitLabel = `${commitPct % 1 === 0 ? commitPct.toFixed(0) : commitPct.toFixed(1)}%`;
+ const commit = `<div class="tk-bb-commit"><b>${commitLabel}</b><em>of all platform revenue → $THREE buybacks</em></div>`;
+ const lead = `The $THREE protocol commits a fixed share of platform revenue to buying $THREE on the open market and routing it to the treasury — on-chain, on a schedule, every buy verifiable below. No burn: supply is never destroyed.`;
+
if (!bb.runs) {
return `
+ ${commit}
<p class="tk-bb-lead">${lead}</p>
<div class="tk-bb-empty">
- <strong>${revenue}</strong> in platform revenue earned so far.
- <span>Buybacks begin once the treasury deploys revenue onchain — every run will appear here with its Solscan receipt.</span>
+ <strong>${revenue}</strong> in platform revenue earned so far · <strong>${fmtUsd(bb.committed_usd)}</strong> committed to buybacks at ${commitLabel}.
+ <span>Buys begin as the treasury deploys revenue on-chain — each one appears here with its Solscan receipt.</span>
</div>`;
}
- const pct = Math.max(0, Math.min(100, Number(bb.deployed_pct) || 0));
- const last = bb.last_run;
- const lastDate = last?.at ? new Date(last.at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : null;
+
+ // Progress = share of the COMMITMENT already deployed on-chain (keeping the
+ // promise), distinct from the raw deployed/revenue ratio.
+ const pct = Math.max(0, Math.min(100, Number(bb.commitment_progress_pct) || 0));
return `
+ ${commit}
<p class="tk-bb-lead">${lead}</p>
<div class="tk-bb-head">
<div><div class="tk-bb-k">Revenue earned</div><div class="tk-bb-v">${revenue}</div></div>
- <div><div class="tk-bb-k">Deployed to buybacks</div><div class="tk-bb-v">${fmtUsd(bb.deployed_usd)}</div></div>
- <div><div class="tk-bb-k">$THREE bought</div><div class="tk-bb-v">${fmtNum(bb.three_bought)}</div></div>
+ <div><div class="tk-bb-k">Committed (${commitLabel})</div><div class="tk-bb-v">${fmtUsd(bb.committed_usd)}</div></div>
+ <div><div class="tk-bb-k">Deployed on-chain</div><div class="tk-bb-v">${fmtUsd(bb.deployed_usd)}</div></div>
+ <div><div class="tk-bb-k">$THREE bought back</div><div class="tk-bb-v">${fmtNum(bb.three_bought)}</div></div>
</div>
- <div class="tk-bb-bar" role="progressbar" aria-valuenow="${pct.toFixed(0)}" aria-valuemin="0" aria-valuemax="100" aria-label="Share of revenue deployed to buybacks">
+ <div class="tk-bb-bar" role="progressbar" aria-valuenow="${pct.toFixed(0)}" aria-valuemin="0" aria-valuemax="100" aria-label="Share of the buyback commitment deployed on-chain">
<span style="width:${pct}%"></span>
</div>
<div class="tk-bb-foot">
- <span>${pct.toFixed(1)}% of revenue → onchain buy pressure · ${fmtNum(bb.runs)} run${bb.runs === 1 ? '' : 's'}</span>
- ${last?.signature ? `<a href="https://solscan.io/tx/${esc(last.signature)}" target="_blank" rel="noopener">Last buyback${lastDate ? ` · ${lastDate}` : ''} ↗</a>` : ''}
- </div>`;
+ <span>${pct.toFixed(1)}% of the ${commitLabel} commitment deployed · ${fmtNum(bb.runs)} buyback${bb.runs === 1 ? '' : 's'}</span>
+ </div>
+ ${renderBuybackRuns(bb.recent_runs)}`;
}
// ── live trade tape via SSE (reconnecting) ───────────────────────────────────
diff --git a/tests/api/three-buyback-math.test.js b/tests/api/three-buyback-math.test.js
index 9acd8f73e..d5a7bfcb5 100644
--- a/tests/api/three-buyback-math.test.js
+++ b/tests/api/three-buyback-math.test.js
@@ -10,6 +10,9 @@ import {
USDC_ATOMICS,
computeSpend,
deployedPct,
+ committedUsd,
+ commitmentProgressPct,
+ envBps,
envSlippageBps,
envUsd,
usdToUsdcAtomics,
@@ -70,6 +73,43 @@ describe('buyback deployedPct', () => {
});
});
+describe('buyback commitment math', () => {
+ it('committedUsd applies the commitment bps to revenue', () => {
+ expect(committedUsd(1000, 5000)).toBe(500); // 50% of $1000
+ expect(committedUsd(1000, 8000)).toBe(800); // 80%
+ expect(committedUsd(250, 10_000)).toBe(250); // full revenue
+ });
+
+ it('committedUsd is 0 for non-positive revenue or commitment', () => {
+ expect(committedUsd(0, 5000)).toBe(0);
+ expect(committedUsd(-10, 5000)).toBe(0);
+ expect(committedUsd(1000, 0)).toBe(0);
+ });
+
+ it('commitmentProgressPct measures deployed against the committed target', () => {
+ expect(commitmentProgressPct(250, 500)).toBe(50); // half the promise kept
+ expect(commitmentProgressPct(0, 500)).toBe(0); // nothing deployed yet
+ expect(commitmentProgressPct(500, 500)).toBe(100); // promise fully kept
+ });
+
+ it('commitmentProgressPct clamps to 100 and is 0 when nothing is committed', () => {
+ expect(commitmentProgressPct(600, 500)).toBe(100); // over-deployed → capped
+ expect(commitmentProgressPct(50, 0)).toBe(0); // no commitment target yet
+ });
+
+ it('envBps parses [0,10000], else falls back', () => {
+ expect(envBps(undefined, 5000)).toBe(5000);
+ expect(envBps('', 5000)).toBe(5000);
+ expect(envBps('8000', 5000)).toBe(8000);
+ expect(envBps('0', 5000)).toBe(0); // 0% is a valid (if odd) commitment
+ expect(envBps('10000', 5000)).toBe(10_000);
+ expect(envBps('10001', 5000)).toBe(5000); // over ceiling → fallback
+ expect(envBps('-1', 5000)).toBe(5000); // negative → fallback
+ expect(envBps('abc', 5000)).toBe(5000);
+ expect(envBps('5000.6', 5000)).toBe(5001); // rounds
+ });
+});
+
describe('buyback unit conversions', () => {
it('round-trips USD ↔ USDC atomics', () => {
expect(usdToUsdcAtomics(1)).toBe(USDC_ATOMICS);
diff --git a/tests/src/eth-vanity-worker.test.js b/tests/src/eth-vanity-worker.test.js
new file mode 100644
index 000000000..33821c9b9
--- /dev/null
+++ b/tests/src/eth-vanity-worker.test.js
@@ -0,0 +1,160 @@
+/**
+ * Drives the CREATE2 vanity grind Web Worker (src/eth/vanity/grinder-worker.js)
+ * directly by mocking `self`, exercising the parts that have no other coverage:
+ *
+ * 1. correctness — a reported match actually re-derives to the claimed
+ * CREATE2 address and honours the requested prefix;
+ * 2. input validation — a malformed deployer is rejected, not ground on;
+ * 3. the pause/resume state machine — pause genuinely halts the hot loop
+ * (no further progress) and resume continues the SAME search with a
+ * monotonic attempt count (it is not silently restarted from zero).
+ *
+ * The worker assigns `self.onmessage` at module-eval time and reports via
+ * `self.postMessage`, so we install a fresh `self` mock before each import
+ * (vi.resetModules gives each test its own module state) and pump messages
+ * through onmessage just like a real Worker host would.
+ */
+import { describe, it, expect, vi, beforeAll } from 'vitest';
+import { webcrypto } from 'node:crypto';
+import { keccak_256 } from '@noble/hashes/sha3';
+
+beforeAll(() => {
+ globalThis.crypto ??= webcrypto;
+});
+
+const WORKER = '../../src/eth/vanity/grinder-worker.js';
+
+/** Reset module state, install a capturing `self`, import the worker fresh. */
+async function loadWorker() {
+ vi.resetModules();
+ const messages = [];
+ const selfMock = { postMessage: (m) => messages.push(m), onmessage: null };
+ globalThis.self = selfMock;
+ await import(WORKER);
+ return {
+ messages,
+ send: (msg) => selfMock.onmessage({ data: msg }),
+ of: (type) => messages.filter((m) => m.type === type),
+ };
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/** Poll `predicate` until true or `timeout` ms elapse. */
+async function waitFor(predicate, { timeout = 5000, interval = 5 } = {}) {
+ const start = Date.now();
+ while (Date.now() - start < timeout) {
+ if (predicate()) return true;
+ await sleep(interval);
+ }
+ return false;
+}
+
+function hexToBytes(hex) {
+ const h = hex.startsWith('0x') ? hex.slice(2) : hex;
+ const out = new Uint8Array(h.length / 2);
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(h.substring(i * 2, i * 2 + 2), 16);
+ return out;
+}
+function bytesToHex(bytes) {
+ let s = '';
+ for (const b of bytes) s += b.toString(16).padStart(2, '0');
+ return s;
+}
+
+/** Independent CREATE2: keccak256(0xff ‖ deployer ‖ salt ‖ initCodeHash)[12:]. */
+function create2Address(deployer, salt, initCodeHash) {
+ const pre = new Uint8Array(1 + 20 + 32 + 32);
+ pre[0] = 0xff;
+ pre.set(hexToBytes(deployer), 1);
+ pre.set(hexToBytes(salt), 21);
+ pre.set(hexToBytes(initCodeHash), 53);
+ return '0x' + bytesToHex(keccak_256(pre).subarray(12));
+}
+
+const DEPLOYER = '0x' + '11'.repeat(20);
+const INIT_CODE_HASH = '0x' + '22'.repeat(32);
+
+describe('eth CREATE2 vanity worker', () => {
+ it('reports a match whose salt re-derives to the claimed address and honours the prefix', async () => {
+ const { send, of } = await loadWorker();
+ // '0' is 1 of 16 hex nibbles → a match lands within a handful of attempts.
+ send({ type: 'start', deployer: DEPLOYER, initCodeHash: INIT_CODE_HASH, prefix: '0', suffix: '', caseSensitive: false });
+
+ expect(await waitFor(() => of('match').length > 0)).toBe(true);
+ const match = of('match')[0];
+
+ expect(match.address.slice(2).startsWith('0')).toBe(true);
+ // The worker's salt must independently reproduce the address it claimed.
+ expect(create2Address(DEPLOYER, match.salt, INIT_CODE_HASH)).toBe(match.address);
+ expect(match.attempts).toBeGreaterThan(0);
+
+ send({ type: 'stop' });
+ });
+
+ it('honours a hex suffix as well as a prefix', async () => {
+ const { send, of } = await loadWorker();
+ send({ type: 'start', deployer: DEPLOYER, initCodeHash: INIT_CODE_HASH, prefix: '', suffix: 'a', caseSensitive: false });
+
+ expect(await waitFor(() => of('match').length > 0)).toBe(true);
+ const match = of('match')[0];
+ expect(match.address.endsWith('a')).toBe(true);
+ expect(create2Address(DEPLOYER, match.salt, INIT_CODE_HASH)).toBe(match.address);
+
+ send({ type: 'stop' });
+ });
+
+ it('rejects a malformed deployer with an error and never grinds', async () => {
+ const { send, of, messages } = await loadWorker();
+ send({ type: 'start', deployer: '0x1234', initCodeHash: INIT_CODE_HASH, prefix: 'a', suffix: '', caseSensitive: false });
+
+ // initState posts the error synchronously, before any async work.
+ expect(of('error').some((m) => /deployer must be 20 bytes/.test(m.message))).toBe(true);
+ await sleep(40);
+ expect(messages.some((m) => m.type === 'match' || m.type === 'progress')).toBe(false);
+ });
+
+ it('rejects a malformed initCodeHash with an error', async () => {
+ const { send, of } = await loadWorker();
+ send({ type: 'start', deployer: DEPLOYER, initCodeHash: '0xdead', prefix: 'a', suffix: '', caseSensitive: false });
+ expect(of('error').some((m) => /initCodeHash must be 32 bytes/.test(m.message))).toBe(true);
+ });
+
+ it('pause halts the hot loop and resume continues the same search with a monotonic count', async () => {
+ const { send, of } = await loadWorker();
+ // 6 hex chars (~1 in 16.7M) will not match within the test window, so we
+ // deterministically exercise progress → pause → resume rather than an
+ // accidental early hit.
+ send({ type: 'start', deployer: DEPLOYER, initCodeHash: INIT_CODE_HASH, prefix: 'ffffff', suffix: '', caseSensitive: false });
+
+ expect(await waitFor(() => of('progress').length >= 1)).toBe(true);
+
+ send({ type: 'pause' });
+ await sleep(40); // let the in-flight batch unwind past its yield
+ const countAtPause = of('progress').length;
+ const attemptsAtPause = of('progress')[countAtPause - 1].attempts;
+
+ // While paused the loop is gone — no new progress is emitted.
+ await sleep(80);
+ expect(of('progress').length).toBe(countAtPause);
+
+ send({ type: 'resume' });
+ expect(await waitFor(() => of('progress').length > countAtPause)).toBe(true);
+ const resumed = of('progress')[of('progress').length - 1];
+ // Monotonic: the attempt counter continued, it was not reset to zero.
+ expect(resumed.attempts).toBeGreaterThan(attemptsAtPause);
+
+ send({ type: 'stop' });
+ await sleep(40);
+ const afterStop = of('progress').length;
+ await sleep(60);
+ expect(of('progress').length).toBe(afterStop);
+ });
+
+ it('resume is a no-op when no grind was ever started', async () => {
+ const { send, messages } = await loadWorker();
+ send({ type: 'resume' });
+ await sleep(40);
+ expect(messages.length).toBe(0);
+ });
+});
diff --git a/tests/token-allowance.test.js b/tests/token-allowance.test.js
new file mode 100644
index 000000000..861cc5a51
--- /dev/null
+++ b/tests/token-allowance.test.js
@@ -0,0 +1,143 @@
+// Unit tests for the $THREE spend-allowance encoders (api/_lib/token/allowance.js).
+//
+// These pin the on-chain wire format against the native Subscriptions program's
+// published IDL: instruction discriminators, argument byte layouts, account
+// ordering/signer flags, PDA seeds, and account-state offsets. A drift in any
+// constant — which would silently send malformed instructions or misread a
+// balance — fails here before it can reach mainnet.
+
+import { describe, it, expect } from 'vitest';
+import { PublicKey } from '@solana/web3.js';
+import {
+ SUBSCRIPTIONS_PROGRAM_ID,
+ subscriptionAuthorityPda,
+ fixedDelegationPda,
+ eventAuthorityPda,
+ ixInitSubscriptionAuthority,
+ ixCreateFixedDelegation,
+ ixTransferFixed,
+ parseSubscriptionAuthorityInitId,
+ parseFixedDelegation,
+} from '../api/_lib/token/allowance.js';
+
+const USER = new PublicKey('9MjzHaTB6Jko4YKo9mDzJSaGnktzhbebgsnqPpYWnXC7');
+const DELEGATEE = new PublicKey('De1egAFMkMWZSN5rYXRj9CAdheBamobVNubTsi9avR44');
+const MINT = new PublicKey('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump');
+
+describe('program identity', () => {
+ it('uses the audited native Subscriptions program id', () => {
+ expect(SUBSCRIPTIONS_PROGRAM_ID.toBase58()).toBe('De1egAFMkMWZSN5rYXRj9CAdheBamobVNubTsi9avR44');
+ });
+});
+
+describe('PDA derivation', () => {
+ it('subscription authority is deterministic and program-owned', () => {
+ const a = subscriptionAuthorityPda(USER, MINT);
+ const b = subscriptionAuthorityPda(USER, MINT);
+ expect(a.toBase58()).toBe(b.toBase58());
+ // Re-derive with the documented seeds and confirm it matches.
+ const [expected] = PublicKey.findProgramAddressSync(
+ [Buffer.from('SubscriptionAuthority'), USER.toBuffer(), MINT.toBuffer()],
+ SUBSCRIPTIONS_PROGRAM_ID,
+ );
+ expect(a.toBase58()).toBe(expected.toBase58());
+ });
+
+ it('fixed-delegation PDA varies by nonce', () => {
+ const sa = subscriptionAuthorityPda(USER, MINT);
+ const d0 = fixedDelegationPda({ subscriptionAuthority: sa, delegator: USER, delegatee: DELEGATEE, nonce: 0 });
+ const d1 = fixedDelegationPda({ subscriptionAuthority: sa, delegator: USER, delegatee: DELEGATEE, nonce: 1 });
+ expect(d0.toBase58()).not.toBe(d1.toBase58());
+ });
+
+ it('event authority is a constant PDA', () => {
+ const [expected] = PublicKey.findProgramAddressSync([Buffer.from('event_authority')], SUBSCRIPTIONS_PROGRAM_ID);
+ expect(eventAuthorityPda().toBase58()).toBe(expected.toBase58());
+ });
+});
+
+describe('instruction encodings', () => {
+ it('initSubscriptionAuthority: discriminator 0, 6 accounts, owner is the only signer', () => {
+ const ix = ixInitSubscriptionAuthority({ owner: USER, mint: MINT });
+ expect(ix.programId.equals(SUBSCRIPTIONS_PROGRAM_ID)).toBe(true);
+ expect([...ix.data]).toEqual([0]);
+ expect(ix.keys).toHaveLength(6);
+ expect(ix.keys[0].pubkey.equals(USER)).toBe(true);
+ expect(ix.keys[0].isSigner).toBe(true);
+ expect(ix.keys[0].isWritable).toBe(true);
+ expect(ix.keys.filter((k) => k.isSigner)).toHaveLength(1);
+ });
+
+ it('createFixedDelegation: disc 1 + nonce(u64) + amount(u64) + expiry(i64) + initId(i64) little-endian', () => {
+ const ix = ixCreateFixedDelegation({
+ delegator: USER,
+ delegatee: DELEGATEE,
+ nonce: 7,
+ amount: 123_456n,
+ expiryTs: 1_900_000_000,
+ expectedInitId: 1_750_000_000,
+ mint: MINT,
+ });
+ expect(ix.data[0]).toBe(1);
+ const d = Buffer.from(ix.data);
+ expect(d.readBigUInt64LE(1)).toBe(7n);
+ expect(d.readBigUInt64LE(9)).toBe(123_456n);
+ expect(d.readBigInt64LE(17)).toBe(1_900_000_000n);
+ expect(d.readBigInt64LE(25)).toBe(1_750_000_000n);
+ expect(d.length).toBe(33); // 1 + 8 + 8 + 8 + 8
+ expect(ix.keys[0].isSigner).toBe(true); // delegator signs the grant
+ });
+
+ it('transferFixed: disc 4 + amount(u64) + delegator(32) + mint(32); delegatee is the signer', () => {
+ const delegationPda = fixedDelegationPda({
+ subscriptionAuthority: subscriptionAuthorityPda(USER, MINT),
+ delegator: USER,
+ delegatee: DELEGATEE,
+ nonce: 0,
+ });
+ const ix = ixTransferFixed({
+ delegationPda,
+ delegator: USER,
+ delegatee: DELEGATEE,
+ receiver: MINT, // any pubkey works as a receiver owner for encoding
+ amount: 5000n,
+ mint: MINT,
+ });
+ expect(ix.data[0]).toBe(4);
+ const d = Buffer.from(ix.data);
+ expect(d.readBigUInt64LE(1)).toBe(5000n);
+ expect(new PublicKey(d.subarray(9, 41)).equals(USER)).toBe(true);
+ expect(new PublicKey(d.subarray(41, 73)).equals(MINT)).toBe(true);
+ expect(d.length).toBe(73); // 1 + 8 + 32 + 32
+ expect(ix.keys).toHaveLength(9);
+ // The delegatee (platform delegate) is the sole signer on a pull.
+ const signers = ix.keys.filter((k) => k.isSigner);
+ expect(signers).toHaveLength(1);
+ expect(signers[0].pubkey.equals(DELEGATEE)).toBe(true);
+ // Last account is the program itself (self CPI for event emission).
+ expect(ix.keys[ix.keys.length - 1].pubkey.equals(SUBSCRIPTIONS_PROGRAM_ID)).toBe(true);
+ });
+});
+
+describe('account-state parsers', () => {
+ it('reads the subscription authority init-id at its documented offset', () => {
+ const buf = Buffer.alloc(106);
+ buf.writeBigInt64LE(1_751_234_567n, 98);
+ expect(parseSubscriptionAuthorityInitId(buf)).toBe(1_751_234_567);
+ expect(parseSubscriptionAuthorityInitId(Buffer.alloc(10))).toBeNull(); // too short
+ });
+
+ it('decodes a fixed-delegation account: parties, remaining balance, expiry', () => {
+ const buf = Buffer.alloc(187);
+ USER.toBuffer().copy(buf, 3); // header.delegator
+ DELEGATEE.toBuffer().copy(buf, 35); // header.delegatee
+ buf.writeBigUInt64LE(42_000n, 171); // remaining amount (decrements per pull)
+ buf.writeBigInt64LE(1_888_000_000n, 179); // expiry
+ const parsed = parseFixedDelegation(buf);
+ expect(parsed.delegator).toBe(USER.toBase58());
+ expect(parsed.delegatee).toBe(DELEGATEE.toBase58());
+ expect(parsed.remaining).toBe(42_000n);
+ expect(parsed.expiryTs).toBe(1_888_000_000);
+ expect(parseFixedDelegation(Buffer.alloc(100))).toBeNull(); // undersized
+ });
+});