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 allowance ops, Helius failover, vanity grinding, and x402 merchant updates

nirholasf23794a3c714
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14befa826..bafa59e48 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **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]`
- **Free photo → 3D is now a one-click engine in Forge** — Turning a photo into a 3D model is free — and now you can pick it directly. Forge's engine selector has a new 'Hunyuan3D / TRELLIS' lane marked with a FREE badge that reconstructs your uploaded photo (or 2–4 angles) into a textured GLB at no cost and with no API key, running on community GPU Spaces with automatic failover across Hunyuan3D, TRELLIS, and TripoSR. Until now the free photo lane only kicked in behind the scenes; it's a first-class choice in the picker, shows live availability, and never silently falls back to a paid engine. The FREE badge also marks every other no-cost lane so you can always see which engines cost nothing. (`/forge`) `[feature, improvement]`
+- **Hardened on-chain confirmations and faster profile loads** — Two reliability fixes for everyone trading, launching, and browsing. First: every on-chain action that moves funds — coin launches, buys and sells, buybacks, payouts, transfers — now treats a transaction that lands but reverts as a real failure instead of quietly reporting success. You'll see an accurate error and your spending limit won't be charged for a trade that didn't go through. Second: public profile and creator pages are now cacheable at the edge, so they load noticeably faster under load. No action needed — these apply automatically. `[fix, security, 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/api/_lib/helius.js b/api/_lib/helius.js
index 529192f7f..d14bf741d 100644
--- a/api/_lib/helius.js
+++ b/api/_lib/helius.js
@@ -22,6 +22,14 @@ function apiKey() {
return k;
}
+// All Helius calls run inside serverless functions with a hard maxDuration. A
+// hung Helius socket must not pin a function open to its limit, so every request
+// carries a bounded abort. 10s is generous for a webhook-management API.
+const HELIUS_TIMEOUT_MS = 10_000;
+function heliusFetch(url, init = {}) {
+ return fetch(url, { ...init, signal: AbortSignal.timeout(HELIUS_TIMEOUT_MS) });
+}
+
export function heliusEnabled() {
return Boolean(process.env.HELIUS_API_KEY && process.env.HELIUS_WEBHOOK_AUTH);
}
@@ -32,7 +40,7 @@ export function heliusEnabled() {
* @param {{ wallets: string[], webhookURL: string, network?: 'mainnet'|'devnet' }} opts
*/
export async function createWebhook({ wallets, webhookURL, network = 'mainnet' }) {
- const r = await fetch(`${HELIUS_API}?api-key=${apiKey()}`, {
+ const r = await heliusFetch(`${HELIUS_API}?api-key=${apiKey()}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
@@ -49,7 +57,7 @@ export async function createWebhook({ wallets, webhookURL, network = 'mainnet' }
/** Replace `accountAddresses` on an existing webhook (use to add/remove wallets in batch). */
export async function updateWebhookWallets(webhookID, wallets) {
- const r = await fetch(`${HELIUS_API}/${webhookID}?api-key=${apiKey()}`, {
+ const r = await heliusFetch(`${HELIUS_API}/${webhookID}?api-key=${apiKey()}`, {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ accountAddresses: wallets }),
@@ -59,13 +67,13 @@ export async function updateWebhookWallets(webhookID, wallets) {
}
export async function listWebhooks() {
- const r = await fetch(`${HELIUS_API}?api-key=${apiKey()}`);
+ const r = await heliusFetch(`${HELIUS_API}?api-key=${apiKey()}`);
if (!r.ok) throw new Error(`helius list failed: ${r.status}`);
return r.json();
}
export async function deleteWebhook(webhookID) {
- const r = await fetch(`${HELIUS_API}/${webhookID}?api-key=${apiKey()}`, { method: 'DELETE' });
+ const r = await heliusFetch(`${HELIUS_API}/${webhookID}?api-key=${apiKey()}`, { method: 'DELETE' });
if (!r.ok && r.status !== 404) throw new Error(`helius delete failed: ${r.status}`);
}
diff --git a/api/_lib/market/token-market.js b/api/_lib/market/token-market.js
index b05de640b..e1ce20a68 100644
--- a/api/_lib/market/token-market.js
+++ b/api/_lib/market/token-market.js
@@ -12,6 +12,8 @@
// they can and never crash on a single upstream blip. This is the market-data
// analogue of the RPC failover layer.
+import { cacheGet, cacheSet } from '../cache.js';
+
const BIRDEYE_BASE = 'https://public-api.birdeye.so';
const DEXSCREENER_BASE = 'https://api.dexscreener.com/latest/dex/tokens';
const GECKOTERMINAL_BASE = 'https://api.geckoterminal.com/api/v2/networks/solana/tokens';
@@ -20,6 +22,16 @@ const FETCH_TIMEOUT_MS = 6000;
const DEFAULT_TTL_MS = 30_000;
const STALE_MAX_MS = 5 * 60_000;
+// L2 (shared, cross-instance) cache TTL. Scaling defense: Vercel runs many
+// stateless lambda instances; the per-instance L1 Map below is wiped on every
+// cold start, so under a traffic spike each cold instance would independently
+// fan out to all three upstreams. The L2 Upstash cache lets a cold lambda serve
+// a sibling's recent fetch instead, collapsing fleet-wide upstream load to ~1
+// call per key per window — the difference between "holds at 100x" and "every
+// instance rate-limits Birdeye at once". Short window keeps a token price fresh.
+const SHARED_TTL_S = 15;
+const sharedKey = (mint) => `mktdata:v1:${mint}`;
+
const _cache = new Map(); // mint → { value, expires, fetchedAt }
const _warnedAt = new Map();
const WARN_COOLDOWN_MS = 60_000;
@@ -159,7 +171,25 @@ const SOURCES = [fromBirdeye, fromDexScreener, fromGeckoTerminal];
export async function fetchTokenMarketData(mint, { fresh = false, ttlMs = DEFAULT_TTL_MS } = {}) {
const now = Date.now();
const hit = _cache.get(mint);
- if (!fresh && hit && hit.expires > now) return hit.value;
+ if (!fresh && hit && hit.expires > now) return hit.value; // L1: warm in-process
+
+ // L2: shared cross-instance cache. A cold lambda (no L1) serves a sibling's
+ // recent fetch instead of hitting three upstreams — the core scaling defense.
+ // cache.js already single-flights + memoizes GETs, so a burst of cold reads
+ // collapses to one Redis round-trip. Best-effort: any cache error falls through
+ // to a live fetch, never failing the read.
+ if (!fresh) {
+ try {
+ const shared = await cacheGet(sharedKey(mint));
+ if (shared && shared.price_usd > 0) {
+ _cache.set(mint, { value: shared, expires: now + ttlMs, fetchedAt: now });
+ if (_cache.size > 256) _cache.delete(_cache.keys().next().value);
+ return shared;
+ }
+ } catch {
+ /* fall through to live fetch */
+ }
+ }
for (const src of SOURCES) {
if ((_sourceCooldown.get(src.name) || 0) > now) continue;
@@ -168,6 +198,8 @@ export async function fetchTokenMarketData(mint, { fresh = false, ttlMs = DEFAUL
if (result && result.price_usd > 0) {
_cache.set(mint, { value: result, expires: now + ttlMs, fetchedAt: now });
if (_cache.size > 256) _cache.delete(_cache.keys().next().value);
+ // Publish to the shared cache for sibling instances (best-effort).
+ cacheSet(sharedKey(mint), result, SHARED_TTL_S).catch(() => {});
return result;
}
} catch (err) {
diff --git a/api/_lib/memory-store.js b/api/_lib/memory-store.js
index 1ca433be3..956e9e5be 100644
--- a/api/_lib/memory-store.js
+++ b/api/_lib/memory-store.js
@@ -288,7 +288,8 @@ export async function ensureEntities(agentId, cap = ENTITY_CAP) {
]);
const upserted = await sql`
INSERT INTO agent_memory_entities (agent_id, kind, label, normalized, mention_count, salience, meta)
- SELECT v.agent_id, v.kind, v.label, v.normalized, v.cnt, 0.5, v.meta::jsonb
+ SELECT v.agent_id, v.kind, v.label, v.normalized, v.cnt::int,
+ LEAST(1.0, 0.5 + 0.05 * (v.cnt::int - 1)), v.meta::jsonb
FROM ( VALUES ${sqlValues(entityRows)} ) AS v(agent_id, kind, label, normalized, cnt, meta)
ON CONFLICT (agent_id, kind, normalized) DO UPDATE
SET mention_count = agent_memory_entities.mention_count + EXCLUDED.mention_count,
diff --git a/api/_lib/pump-vanity.js b/api/_lib/pump-vanity.js
index 8cc4c0878..8a50b76ab 100644
--- a/api/_lib/pump-vanity.js
+++ b/api/_lib/pump-vanity.js
@@ -54,6 +54,28 @@ export function isValidVanityPrefix(prefix) {
return true;
}
+/**
+ * Does `address` satisfy the requested vanity pattern? The security boundary
+ * for adopting a browser-ground keypair: the server must NEVER trust a client's
+ * claim that a key is "vanity" — it re-derives the address and checks it here.
+ * Case-insensitive matching is applied only when the owner explicitly asked for
+ * it; otherwise an exact (case-sensitive) match is required.
+ *
+ * @param {string} address Base58 public key.
+ * @param {{ prefix?: string, suffix?: string, ignoreCase?: boolean }} pattern
+ * @returns {boolean}
+ */
+export function addressMatchesPattern(address, { prefix = '', suffix = '', ignoreCase = false } = {}) {
+ if (typeof address !== 'string' || !address) return false;
+ if (!prefix && !suffix) return false;
+ const probe = ignoreCase ? address.toLowerCase() : address;
+ const wantP = prefix ? (ignoreCase ? prefix.toLowerCase() : prefix) : '';
+ const wantS = suffix ? (ignoreCase ? suffix.toLowerCase() : suffix) : '';
+ if (wantP && !probe.startsWith(wantP)) return false;
+ if (wantS && !probe.endsWith(wantS)) return false;
+ return true;
+}
+
// Estimated attempts ≈ 58^n (per pattern position). Used by callers to set
// a reasonable maxIterations and to surface difficulty in error messages.
export function estimateAttempts({ prefix, suffix, ignoreCase = false } = {}) {
diff --git a/api/_lib/solana-signers.js b/api/_lib/solana-signers.js
index abb35b062..28113d8e8 100644
--- a/api/_lib/solana-signers.js
+++ b/api/_lib/solana-signers.js
@@ -118,7 +118,7 @@ export async function decodeSecretKey(secret) {
try {
const arr = JSON.parse(raw);
if (Array.isArray(arr) && (arr.length === 64 || arr.length === 32)) {
- return Uint8Array.from(arr);
+ return toFullSecretKey(Uint8Array.from(arr));
}
} catch {
/* fall through */
@@ -132,7 +132,7 @@ export async function decodeSecretKey(secret) {
// Guard against base58 strings that happen to base64-decode to 64 bytes:
// re-encode and compare, accept only on round-trip match.
if (buf.toString('base64').replace(/=+$/, '') === raw.replace(/=+$/, '')) {
- return new Uint8Array(buf);
+ return toFullSecretKey(new Uint8Array(buf));
}
}
} catch {
@@ -144,7 +144,7 @@ export async function decodeSecretKey(secret) {
const bs58mod = await import('bs58');
const bs58 = bs58mod.default || bs58mod;
const bytes = bs58.decode(raw);
- if (bytes.length === 64 || bytes.length === 32) return Uint8Array.from(bytes);
+ if (bytes.length === 64 || bytes.length === 32) return toFullSecretKey(Uint8Array.from(bytes));
} catch {
/* fall through */
}
@@ -152,6 +152,19 @@ export async function decodeSecretKey(secret) {
return null;
}
+// Normalize to a full 64-byte ed25519 secret key. A 32-byte value is a SEED, not
+// a secret key — passing it straight to Keypair.fromSecretKey throws or, worse,
+// resolves a DIFFERENT pubkey than intended (so a treasury/relayer signer would
+// silently sign from the wrong address). Expand the seed deterministically.
+async function toFullSecretKey(bytes) {
+ if (bytes.length === 64) return bytes;
+ if (bytes.length === 32) {
+ const { Keypair } = await import('@solana/web3.js');
+ return Keypair.fromSeed(bytes).secretKey;
+ }
+ return null;
+}
+
/**
* Resolve a SignerSpec to a loaded keypair pubkey (base58) using whichever env
* var (primary or fallback) is set. Returns null when neither is configured or
diff --git a/api/_lib/token/allowance-ops.js b/api/_lib/token/allowance-ops.js
index 2da54d325..1bed14be6 100644
--- a/api/_lib/token/allowance-ops.js
+++ b/api/_lib/token/allowance-ops.js
@@ -1,9 +1,14 @@
-// $THREE allowance — chain operations (read status, build grant, execute pull).
+// $THREE allowance — chain operations (read status, build grant/revoke, pull).
+//
+// SCALING MODEL: never getProgramAccounts on the hot path. Grants are persisted in
+// three_allowances (allowance-registry.js) with their deterministic PDAs, so a
+// status read is a single batched getMultipleAccountsInfo over the user's own few
+// PDAs, served from a short-TTL Redis cache. getProgramAccounts survives only as a
+// one-shot fallback for a wallet with zero registry rows (a grant made before this
+// index existed, or from another client) — bounded and rare.
//
// 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.
+// RPC/signing/cache shell.
import { PublicKey, Transaction } from '@solana/web3.js';
import {
@@ -12,6 +17,7 @@ import {
ASSOCIATED_TOKEN_PROGRAM_ID,
} from '@solana/spl-token';
import { solanaConnection } from '../solana/connection.js';
+import { getRedis } from '../redis.js';
import { TOKEN_MINT, ATOMICS_PER_TOKEN } from './config.js';
import {
SUBSCRIPTIONS_PROGRAM_ID,
@@ -20,92 +26,170 @@ import {
userThreeAta,
ixInitSubscriptionAuthority,
ixCreateFixedDelegation,
+ ixRevokeDelegation,
ixTransferFixed,
parseSubscriptionAuthorityInitId,
parseFixedDelegation,
loadDelegateKeypair,
delegateAddress,
} from './allowance.js';
+import {
+ recordPendingGrant,
+ markGrantActive,
+ markRevoked,
+ getAllowanceRow,
+ listWalletAllowances,
+ syncReconciled,
+} from './allowance-registry.js';
const mintPubkey = () => new PublicKey(TOKEN_MINT);
const nowSec = () => Math.floor(Date.now() / 1000);
+const STATUS_CACHE_TTL_S = 15;
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);
+function statusCacheKey(wallet, network) {
+ return `three-allow:status:${network}:${wallet}`;
+}
+
+/** Drop the cached status so the next read reflects a just-landed grant/revoke/pull. */
+export async function invalidateAllowanceStatus(wallet, network = 'mainnet') {
+ const redis = getRedis();
+ if (redis) await redis.del(statusCacheKey(wallet, network)).catch(() => {});
+}
+
+/** A delegation is spendable when it has remaining balance and is not past expiry (0 = none). */
+function isLive(remaining, expiryTs, now = nowSec()) {
+ return remaining > 0n && (expiryTs <= 0 || 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.
+ * Reconcile the user's registry rows against the chain in ONE batched RPC, write
+ * back the observed state, and return the live delegations. This is the cheap
+ * path that replaces getProgramAccounts. Returns null when the wallet has no
+ * registry rows (caller may then fall back).
*/
-export async function getAllowanceStatus(userWallet, { network = 'mainnet' } = {}) {
- const delegate = await delegateAddress();
- if (!delegate) {
- return { enabled: false, delegate: null, remaining_atomics: '0', delegations: [] };
- }
+async function reconcileFromRegistry(connection, wallet, network) {
+ const rows = await listWalletAllowances({ wallet, network });
+ if (!rows.length) return null;
- 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 pdas = rows.map((r) => new PublicKey(r.delegation_pda));
+ const infos = await connection.getMultipleAccountsInfo(pdas, 'confirmed');
+ const now = nowSec();
+ const live = [];
+
+ await Promise.all(
+ rows.map(async (row, i) => {
+ const info = infos[i];
+ if (!info) {
+ // Account gone: a still-pending grant never landed, or an active one
+ // was fully spent/closed. Mark terminal so it stops being re-read.
+ if (row.status === 'active') await syncReconciled({ delegationPda: row.delegation_pda, remainingAtomics: 0, status: 'spent' });
+ return;
+ }
+ const parsed = parseFixedDelegation(info.data);
+ if (!parsed) return;
+ // First on-chain sighting of a pending grant ⇒ it's active.
+ const nextStatus = parsed.remaining === 0n ? 'spent' : 'active';
+ // Skip the write when nothing observable changed — under load the 15s cache
+ // means each active user reconciles at most ~4×/min; this trims those to
+ // only the reconciles that actually move the balance or lifecycle.
+ const changed = row.status !== nextStatus || row.last_remaining_atomics !== parsed.remaining.toString();
+ if (changed) {
+ if (row.status === 'pending' && nextStatus !== 'pending') await markGrantActive({ delegationPda: row.delegation_pda });
+ await syncReconciled({ delegationPda: row.delegation_pda, remainingAtomics: parsed.remaining.toString(), status: nextStatus });
+ }
+ if (isLive(parsed.remaining, parsed.expiryTs, now)) {
+ live.push({ pubkey: row.delegation_pda, remaining: parsed.remaining, expiryTs: parsed.expiryTs });
+ }
+ }),
+ );
+
+ live.sort((a, b) => (b.remaining > a.remaining ? 1 : b.remaining < a.remaining ? -1 : 0));
+ return live;
+}
+/** Bounded fallback: discover delegations on-chain for a wallet with no registry rows. */
+async function discoverFromChain(connection, wallet, delegate) {
+ const accounts = await connection.getProgramAccounts(SUBSCRIPTIONS_PROGRAM_ID, {
+ filters: [
+ { dataSize: 187 },
+ { memcmp: { offset: 3, bytes: new PublicKey(wallet).toBase58() } },
+ { memcmp: { offset: 35, bytes: delegate } },
+ ],
+ });
const now = nowSec();
- const delegations = accounts
+ return accounts
.map(({ pubkey, account }) => {
const parsed = parseFixedDelegation(account.data);
- return parsed ? { pubkey: pubkey.toBase58(), ...parsed } : null;
+ return parsed ? { pubkey: pubkey.toBase58(), remaining: parsed.remaining, expiryTs: parsed.expiryTs } : null;
})
- .filter((d) => d && isLive(d, now))
+ .filter((d) => d && isLive(d.remaining, d.expiryTs, 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);
+function shapeStatus(delegate, wallet, live) {
+ const totalRemaining = live.reduce((s, d) => s + d.remaining, 0n);
return {
enabled: true,
delegate,
+ wallet,
remaining_atomics: totalRemaining.toString(),
remaining_tokens: Number(totalRemaining) / Number(ATOMICS_PER_TOKEN),
- delegations: delegations.map((d) => ({
+ delegations: live.map((d) => ({
pubkey: d.pubkey,
remaining_atomics: d.remaining.toString(),
+ remaining_tokens: Number(d.remaining) / Number(ATOMICS_PER_TOKEN),
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.
+ * The user's live $THREE spend allowance. Redis-cached (TTL 15s) and DB-indexed;
+ * `fresh: true` bypasses the cache (used by the pull path before moving funds).
*/
-export async function buildGrantTransaction({
- userWallet,
- capAtomics,
- expiryTs = 0,
- network = 'mainnet',
-}) {
+export async function getAllowanceStatus(userWallet, { network = 'mainnet', fresh = false } = {}) {
+ const delegate = await delegateAddress();
+ if (!delegate) return { enabled: false, delegate: null, wallet: userWallet, remaining_atomics: '0', delegations: [] };
+
+ const redis = getRedis();
+ const cacheKey = statusCacheKey(userWallet, network);
+ if (!fresh && redis) {
+ try {
+ const cached = await redis.get(cacheKey);
+ if (cached) return cached;
+ } catch { /* fall through to a live read */ }
+ }
+
+ const connection = conn(network);
+ let live;
+ try {
+ live = await reconcileFromRegistry(connection, userWallet, network);
+ if (live == null) live = await discoverFromChain(connection, userWallet, delegate);
+ } catch (err) {
+ // Read path never throws — degrade to "no allowance" and let the caller fall
+ // back to the signed quote flow. Don't cache a degraded result.
+ console.warn('[allowance] status read failed:', err?.message || err);
+ return { enabled: true, delegate, wallet: userWallet, remaining_atomics: '0', delegations: [], degraded: true };
+ }
+
+ const result = shapeStatus(delegate, userWallet, live);
+ if (redis) redis.set(cacheKey, result, { ex: STATUS_CACHE_TTL_S }).catch(() => {});
+ return result;
+}
+
+/**
+ * Build the user-signed GRANT transaction and persist it as a pending registry row
+ * so the status/pull paths can read it cheaply. Returns the unsigned tx (base64),
+ * the delegation PDA, and the nonce.
+ */
+export async function buildGrantTransaction({ userWallet, capAtomics, expiryTs = 0, network = 'mainnet', userId = null }) {
const delegate = await delegateAddress();
if (!delegate) {
- throw Object.assign(new Error('allowance delegate not configured'), {
- status: 503,
- code: 'allowance_unavailable',
- });
+ throw Object.assign(new Error('allowance delegate not configured'), { status: 503, code: 'allowance_unavailable' });
}
const owner = new PublicKey(userWallet);
@@ -118,24 +202,20 @@ export async function buildGrantTransaction({
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();
+ expectedInitId = nowSec(); // fresh SA: program stamps clock; within drift tolerance
} else {
expectedInitId = parseSubscriptionAuthorityInitId(saInfo.data);
if (expectedInitId == null) {
- throw Object.assign(new Error('unreadable subscription authority'), {
- status: 422,
- code: 'sa_unreadable',
- });
+ throw Object.assign(new Error('unreadable subscription authority'), { status: 422, code: 'sa_unreadable' });
}
}
const nonce = nowSec();
+ const delegatePk = new PublicKey(delegate);
instructions.push(
ixCreateFixedDelegation({
delegator: owner,
- delegatee: new PublicKey(delegate),
+ delegatee: delegatePk,
nonce,
amount: BigInt(capAtomics),
expiryTs: Math.floor(expiryTs) || 0,
@@ -150,55 +230,124 @@ export async function buildGrantTransaction({
tx.feePayer = owner;
tx.recentBlockhash = blockhash;
- const serialized = tx
- .serialize({ requireAllSignatures: false, verifySignatures: false })
- .toString('base64');
+ const delegationPda = fixedDelegationPda({ subscriptionAuthority: sa, delegator: owner, delegatee: delegatePk, nonce });
+
+ // Persist intent before the user signs, so confirm + status can find it. A
+ // never-sent grant simply stays 'pending' and is reconciled away on next read.
+ await recordPendingGrant({
+ userId,
+ wallet: userWallet,
+ mint: TOKEN_MINT,
+ delegate,
+ delegationPda: delegationPda.toBase58(),
+ subscriptionAuthority: sa.toBase58(),
+ nonce,
+ capAtomics: BigInt(capAtomics).toString(),
+ expiryTs: Math.floor(expiryTs) || 0,
+ network,
+ }).catch((err) => console.warn('[allowance] recordPendingGrant failed (non-fatal):', err?.message || err));
return {
- transaction: serialized,
- delegation_pda: fixedDelegationPda({
- subscriptionAuthority: sa,
- delegator: owner,
- delegatee: new PublicKey(delegate),
- nonce,
- }).toBase58(),
+ transaction: tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64'),
+ delegation_pda: delegationPda.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.
+ * Reconcile a single delegation PDA after a signed grant or revoke landed, and
+ * update the registry. `revoked: true` marks it revoked once the account is gone.
+ * Returns the new lifecycle state + remaining for an instant, accurate UI update.
+ */
+export async function confirmAllowance({ userWallet, delegationPda, revoked = false, network = 'mainnet' }) {
+ // Ownership guard: a registry row must belong to the caller before we mutate it,
+ // so one user can never flip another user's allowance state in our index. A
+ // legacy/external grant with no row is validated against the on-chain delegator
+ // below instead.
+ const row = await getAllowanceRow(delegationPda);
+ if (row && row.wallet !== userWallet) {
+ throw Object.assign(new Error('not your allowance'), { status: 403, code: 'forbidden' });
+ }
+
+ const connection = conn(network);
+ const info = await connection.getAccountInfo(new PublicKey(delegationPda), 'confirmed');
+
+ if (!info) {
+ // Only a known-owned row may be marked terminal on a missing account; without
+ // a row we can't prove ownership of a vanished account, so we no-op.
+ if (row) {
+ if (revoked) await markRevoked({ delegationPda });
+ else await syncReconciled({ delegationPda, remainingAtomics: 0, status: 'spent' });
+ await invalidateAllowanceStatus(userWallet, network);
+ }
+ return { active: false, status: revoked ? 'revoked' : 'spent', remaining_atomics: '0' };
+ }
+
+ const parsed = parseFixedDelegation(info.data);
+ // For an external grant (no row), bind the confirm to the on-chain delegator.
+ if (!row && parsed && parsed.delegator !== userWallet) {
+ throw Object.assign(new Error('not your allowance'), { status: 403, code: 'forbidden' });
+ }
+ const remaining = parsed?.remaining ?? 0n;
+ const status = remaining === 0n ? 'spent' : 'active';
+ if (status === 'active') await markGrantActive({ delegationPda });
+ await syncReconciled({ delegationPda, remainingAtomics: remaining.toString(), status });
+ await invalidateAllowanceStatus(userWallet, network);
+ return { active: status === 'active', status, remaining_atomics: remaining.toString() };
+}
+
+/**
+ * Build the user-signed REVOKE transaction for one of their delegations. Ownership
+ * is checked against the registry (the wallet must own the row) so a user can only
+ * revoke their own grant.
+ */
+export async function buildRevokeTransaction({ userWallet, delegationPda, network = 'mainnet' }) {
+ const row = await getAllowanceRow(delegationPda);
+ if (row && row.wallet !== userWallet) {
+ throw Object.assign(new Error('not your allowance'), { status: 403, code: 'forbidden' });
+ }
+
+ const owner = new PublicKey(userWallet);
+ const connection = conn(network);
+ const tx = new Transaction();
+ tx.add(ixRevokeDelegation({ authority: owner, delegationPda }));
+ const { blockhash } = await connection.getLatestBlockhash('confirmed');
+ tx.feePayer = owner;
+ tx.recentBlockhash = blockhash;
+
+ return {
+ transaction: tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64'),
+ delegation_pda: delegationPda,
+ recent_blockhash: blockhash,
+ };
+}
+
+/**
+ * Pull `legs` from the user's wallet against an existing allowance in a single
+ * delegate-signed transaction — no user popup. Reads candidates FRESH (bypassing
+ * the status cache) so it never moves funds on a stale balance.
*
- * Throws code 'insufficient_allowance' when no single live delegation covers the
- * total — the caller treats that as "fall back to the signed quote flow".
+ * Throws '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',
- });
+ 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' });
- }
+ 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 status = await getAllowanceStatus(userWallet, { network, fresh: true });
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 },
- );
+ 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);
@@ -208,7 +357,6 @@ export async function pullFromAllowance({ userWallet, legs, network = 'mainnet'
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,
@@ -236,10 +384,7 @@ export async function pullFromAllowance({ userWallet, legs, network = 'mainnet'
tx.recentBlockhash = blockhash;
tx.sign(delegate);
- const signature = await connection.sendRawTransaction(tx.serialize(), {
- skipPreflight: false,
- maxRetries: 3,
- });
+ const signature = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });
const confirmation = await connection.confirmTransaction(
{ signature, blockhash, lastValidBlockHeight },
'confirmed',
@@ -252,10 +397,21 @@ export async function pullFromAllowance({ userWallet, legs, network = 'mainnet'
});
}
+ // Reflect the spend immediately: decrement the cached/registry remaining and
+ // drop the status cache so the next read is accurate.
+ const remainingAfter = BigInt(covering.remaining_atomics) - total;
+ await syncReconciled({
+ delegationPda: covering.pubkey,
+ remainingAtomics: remainingAfter.toString(),
+ status: remainingAfter === 0n ? 'spent' : 'active',
+ }).catch(() => {});
+ await invalidateAllowanceStatus(userWallet, network);
+
return {
signature,
delegation_pda: covering.pubkey,
total_atomics: total.toString(),
+ remaining_after_atomics: remainingAfter.toString(),
slot: confirmation.context?.slot ?? null,
};
}
diff --git a/api/_lib/token/index.js b/api/_lib/token/index.js
index 4b580c46c..511f1a42e 100644
--- a/api/_lib/token/index.js
+++ b/api/_lib/token/index.js
@@ -24,4 +24,11 @@ export {
} from './payments.js';
export { computeRewardsDistribution } from './rewards.js';
export { allowanceEnabled, delegateAddress } from './allowance.js';
-export { getAllowanceStatus, buildGrantTransaction, pullFromAllowance } from './allowance-ops.js';
+export {
+ getAllowanceStatus,
+ buildGrantTransaction,
+ confirmAllowance,
+ buildRevokeTransaction,
+ pullFromAllowance,
+ invalidateAllowanceStatus,
+} from './allowance-ops.js';
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index b5324d616..d25704621 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -19,7 +19,7 @@ import {
createAssociatedTokenAccountIdempotentInstruction, createCloseAccountInstruction, getMint,
TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
} from '@solana/spl-token';
-import { grindMintKeypair, estimateAttempts, BASE58_ALPHABET } from '../_lib/pump-vanity.js';
+import { grindMintKeypair, estimateAttempts, BASE58_ALPHABET, addressMatchesPattern } from '../_lib/pump-vanity.js';
import { randomUUID } from 'node:crypto';
import { recordEvent } from '../_lib/usage.js';
import { cacheGet, cacheSet } from '../_lib/cache.js';
@@ -1183,31 +1183,58 @@ async function handleVanity(req, res, id) {
if (!prefix && !suffix) return error(res, 400, 'validation_error', 'provide a prefix and/or suffix');
const combinedLen = (prefix?.length || 0) + (suffix?.length || 0);
- if (combinedLen > VANITY_MAX_CHARS) {
- return error(res, 400, 'pattern_too_hard',
- `server-side grinding supports up to ${VANITY_MAX_CHARS} combined characters. ` +
- `Grind longer patterns in your browser at /vanity-wallet (GPU-accelerated, up to 8 chars) and assign the result.`);
- }
- // Grind the vanity keypair. The secret stays in process memory only.
- let ground;
- try {
- const est = estimateAttempts({ prefix, suffix, ignoreCase });
- const maxIterations = Math.min(VANITY_MAX_ITERATIONS, Math.max(200_000, Math.ceil(est * 25)));
- // Bail before the function's maxDuration (45s, see vercel.json) so the grind
- // returns a clean `vanity_timeout` 504 instead of a hard runtime kill, and
- // still leaves headroom to sweep the wallet to the new address afterward.
- ground = await grindMintKeypair({ prefix, suffix, ignoreCase, maxIterations, maxMs: VANITY_GRIND_BUDGET_MS });
- } catch (e) {
- if (e?.code === 'vanity_timeout') {
- return error(res, 504, 'vanity_timeout', 'could not find a matching address in time — try a shorter pattern or grind it in the browser at /vanity-wallet');
+ // Two ways to supply the new keypair, both ending in the identical sweep-then-
+ // swap below so funds are equally safe either way:
+ // (A) `secret_key` — a 64-byte Ed25519 key the owner ground in their browser
+ // at full speed (worker pool, longer patterns, case-insensitive). We
+ // re-derive the address and prove it matches the requested pattern before
+ // adopting it — the client's "this is vanity" claim is never trusted.
+ // (B) no key — a bounded server-side grind for short patterns only.
+ let ground = null;
+ let newKp;
+
+ if (body.secret_key != null) {
+ const sk = body.secret_key;
+ if (!Array.isArray(sk) || sk.length !== 64 || !sk.every((n) => Number.isInteger(n) && n >= 0 && n <= 255)) {
+ return error(res, 400, 'validation_error', 'secret_key must be a 64-byte number array');
+ }
+ try {
+ newKp = Keypair.fromSecretKey(Uint8Array.from(sk));
+ } catch {
+ return error(res, 400, 'validation_error', 'secret_key did not parse as a valid Solana keypair');
+ }
+ // Verify the supplied address genuinely satisfies the pattern — the
+ // client's "this is vanity" claim is never trusted.
+ const claimed = newKp.publicKey.toBase58();
+ if (!addressMatchesPattern(claimed, { prefix, suffix, ignoreCase })) {
+ return error(res, 400, 'validation_error', 'the supplied address does not match the requested prefix/suffix');
+ }
+ } else {
+ if (combinedLen > VANITY_MAX_CHARS) {
+ return error(res, 400, 'pattern_too_hard',
+ `server-side grinding supports up to ${VANITY_MAX_CHARS} combined characters. ` +
+ `Grind longer patterns in your browser (this tab grinds with your CPU cores) — they assign automatically.`);
+ }
+ // Grind the vanity keypair. The secret stays in process memory only.
+ try {
+ const est = estimateAttempts({ prefix, suffix, ignoreCase });
+ const maxIterations = Math.min(VANITY_MAX_ITERATIONS, Math.max(200_000, Math.ceil(est * 25)));
+ // Bail before the function's maxDuration (45s, see vercel.json) so the grind
+ // returns a clean `vanity_timeout` 504 instead of a hard runtime kill, and
+ // still leaves headroom to sweep the wallet to the new address afterward.
+ ground = await grindMintKeypair({ prefix, suffix, ignoreCase, maxIterations, maxMs: VANITY_GRIND_BUDGET_MS });
+ } catch (e) {
+ if (e?.code === 'vanity_timeout') {
+ return error(res, 504, 'vanity_timeout', 'could not find a matching address in time — try a shorter pattern or grind it in the browser');
+ }
+ if (e?.code === 'invalid_vanity') return error(res, 400, 'validation_error', e.message);
+ console.error('[agents/solana/vanity] grind failed', e?.message);
+ return error(res, 502, 'grind_failed', 'vanity grind failed — try again');
}
- if (e?.code === 'invalid_vanity') return error(res, 400, 'validation_error', e.message);
- console.error('[agents/solana/vanity] grind failed', e?.message);
- return error(res, 502, 'grind_failed', 'vanity grind failed — try again');
+ newKp = ground.keypair;
}
- const newKp = ground.keypair;
const newAddress = newKp.publicKey.toBase58();
// If the agent already holds a funded custodial wallet, migrate the balance to
@@ -1263,13 +1290,14 @@ async function handleVanity(req, res, id) {
}
// Persist the new keypair as the agent's custodial wallet.
+ const walletSource = ground ? 'vanity_grind' : 'imported_vanity';
const encrypted_secret = await _encryptSecret(Buffer.from(newKp.secretKey).toString('base64'));
const history = Array.isArray(meta.solana_wallet_history) ? meta.solana_wallet_history : [];
const nextMeta = {
...meta,
solana_address: newAddress,
encrypted_solana_secret: encrypted_secret,
- solana_wallet_source: 'vanity_grind',
+ solana_wallet_source: walletSource,
solana_vanity_prefix: prefix || null,
solana_vanity_suffix: suffix || null,
};
@@ -1286,9 +1314,11 @@ async function handleVanity(req, res, id) {
if (currentAddress) await cacheSet(`sol:bal:${currentAddress}:${network}`, null, 1).catch(() => {});
await cacheSet(`sol:bal:${newAddress}:${network}`, null, 1).catch(() => {});
+ const iterations = ground ? ground.iterations : (Number.isFinite(Number(body.iterations)) ? Number(body.iterations) : null);
+ const durationMs = ground ? ground.durationMs : (Number.isFinite(Number(body.duration_ms)) ? Number(body.duration_ms) : null);
recordEvent({
- userId: auth.userId, agentId: id, kind: 'solana_vanity_grind', tool: 'server', status: 'ok',
- meta: { address: newAddress, prefix, suffix, ignoreCase, iterations: ground.iterations, swept: swept ? { sol: swept.sol, tokens: swept.tokens.length } : null },
+ userId: auth.userId, agentId: id, kind: 'solana_vanity_grind', tool: ground ? 'server' : 'browser', status: 'ok',
+ meta: { address: newAddress, prefix, suffix, ignoreCase, iterations, swept: swept ? { sol: swept.sol, tokens: swept.tokens.length } : null },
});
logAudit({ userId: auth.userId, action: 'custody.vanity_grind', resourceId: id, meta: { address: newAddress, prefix, suffix, replaced: currentAddress || null, swept: !!swept }, req });
@@ -1298,11 +1328,11 @@ async function handleVanity(req, res, id) {
vanity_prefix: prefix,
vanity_suffix: suffix,
network,
- iterations: ground.iterations,
- duration_ms: ground.durationMs,
+ iterations,
+ duration_ms: durationMs,
replaced: currentAddress && currentAddress !== newAddress ? currentAddress : null,
swept,
- source: 'vanity_grind',
+ source: walletSource,
},
});
}
diff --git a/api/forge.js b/api/forge.js
index 5ce423519..fec675a4b 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -1428,9 +1428,16 @@ export default wrap(async (req, res) => {
// ?catalog — the tier + backend + cost/time matrix the composer renders.
// Public, no secrets; lets the UI communicate the time/cost trade-off and
- // which backends are live before the user commits.
+ // which backends are live before the user commits. The payload only changes
+ // on a redeploy (tiers/backends are static; `configured` reflects env
+ // presence), so it is heavily CDN-cacheable — one of the hottest GETs on the
+ // site (every /forge load), now served almost entirely from the edge instead
+ // of recomputing per request. stale-while-revalidate keeps it instant even as
+ // the cache refreshes in the background.
if (url.searchParams.has('catalog')) {
- return json(res, 200, buildCatalog());
+ return json(res, 200, buildCatalog(), {
+ 'cache-control': 'public, max-age=60, s-maxage=600, stale-while-revalidate=86400',
+ });
}
// ?health — live-probes every platform backend's upstream (auth + quota
@@ -1441,7 +1448,14 @@ export default wrap(async (req, res) => {
const rl = await limits.mcp3dStatus(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
const { probeForgeHealth } = await import('./_lib/forge-health.js');
- return json(res, 200, await probeForgeHealth());
+ // The probe already memoizes per instance (60s TTL); a short edge cache
+ // collapses an influx of identical health polls into one shared response
+ // every ~30s instead of one origin probe per client. stale-while-revalidate
+ // means a client never waits on a refresh — it sees the live status surface
+ // update within ~30s while the CDN absorbs the load.
+ return json(res, 200, await probeForgeHealth(), {
+ 'cache-control': 'public, max-age=15, s-maxage=30, stale-while-revalidate=120',
+ });
}
const jobId = (url.searchParams.get('job') || '').trim();
diff --git a/api/token/[action].js b/api/token/[action].js
index f5e9200a1..f0f0a1285 100644
--- a/api/token/[action].js
+++ b/api/token/[action].js
@@ -25,6 +25,8 @@ import {
listPayments,
getAllowanceStatus,
buildGrantTransaction,
+ confirmAllowance,
+ buildRevokeTransaction,
delegateAddress,
} from '../_lib/token/index.js';
@@ -197,6 +199,8 @@ async function handleAllowanceStatus(req, res) {
if (!method(req, res, ['GET'])) return;
const user = await getSessionUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.tokenPriceIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
const delegate = await delegateAddress();
if (!delegate) {
@@ -254,6 +258,7 @@ async function handleAllowanceGrant(req, res) {
capAtomics,
expiryTs,
network: body.network,
+ userId: user.id,
});
return json(res, 200, {
@@ -265,6 +270,67 @@ async function handleAllowanceGrant(req, res) {
});
}
+// ── POST /api/token/allowance-confirm ────────────────────────────────────────
+//
+// Called by the client right after it sends a signed grant or revoke. Reconciles
+// the one delegation PDA against the chain and updates the registry, so the wallet
+// panel reflects the new cap (or revocation) instantly without waiting on the
+// status cache to expire.
+
+const DELEGATION_PDA = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'invalid delegation address');
+const confirmSchema = z.object({
+ delegation_pda: DELEGATION_PDA,
+ revoked: z.boolean().optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleAllowanceConfirm(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');
+ const rl = await limits.tokenSettle(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = parse(confirmSchema, await readJson(req));
+ const result = await confirmAllowance({
+ userWallet: user.wallet_address,
+ delegationPda: body.delegation_pda,
+ revoked: body.revoked === true,
+ network: body.network,
+ });
+ return json(res, 200, result);
+}
+
+// ── POST /api/token/allowance-revoke ─────────────────────────────────────────
+//
+// Build the user-signed transaction that cancels a delegation and reclaims its
+// rent. The client signs + sends it, then calls allowance-confirm with revoked:true.
+
+const revokeSchema = z.object({
+ delegation_pda: DELEGATION_PDA,
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleAllowanceRevoke(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');
+ const rl = await limits.tokenQuote(user.id);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = parse(revokeSchema, await readJson(req));
+ const built = await buildRevokeTransaction({
+ userWallet: user.wallet_address,
+ delegationPda: body.delegation_pda,
+ network: body.network,
+ });
+ return json(res, 200, built);
+}
+
// ── GET /api/token/payments (audit) ──────────────────────────────────────────
async function handlePayments(req, res) {
@@ -295,6 +361,8 @@ const DISPATCH = {
payments: handlePayments,
'allowance-status': handleAllowanceStatus,
'allowance-grant': handleAllowanceGrant,
+ 'allowance-confirm': handleAllowanceConfirm,
+ 'allowance-revoke': handleAllowanceRevoke,
};
export default wrap(async (req, res) => {
diff --git a/data/changelog.json b/data/changelog.json
index 197fe97f6..a023eadf4 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$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": "Hardened on-chain confirmations and faster profile loads",
+ "summary": "Two reliability fixes for everyone trading, launching, and browsing. First: every on-chain action that moves funds — coin launches, buys and sells, buybacks, payouts, transfers — now treats a transaction that lands but reverts as a real failure instead of quietly reporting success. You'll see an accurate error and your spending limit won't be charged for a trade that didn't go through. Second: public profile and creator pages are now cacheable at the edge, so they load noticeably faster under load. No action needed — these apply automatically.",
+ "tags": [
+ "fix",
+ "security",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-21",
"title": "Free photo → 3D is now a one-click engine in Forge",
diff --git a/public/changelog.json b/public/changelog.json
index 338664e59..63df2a1bc 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T04:52:15.005Z",
+ "generated_at": "2026-06-21T05:01:39.901Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -59,6 +59,18 @@
"improvement"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Hardened on-chain confirmations and faster profile loads",
+ "summary": "Two reliability fixes for everyone trading, launching, and browsing. First: every on-chain action that moves funds — coin launches, buys and sells, buybacks, payouts, transfers — now treats a transaction that lands but reverts as a real failure instead of quietly reporting success. You'll see an accurate error and your spending limit won't be charged for a trade that didn't go through. Second: public profile and creator pages are now cacheable at the edge, so they load noticeably faster under load. No action needed — these apply automatically.",
+ "link": null,
+ "tags": [
+ "fix",
+ "security",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 469f708f6..f035d685e 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -46,6 +46,14 @@
<category>feature</category>
<description>Turning a photo into a 3D model is free — and now you can pick it directly. Forge's engine selector has a new 'Hunyuan3D / TRELLIS' lane marked with a FREE badge that reconstructs your uploaded photo (or 2–4 angles) into a textured GLB at no cost and with no API key, running on community GPU Spaces with automatic failover across Hunyuan3D, TRELLIS, and TripoSR. Until now the free photo lane only kicked in behind the scenes; it's a first-class choice in the picker, shows live availability, and never silently falls back to a paid engine. The FREE badge also marks every other no-cost lane so you can always see which engines cost nothing.</description>
</item>
+ <item>
+ <title>Hardened on-chain confirmations and faster profile loads</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-21:Hardened on-chain confirmations and faster profile loads</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Two reliability fixes for everyone trading, launching, and browsing. First: every on-chain action that moves funds — coin launches, buys and sells, buybacks, payouts, transfers — now treats a transaction that lands but reverts as a real failure instead of quietly reporting success. You'll see an accurate error and your spending limit won't be charged for a trade that didn't go through. Second: public profile and creator pages are now cacheable at the edge, so they load noticeably faster under load. No action needed — these apply automatically.</description>
+ </item>
<item>
<title>Solana is now the default payment network</title>
<link>https://three.ws/dashboard</link>
diff --git a/public/features.json b/public/features.json
index 154febe09..3dee456a3 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T04:52:14.964Z",
+ "generated_at": "2026-06-21T05:01:39.521Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agent-wallet-hub/tabs/vanity.js b/src/agent-wallet-hub/tabs/vanity.js
index 4ba0d01f7..ea0a83cb5 100644
--- a/src/agent-wallet-hub/tabs/vanity.js
+++ b/src/agent-wallet-hub/tabs/vanity.js
@@ -1,23 +1,30 @@
/**
* Agent Wallet hub — Vanity tab.
*
- * Owner-only. Opt-in: grind a custom vanity address for the agent's custodial
- * Solana wallet, with a per-agent prefix/suffix the owner chooses. The grind runs
- * server-side (the secret key never leaves the server) via
- * POST /api/agents/:id/solana/vanity. If the wallet already holds funds, every
- * asset is swept to the new address before the stored key is swapped — funds are
- * never stranded (the swap is aborted if the sweep fails).
+ * Owner-only. Grind a custom vanity address for the agent's custodial Solana
+ * wallet, with a per-agent prefix/suffix the owner chooses.
*
- * Server-side grinding is bounded to short patterns (≤3 combined chars). Longer,
- * harder patterns are ground in the browser at /vanity-wallet (GPU + workers, up
- * to 8 chars) and assigned from there — this tab links out for that path.
+ * The grind runs IN THE BROWSER using the same worker-pool WASM grinder as
+ * /vanity-wallet (src/solana/vanity/grinder.js) — the owner picks how many CPU
+ * cores to spend, can match case-insensitively, pause/resume at will, and there
+ * is no serverless time budget to time out against. Once a match is found the
+ * 64-byte keypair is POSTed to /api/agents/:id/solana/vanity, which re-derives
+ * the address, proves it matches the requested pattern, sweeps every asset from
+ * the old wallet to the new one, and only then swaps the stored key — so funds
+ * can never be stranded (the swap aborts if the sweep fails).
+ *
+ * This replaces the old server-side grind, which was bounded to ≤3 chars and
+ * timed out on anything harder.
*/
import { registerWalletTab } from '../registry.js';
import { consumeCsrfToken } from '../../api.js';
+import { grindVanity } from '../../solana/vanity/grinder.js';
+import { validatePattern, expectedAttempts, formatTimeEstimate, MAX_PATTERN_LENGTH } from '../../solana/vanity/validation.js';
-const MAX_CHARS = 3;
-const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]*$/;
+// Per-core grind throughput, used only for the pre-grind time estimate. The
+// live ETA during grinding comes from the workers' real measured rate.
+const EST_KEYS_PER_CORE_PER_SEC = 15000;
const VN_STYLE_ID = 'awh-vanity-style';
const VN_STYLE = `
@@ -33,6 +40,34 @@ const VN_STYLE = `
.awh-vn-toggle{display:flex;align-items:center;gap:8px;font-size:var(--text-sm,.764rem);color:var(--ink-dim,#888);margin-bottom:var(--space-3,12px);cursor:pointer;}
.awh-vn-warn{background:color-mix(in srgb, var(--warn,#fbbf24) 10%, transparent);border:1px solid color-mix(in srgb, var(--warn,#fbbf24) 28%, transparent);color:var(--warn,#fbbf24);border-radius:var(--radius-md,10px);padding:10px 12px;font-size:var(--text-sm,.764rem);margin-bottom:var(--space-3,12px);line-height:1.45;}
.awh-vn-out{font-family:var(--font-mono,ui-monospace,monospace);font-size:var(--text-2xs,.6875rem);color:var(--ink-dim,#888);}
+
+/* Compute / core selector */
+.awh-vn-cores{margin:var(--space-3,12px) 0;padding-top:var(--space-3,12px);border-top:1px solid var(--line,rgba(255,255,255,.08));}
+.awh-vn-cores-head{display:flex;justify-content:space-between;align-items:baseline;margin-bottom:6px;}
+.awh-vn-cores-head label{margin:0;font-size:var(--text-sm,.764rem);color:var(--ink-dim,#888);}
+.awh-vn-cores-val{font-family:var(--font-mono,ui-monospace,monospace);font-size:var(--text-sm,.8rem);color:var(--ink-dim,#888);}
+.awh-vn-cores-val b{color:var(--ink-bright,#fff);font-size:.95rem;}
+.awh-vn-cores input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:4px;border-radius:999px;background:var(--line,rgba(255,255,255,.14));outline:none;cursor:pointer;}
+.awh-vn-cores input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:16px;height:16px;border-radius:50%;background:#a78bfa;cursor:pointer;transition:transform .12s ease;}
+.awh-vn-cores input[type=range]::-webkit-slider-thumb:hover{transform:scale(1.15);}
+.awh-vn-cores input[type=range]::-moz-range-thumb{width:16px;height:16px;border:none;border-radius:50%;background:#a78bfa;cursor:pointer;}
+.awh-vn-cores input[type=range]:disabled{opacity:.4;cursor:not-allowed;}
+.awh-vn-cores input[type=range]:focus-visible{box-shadow:0 0 0 2px rgba(167,139,250,.5);}
+.awh-vn-ticks{display:flex;gap:6px;margin-top:8px;}
+.awh-vn-ticks button{flex:0 0 auto;font-size:var(--text-2xs,.6875rem);padding:3px 9px;border-radius:999px;border:1px solid var(--line,rgba(255,255,255,.14));background:transparent;color:var(--ink-dim,#888);cursor:pointer;transition:background .12s,border-color .12s,color .12s;}
+.awh-vn-ticks button:hover{border-color:rgba(167,139,250,.5);color:var(--ink,#e8e8e8);}
+.awh-vn-ticks button[aria-pressed=true]{background:#a78bfa;border-color:#a78bfa;color:#1a1130;font-weight:600;}
+
+/* Live grind progress */
+.awh-vn-prog{text-align:center;padding:var(--space-3,12px) 0;}
+.awh-vn-prog-rate{font-family:var(--font-mono,ui-monospace,monospace);font-size:1.6rem;font-weight:700;color:var(--ink-bright,#fff);line-height:1.1;}
+.awh-vn-prog-sub{font-size:var(--text-2xs,.6875rem);color:var(--ink-dim,#888);margin-top:4px;}
+.awh-vn-prog-grid{display:flex;justify-content:center;gap:18px;margin-top:10px;}
+.awh-vn-prog-grid div{font-size:var(--text-2xs,.6875rem);color:var(--ink-dim,#888);}
+.awh-vn-prog-grid b{display:block;font-family:var(--font-mono,ui-monospace,monospace);font-size:var(--text-sm,.8rem);color:var(--ink,#e8e8e8);font-weight:600;margin-top:2px;}
+.awh-vn-paused{display:inline-block;margin-left:8px;font-size:var(--text-2xs,.625rem);font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--warn,#fbbf24);background:color-mix(in srgb,var(--warn,#fbbf24) 14%,transparent);border-radius:999px;padding:1px 7px;}
+.awh-vn-actions{display:flex;gap:8px;margin-top:var(--space-3,12px);}
+.awh-vn-actions .awh-btn{flex:1;}
`;
function injectStyle() {
@@ -50,7 +85,7 @@ async function call(url, { method = 'GET', body = null } = {}) {
opts.headers['content-type'] = 'application/json';
opts.body = JSON.stringify(body);
}
- // Grinding a vanity address swaps the keypair and sweeps funds — the POST is
+ // Assigning a vanity address swaps the keypair and sweeps funds — the POST is
// state-changing, so carry a single-use CSRF token (server burns it on use).
if (method !== 'GET') {
const token = await consumeCsrfToken();
@@ -66,11 +101,16 @@ async function call(url, { method = 'GET', body = null } = {}) {
}
}
-// Expected attempts ≈ alphabet^len. Matches the server estimate.
-function estimate(prefix, suffix, ignoreCase) {
- const len = (prefix?.length || 0) + (suffix?.length || 0);
- if (len === 0) return 1;
- return Math.pow(ignoreCase ? 33 : 58, len);
+const HW_CORES = Math.max(1, (typeof navigator !== 'undefined' && navigator.hardwareConcurrency) || 4);
+const DEFAULT_CORES = Math.max(1, Math.min(HW_CORES, Math.round(HW_CORES / 2)));
+// Quick presets: 1, balanced default, max — deduped for low-core machines.
+const PRESETS = [...new Set([1, DEFAULT_CORES, HW_CORES])].sort((a, b) => a - b);
+
+function fmtRate(r) {
+ if (!r || r < 1) return '0';
+ if (r >= 1e6) return `${(r / 1e6).toFixed(1)}M`;
+ if (r >= 1e3) return `${(r / 1e3).toFixed(1)}k`;
+ return String(Math.round(r));
}
registerWalletTab({
@@ -85,33 +125,66 @@ registerWalletTab({
const base = `/api/agents/${encodeURIComponent(ctx.agentId)}/solana/vanity`;
let destroyed = false;
+ let controller = null; // grindVanity pause/resume/stop handle while grinding
+
const state = {
status: null, // { address, vanity_prefix, vanity_suffix, is_vanity } | { error }
prefix: '',
suffix: '',
ignoreCase: false,
- phase: 'form', // 'form' | 'grinding' | 'success'
- result: null,
- err: null,
+ cores: DEFAULT_CORES,
+ phase: 'form', // 'form' | 'grinding' | 'applying' | 'apply_failed' | 'success'
+ progress: null, // { attempts, rate, eta, paused }
+ ground: null, // { secretKey, address, attempts, durationMs } once a match is found
+ applyError: null,
+ result: null, // server response after a successful assign
};
- function currentAddrHTML() {
- const s = state.status;
- if (!s || s.error || !s.address) return '';
- const a = s.address;
- const p = s.vanity_prefix;
- const sf = s.vanity_suffix;
+ function patternError() {
+ for (const [val, label] of [[state.prefix, 'prefix'], [state.suffix, 'suffix']]) {
+ if (!val) continue;
+ const v = validatePattern(val);
+ if (!v.valid) return `Invalid ${label}: ${v.errors.join('; ')}`;
+ }
+ return null;
+ }
+
+ function highlight(addr, p, sf) {
+ const a = addr || '';
let html = esc(a);
- if (p && a.startsWith(p)) html = `<b>${esc(p)}</b>${esc(a.slice(p.length))}`;
- if (sf && a.endsWith(sf)) {
- const body = p && a.startsWith(p) ? a.slice(p.length) : a;
- const mid = body.slice(0, body.length - sf.length);
- const pre = p && a.startsWith(p) ? `<b>${esc(p)}</b>` : '';
- html = `${pre}${esc(mid)}<b>${esc(sf)}</b>`;
+ const hasP = p && a.startsWith(p);
+ const hasS = sf && a.endsWith(sf);
+ if (hasP && hasS) {
+ const mid = a.slice(p.length, a.length - sf.length);
+ html = `<b>${esc(p)}</b>${esc(mid)}<b>${esc(sf)}</b>`;
+ } else if (hasP) {
+ html = `<b>${esc(p)}</b>${esc(a.slice(p.length))}`;
+ } else if (hasS) {
+ html = `${esc(a.slice(0, a.length - sf.length))}<b>${esc(sf)}</b>`;
}
return html;
}
+ function currentAddrHTML() {
+ const s = state.status;
+ if (!s || s.error || !s.address) return '';
+ return highlight(s.address, s.vanity_prefix, s.vanity_suffix);
+ }
+
+ function estLine() {
+ const combined = state.prefix.length + state.suffix.length;
+ if (combined === 0) return { html: 'Enter a prefix and/or suffix (base58 — no 0, O, I or l).', warn: false };
+ const perr = patternError();
+ if (perr) return { html: esc(perr), warn: true };
+ const expected = expectedAttempts(state.prefix, state.suffix, state.ignoreCase);
+ const eta = formatTimeEstimate(expected, state.cores * EST_KEYS_PER_CORE_PER_SEC);
+ const hard = expected > 5e8;
+ return {
+ html: `≈ <b>${Math.round(expected).toLocaleString()}</b> attempts · about <b>${esc(eta)}</b> on ${state.cores} core${state.cores > 1 ? 's' : ''}${hard ? ' — this one is hard, grinding may take a while' : ''}.`,
+ warn: hard,
+ };
+ }
+
function render() {
if (destroyed) return;
if (state.status === null) {
@@ -119,14 +192,18 @@ registerWalletTab({
return;
}
if (state.phase === 'success') { panel.innerHTML = renderSuccess(); wireSuccess(); return; }
+ if (state.phase === 'grinding' || state.phase === 'applying') { panel.innerHTML = renderGrinding(); wireGrinding(); return; }
+ panel.innerHTML = renderForm(); wireForm();
+ }
+ function renderForm() {
const s = state.status;
const isVanity = !!(s && !s.error && s.is_vanity);
- const combined = state.prefix.length + state.suffix.length;
- const tooHard = combined > MAX_CHARS;
- const est = estimate(state.prefix, state.suffix, state.ignoreCase);
+ const hasWallet = !!(s && !s.error && s.address);
+ const est = estLine();
+ const ph = ((ctx.agent?.name || 'ag').toLowerCase().replace(/[^1-9a-hj-np-za-km-z]/gi, '').slice(0, 4)) || 'ag';
- panel.innerHTML = `
+ return `
<div class="awh-card">
${s?.error ? `<div class="awh-err">Couldn’t load wallet. <div class="why">${esc(s.error)}</div></div>` : `
<div class="awh-vn-head">
@@ -137,17 +214,17 @@ registerWalletTab({
</div>`}
<p class="awh-empty" style="margin-top:0;">
- Grind a custom address for this agent's wallet. You pick the pattern; the key is generated and stored server-side — it never leaves three.ws.
+ Grind a custom address for this agent's wallet with your CPU. The match is found in your browser; the key is then stored server-side — it never leaves three.ws.
</p>
<div class="awh-vn-grid">
<div class="awh-fld">
<label for="awh-vn-prefix">Starts with</label>
- <input class="awh-in awh-mono" id="awh-vn-prefix" autocomplete="off" spellcheck="false" maxlength="3" placeholder="e.g. ${esc((ctx.agent?.name || 'ag').toLowerCase().replace(/[^1-9a-hj-np-za-km-z]/gi, '').slice(0, 3) || 'ag')}" value="${esc(state.prefix)}">
+ <input class="awh-in awh-mono" id="awh-vn-prefix" autocomplete="off" spellcheck="false" maxlength="${MAX_PATTERN_LENGTH}" placeholder="e.g. ${esc(ph)}" value="${esc(state.prefix)}">
</div>
<div class="awh-fld">
<label for="awh-vn-suffix">Ends with</label>
- <input class="awh-in awh-mono" id="awh-vn-suffix" autocomplete="off" spellcheck="false" maxlength="3" placeholder="optional" value="${esc(state.suffix)}">
+ <input class="awh-in awh-mono" id="awh-vn-suffix" autocomplete="off" spellcheck="false" maxlength="${MAX_PATTERN_LENGTH}" placeholder="optional" value="${esc(state.suffix)}">
</div>
</div>
@@ -156,25 +233,50 @@ registerWalletTab({
Case-insensitive (faster, matches any capitalization)
</label>
- <div class="awh-vn-est ${tooHard ? 'warn' : ''}" id="awh-vn-est">
- ${combined === 0
- ? 'Enter a prefix and/or suffix (base58 — no 0, O, I or l).'
- : tooHard
- ? `Too hard for instant grinding (${combined} chars). <a href="/vanity-wallet" target="_blank" rel="noopener" style="color:var(--warn,#fbbf24);text-decoration:underline;">Grind up to 8 chars in your browser →</a> and assign it.`
- : `≈ <b>${est.toLocaleString()}</b> attempts — usually a few seconds.`}
+ <div class="awh-vn-cores">
+ <div class="awh-vn-cores-head">
+ <label for="awh-vn-cores">Compute — CPU cores</label>
+ <span class="awh-vn-cores-val"><b id="awh-vn-cores-val">${state.cores}</b> / ${HW_CORES}</span>
+ </div>
+ <input id="awh-vn-cores" type="range" min="1" max="${HW_CORES}" step="1" value="${state.cores}" aria-label="Number of CPU cores to grind with">
+ <div class="awh-vn-ticks" id="awh-vn-ticks" aria-label="Quick core presets">
+ ${PRESETS.map((n) => `<button type="button" data-cores="${n}" aria-pressed="${n === state.cores}">${n === 1 ? '1 core' : n === HW_CORES ? `Max (${n})` : String(n)}</button>`).join('')}
+ </div>
</div>
- ${isVanity || (s && !s.error && s.address)
+ <div class="awh-vn-est ${est.warn ? 'warn' : ''}" id="awh-vn-est">${est.html}</div>
+
+ ${isVanity || hasWallet
? `<div class="awh-vn-warn">⚠ This replaces the agent's current address. Any SOL or tokens it holds are <b>automatically swept to the new address</b> first — the swap only completes once funds have moved. Apps pointed at the old address must be updated.</div>`
: ''}
<div class="awh-err" id="awh-vn-err" hidden></div>
- <button class="awh-btn awh-btn--primary" id="awh-vn-go" type="button" style="width:100%;" ${state.phase === 'grinding' ? 'disabled' : ''}>
- ${state.phase === 'grinding' ? '<span class="awh-spin"></span>Grinding & applying…' : 'Grind &amp; apply vanity address'}
- </button>
+ <button class="awh-btn awh-btn--primary" id="awh-vn-go" type="button" style="width:100%;">Grind &amp; apply vanity address</button>
</div>`;
+ }
- wireForm();
+ function renderGrinding() {
+ const applying = state.phase === 'applying';
+ const p = state.progress || { attempts: 0, rate: 0, eta: '—', paused: false };
+ const paused = !!p.paused;
+ return `
+ <div class="awh-card">
+ <div class="awh-card-h" style="margin-bottom:2px;">Grinding <span class="awh-mono" style="color:#a78bfa;">${esc(state.prefix)}${state.prefix && state.suffix ? '…' : ''}${esc(state.suffix)}</span></div>
+ <div class="awh-vn-prog">
+ <div class="awh-vn-prog-rate" id="awh-vn-rate">${applying ? '✦' : fmtRate(p.rate)}<span style="font-size:.9rem;font-weight:500;color:var(--ink-dim,#888);">${applying ? '' : ' /s'}</span><span class="awh-vn-paused" id="awh-vn-paused" ${paused ? '' : 'hidden'}>paused</span></div>
+ <div class="awh-vn-prog-sub">${applying ? 'Match found — migrating funds &amp; applying…' : `across ${state.cores} core${state.cores > 1 ? 's' : ''}`}</div>
+ <div class="awh-vn-prog-grid">
+ <div>attempts<b id="awh-vn-attempts">${Math.round(p.attempts).toLocaleString()}</b></div>
+ <div>eta<b id="awh-vn-eta">${applying ? '—' : esc(p.eta || '—')}</b></div>
+ </div>
+ </div>
+ ${applying
+ ? `<div class="awh-empty" style="text-align:center;">Sweeping any existing balance to the new address, then swapping the key. Don't close this tab.</div>`
+ : `<div class="awh-vn-actions">
+ <button class="awh-btn" id="awh-vn-pause" type="button">${paused ? 'Resume' : 'Pause'}</button>
+ <button class="awh-btn" id="awh-vn-cancel" type="button">Cancel</button>
+ </div>`}
+ </div>`;
}
function renderSuccess() {
@@ -190,14 +292,7 @@ registerWalletTab({
<div class="awh-card awh-ok">
<div class="ic">✦</div>
<div style="font-size:var(--text-md,.8125rem);font-weight:600;color:var(--ink-bright,#fff);margin-bottom:6px;">Vanity address applied</div>
- <div class="awh-vn-addr" style="margin-bottom:8px;">${(() => {
- const a = r.address || '';
- const p = r.vanity_prefix; const sf = r.vanity_suffix;
- let h = esc(a);
- if (p && a.startsWith(p)) h = `<b>${esc(p)}</b>${esc(a.slice(p.length))}`;
- if (sf && a.endsWith(sf)) { const mid = (p && a.startsWith(p) ? a.slice(p.length) : a); h = `${p && a.startsWith(p) ? `<b>${esc(p)}</b>` : ''}${esc(mid.slice(0, mid.length - sf.length))}<b>${esc(sf)}</b>`; }
- return h;
- })()}</div>
+ <div class="awh-vn-addr" style="margin-bottom:8px;">${highlight(r.address, r.vanity_prefix, r.vanity_suffix)}</div>
${sweptLine}
${r.iterations != null ? `<div class="awh-vn-out">Found in ${Number(r.iterations).toLocaleString()} attempts${r.duration_ms != null ? ` · ${(r.duration_ms / 1000).toFixed(1)}s` : ''}</div>` : ''}
<div style="margin-top:14px;display:flex;gap:8px;justify-content:center;">
@@ -207,6 +302,137 @@ registerWalletTab({
</div>`;
}
+ // Patch the live numbers without a full re-render so the readout stays smooth.
+ function updateProgressUI() {
+ if (destroyed || state.phase !== 'grinding') return;
+ const p = state.progress || {};
+ const rate = panel.querySelector('#awh-vn-rate');
+ const attempts = panel.querySelector('#awh-vn-attempts');
+ const eta = panel.querySelector('#awh-vn-eta');
+ const paused = panel.querySelector('#awh-vn-paused');
+ if (rate) rate.firstChild && (rate.firstChild.textContent = p.paused ? '0' : fmtRate(p.rate));
+ if (attempts) attempts.textContent = Math.round(p.attempts || 0).toLocaleString();
+ if (eta) eta.textContent = p.paused ? 'paused' : (p.eta || '—');
+ if (paused) paused.hidden = !p.paused;
+ }
+
+ function showErr(msg) {
+ const e = panel.querySelector('#awh-vn-err');
+ if (e) { e.hidden = false; e.textContent = msg; }
+ }
+
+ async function applyGround() {
+ state.phase = 'applying';
+ state.applyError = null;
+ render();
+ const g = state.ground;
+ const res = await call(base, {
+ method: 'POST',
+ body: {
+ secret_key: Array.from(g.secretKey),
+ prefix: state.prefix || undefined,
+ suffix: state.suffix || undefined,
+ ignoreCase: state.ignoreCase,
+ iterations: g.attempts,
+ duration_ms: Math.round(g.durationMs),
+ network: ctx.getNetwork(),
+ },
+ });
+ if (destroyed) return;
+ if (!res.ok) {
+ // Keep the ground key in memory so the owner can retry the assign
+ // without re-grinding (e.g. a transient RPC/sweep failure).
+ state.phase = 'apply_failed';
+ state.applyError = res.message;
+ renderApplyFailed();
+ return;
+ }
+ state.result = res.data;
+ state.ground = null;
+ state.phase = 'success';
+ toast('Vanity address applied');
+ render();
+ }
+
+ function renderApplyFailed() {
+ const g = state.ground || {};
+ panel.innerHTML = `
+ <div class="awh-card">
+ <div class="awh-err" style="margin-bottom:12px;">Couldn’t apply the address. <div class="why">${esc(state.applyError || 'unknown error')}</div></div>
+ <p class="awh-empty" style="margin-top:0;">Your wallet is unchanged and still holds any funds. The ground address is ready — retry the assign without grinding again.</p>
+ <div class="awh-vn-addr" style="margin:8px 0 12px;">${highlight(g.address, state.prefix, state.suffix)}</div>
+ <div class="awh-vn-actions">
+ <button class="awh-btn awh-btn--primary" id="awh-vn-retry" type="button">Retry assign</button>
+ <button class="awh-btn" id="awh-vn-discard" type="button">Discard</button>
+ </div>
+ </div>`;
+ panel.querySelector('#awh-vn-retry')?.addEventListener('click', applyGround);
+ panel.querySelector('#awh-vn-discard')?.addEventListener('click', () => {
+ state.ground = null; state.applyError = null; state.phase = 'form'; render();
+ });
+ }
+
+ async function startGrind() {
+ const combined = state.prefix.length + state.suffix.length;
+ if (combined === 0) { showErr('Enter a prefix and/or suffix first.'); return; }
+ const perr = patternError();
+ if (perr) { showErr(perr); return; }
+
+ state.phase = 'grinding';
+ state.progress = { attempts: 0, rate: 0, eta: '—', paused: false };
+ render();
+
+ controller = {};
+ let result;
+ try {
+ result = await grindVanity({
+ prefix: state.prefix || '',
+ suffix: state.suffix || '',
+ ignoreCase: state.ignoreCase,
+ maxWorkers: state.cores,
+ controller,
+ onProgress: (p) => {
+ if (destroyed || state.phase !== 'grinding') return;
+ state.progress = p;
+ updateProgressUI();
+ },
+ });
+ } catch (e) {
+ controller = null;
+ if (destroyed) return;
+ if (e?.name === 'AbortError') { state.phase = 'form'; render(); return; }
+ state.phase = 'form';
+ render();
+ showErr(e?.message || 'grind failed — try again');
+ return;
+ }
+ controller = null;
+ if (destroyed) return;
+ state.ground = {
+ secretKey: result.secretKey,
+ address: result.publicKey,
+ attempts: result.attempts,
+ durationMs: result.durationMs,
+ };
+ await applyGround();
+ }
+
+ function wireGrinding() {
+ updateProgressUI();
+ panel.querySelector('#awh-vn-pause')?.addEventListener('click', () => {
+ if (!controller) return;
+ if (controller.paused) controller.resume(); else controller.pause();
+ // Reflect the toggle immediately; live numbers keep flowing via onProgress.
+ state.progress = { ...(state.progress || {}), paused: !!controller.paused };
+ const btn = panel.querySelector('#awh-vn-pause');
+ if (btn) btn.textContent = controller.paused ? 'Resume' : 'Pause';
+ updateProgressUI();
+ });
+ panel.querySelector('#awh-vn-cancel')?.addEventListener('click', () => {
+ if (controller?.stop) controller.stop();
+ });
+ }
+
function wireSuccess() {
panel.querySelector('#awh-vn-again')?.addEventListener('click', () => {
state.phase = 'form'; state.result = null; state.prefix = ''; state.suffix = '';
@@ -218,48 +444,35 @@ registerWalletTab({
const pIn = panel.querySelector('#awh-vn-prefix');
const sIn = panel.querySelector('#awh-vn-suffix');
const ic = panel.querySelector('#awh-vn-ic');
- const errEl = panel.querySelector('#awh-vn-err');
const estEl = panel.querySelector('#awh-vn-est');
+ const slider = panel.querySelector('#awh-vn-cores');
+ const coresVal = panel.querySelector('#awh-vn-cores-val');
+ const ticks = panel.querySelector('#awh-vn-ticks');
- function clean(v) { return (v || '').replace(/[^1-9A-HJ-NP-Za-km-z]/g, '').slice(0, 3); }
+ const clean = (v) => (v || '').replace(/[^1-9A-HJ-NP-Za-km-z]/g, '').slice(0, MAX_PATTERN_LENGTH);
function refreshEst() {
- const combined = state.prefix.length + state.suffix.length;
- const tooHard = combined > MAX_CHARS;
- const est = estimate(state.prefix, state.suffix, state.ignoreCase);
- estEl.className = `awh-vn-est ${tooHard ? 'warn' : ''}`;
- estEl.innerHTML = combined === 0
- ? 'Enter a prefix and/or suffix (base58 — no 0, O, I or l).'
- : tooHard
- ? `Too hard for instant grinding (${combined} chars). <a href="/vanity-wallet" target="_blank" rel="noopener" style="color:var(--warn,#fbbf24);text-decoration:underline;">Grind up to 8 chars in your browser →</a> and assign it.`
- : `≈ <b>${est.toLocaleString()}</b> attempts — usually a few seconds.`;
+ const est = estLine();
+ estEl.className = `awh-vn-est ${est.warn ? 'warn' : ''}`;
+ estEl.innerHTML = est.html;
}
+ function setCores(n) {
+ state.cores = Math.max(1, Math.min(HW_CORES, n | 0));
+ if (slider) slider.value = String(state.cores);
+ if (coresVal) coresVal.textContent = String(state.cores);
+ ticks?.querySelectorAll('button').forEach((b) => b.setAttribute('aria-pressed', String(Number(b.dataset.cores) === state.cores)));
+ refreshEst();
+ }
+
pIn?.addEventListener('input', () => { const c = clean(pIn.value); if (c !== pIn.value) pIn.value = c; state.prefix = c; refreshEst(); });
sIn?.addEventListener('input', () => { const c = clean(sIn.value); if (c !== sIn.value) sIn.value = c; state.suffix = c; refreshEst(); });
ic?.addEventListener('change', () => { state.ignoreCase = ic.checked; refreshEst(); });
+ slider?.addEventListener('input', () => setCores(Number(slider.value)));
+ ticks?.querySelectorAll('button').forEach((b) => b.addEventListener('click', () => setCores(Number(b.dataset.cores))));
- panel.querySelector('#awh-vn-go')?.addEventListener('click', async () => {
- errEl.hidden = true;
- const combined = state.prefix.length + state.suffix.length;
- if (combined === 0) { errEl.hidden = false; errEl.textContent = 'Enter a prefix and/or suffix first.'; return; }
- if (combined > MAX_CHARS) { errEl.hidden = false; errEl.textContent = `Server grinding supports up to ${MAX_CHARS} combined characters. Use the browser grinder for longer patterns.`; return; }
- state.phase = 'grinding';
- render();
- const res = await call(base, {
- method: 'POST',
- body: { prefix: state.prefix || undefined, suffix: state.suffix || undefined, ignoreCase: state.ignoreCase, network: ctx.getNetwork() },
- });
- if (destroyed) return;
- if (!res.ok) {
- state.phase = 'form';
- render();
- const e = panel.querySelector('#awh-vn-err');
- if (e) { e.hidden = false; e.textContent = res.message; }
- return;
- }
- state.result = res.data;
- state.phase = 'success';
- toast('Vanity address applied');
- render();
+ panel.querySelector('#awh-vn-go')?.addEventListener('click', () => {
+ const err = panel.querySelector('#awh-vn-err');
+ if (err) err.hidden = true;
+ startGrind();
});
}
@@ -276,7 +489,11 @@ registerWalletTab({
return {
onShow() { if (state.status === null) loadStatus(); },
- destroy() { destroyed = true; },
+ destroy() {
+ destroyed = true;
+ // Free the worker pool if the owner navigates away mid-grind.
+ if (controller?.stop) { try { controller.stop(); } catch { /* already settled */ } }
+ },
};
},
});
diff --git a/src/dashboard-next/pages/three-token.js b/src/dashboard-next/pages/three-token.js
index e56f2d4c7..2e00560e1 100644
--- a/src/dashboard-next/pages/three-token.js
+++ b/src/dashboard-next/pages/three-token.js
@@ -13,7 +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 { fetchAllowanceStatus, grantAllowance, revokeAllowance } from '../../three-allowance.js';
import { createThreeTokenData } from '../../pump/three-token-data.js';
const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;
@@ -395,6 +395,21 @@ const EXPIRY_OPTIONS = [
{ label: 'No expiry', days: null },
];
+// Reference unit prices (USD) from the pricing catalog, used only to translate a
+// $THREE cap into relatable "what this covers" estimates. Display-only.
+const FORGE_STD_USD = 0.1;
+const SKILL_TYPICAL_USD = 0.05;
+const LOW_BALANCE_USD = 1; // below this, nudge a top-up
+
+function expiryLabel(ts) {
+ if (!ts || ts <= 0) return 'No expiry';
+ const days = Math.round((ts - Date.now() / 1000) / 86_400);
+ if (days <= 0) return 'Expired';
+ if (days === 1) return 'Expires in 1 day';
+ if (days < 45) return `Expires in ${days} days`;
+ return `Expires in ${Math.round(days / 30)} months`;
+}
+
function renderSpendAllowance() {
const section = document.createElement('div');
section.className = 'dn-panel';
@@ -405,14 +420,20 @@ function renderSpendAllowance() {
<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>
+ <div data-slot="allowance-body"><div class="dn-skeleton" style="height:96px;border-radius:10px" aria-busy="true"></div></div>
`;
const body = section.querySelector('[data-slot="allowance-body"]');
let busy = false;
+ let priceUsd = null; // live $THREE price, for "what this covers" translation
+
const load = async () => {
try {
- const status = await fetchAllowanceStatus();
+ const [status, price] = await Promise.all([
+ fetchAllowanceStatus(),
+ priceUsd == null ? fetchTokenPrice().catch(() => null) : Promise.resolve(null),
+ ]);
+ if (price?.price_usd != null) priceUsd = Number(price.price_usd);
if (!status.enabled) {
// The rail isn't configured on this deployment — show nothing rather
// than a button that can't work.
@@ -439,6 +460,16 @@ function renderSpendAllowance() {
}
const remaining = Number(status.remaining_tokens || 0);
const hasAllowance = remaining > 0;
+ const usdValue = priceUsd != null ? remaining * priceUsd : null;
+ const low = usdValue != null && usdValue < LOW_BALANCE_USD;
+
+ // "What this covers" — concrete, relatable units from the live USD value.
+ let covers = '';
+ if (usdValue != null && hasAllowance) {
+ const gens = Math.floor(usdValue / FORGE_STD_USD);
+ const skills = Math.floor(usdValue / SKILL_TYPICAL_USD);
+ covers = `≈ ${fmtUsd(usdValue)} — about ${fmtCompact(gens)} forge generations or ${fmtCompact(skills)} skill calls`;
+ }
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>`,
@@ -447,18 +478,32 @@ function renderSpendAllowance() {
(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('');
+ // One manageable row per active delegation (remaining + expiry + revoke).
+ const grantsList = (status.delegations || [])
+ .map((d) => {
+ const tok = Number(d.remaining_tokens || 0);
+ return `<div style="display:flex;align-items:center;justify-content:space-between;gap:10px;padding:8px 0;border-top:1px solid var(--nxt-line)">
+ <div style="min-width:0">
+ <div style="font-size:14px;font-weight:600;font-family:${MONO}">${fmtCompact(tok)} <span style="font-size:12px;color:var(--nxt-ink-fade)">$THREE</span></div>
+ <div style="font-size:11px;color:var(--nxt-ink-fade)">${esc(expiryLabel(d.expiry_ts))}</div>
+ </div>
+ <button data-action="allowance-revoke" data-pda="${esc(d.pubkey)}" class="dn-btn" style="font-size:11.5px;padding:4px 12px;white-space:nowrap">Revoke</button>
+ </div>`;
+ })
+ .join('');
+
body.innerHTML = `
${hasAllowance ? `
- <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:14px">
+ <div style="display:flex;align-items:flex-end;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:6px">
<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 style="font-size:28px;font-weight:700;font-family:${MONO};color:${low ? '#fbbf24' : '#4ade80'};letter-spacing:-0.02em">${fmtCompact(remaining)} <span style="font-size:14px;color:var(--nxt-ink-fade)">$THREE</span></div>
</div>
+ <div style="font-size:12px;font-weight:600;color:${low ? '#fbbf24' : '#4ade80'};white-space:nowrap">${low ? '● Running low' : '● Frictionless spending on'}</div>
</div>
+ ${covers ? `<div style="font-size:12px;color:var(--nxt-ink-fade);margin-bottom:${low ? '8' : '14'}px">${esc(covers)}</div>` : ''}
+ ${low ? `<div style="font-size:12.5px;color:#fbbf24;background:rgba(251,191,36,0.08);border:1px solid rgba(251,191,36,0.25);border-radius:8px;padding:8px 10px;margin-bottom:14px">Your cap is running low — top it up below to keep paying without popups.</div>` : ''}
+ <div style="margin-bottom:14px">${grantsList}</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>
`}
@@ -522,11 +567,35 @@ function renderSpendAllowance() {
}
};
+ const doRevoke = async (btn) => {
+ if (busy) return;
+ const pda = btn.getAttribute('data-pda');
+ if (!pda) return;
+ busy = true;
+ btn.disabled = true;
+ const labels = { building: 'Building…', awaiting_signature: 'Confirm in wallet…', confirming: 'Revoking…', done: 'Done' };
+ const original = btn.textContent;
+ try {
+ await revokeAllowance({ delegationPda: pda, onStatus: (s) => { btn.textContent = labels[s] || 'Working…'; } });
+ toast('Allowance revoked — your cap was cancelled and rent returned');
+ busy = false;
+ await load();
+ } catch (err) {
+ busy = false;
+ btn.disabled = false;
+ btn.textContent = original;
+ const msg = body.querySelector('[data-slot="allowance-msg"]');
+ if (msg) msg.textContent = err?.message || 'Could not revoke.';
+ }
+ };
+
section.addEventListener('click', (e) => {
const grantBtn = e.target.closest('[data-action="allowance-grant"]');
if (grantBtn) { doGrant(grantBtn); return; }
+ const revokeBtn = e.target.closest('[data-action="allowance-revoke"]');
+ if (revokeBtn) { doRevoke(revokeBtn); 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(); }
+ if (retry) { body.innerHTML = `<div class="dn-skeleton" style="height:96px;border-radius:10px"></div>`; load(); }
});
load();
diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.js
index f0712e6b1..f069b0aa5 100644
--- a/src/dashboard/dashboard.js
+++ b/src/dashboard/dashboard.js
@@ -6,6 +6,16 @@ import { mountAgentVanityGrinderCard } from '/src/agent-vanity-grinder.js';
import { onchainBadgeHTML } from '/src/shared/onchain-badge.js';
import { renderError as renderAsyncError } from '/src/shared/async-state.js';
import { log } from '../shared/log.js';
+import { safeUrl } from '../safe-url.js';
+
+function escapeHtml(s) {
+ return String(s == null ? '' : s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
export const state = { user: null };
@@ -1168,7 +1178,7 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {
if (!r.ok) {
if (data.upgrade_url) {
setMsg(
- `${data.error_description} <a href="${data.upgrade_url}">Upgrade to Pro</a>`,
+ `${escapeHtml(data.error_description)} <a href="${escapeHtml(safeUrl(data.upgrade_url))}">Upgrade to Pro</a>`,
'#ffb3b3',
);
return;
@@ -1176,7 +1186,7 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {
throw new Error(data.error_description || 'post failed');
}
setMsg(
- `Posted: <a href="${data.url}" target="_blank" rel="noopener">${data.url}</a>${data.thread ? ` (${data.thread.length}-tweet thread)` : ''}`,
+ `Posted: <a href="${escapeHtml(safeUrl(data.url))}" target="_blank" rel="noopener">${escapeHtml(data.url)}</a>${data.thread ? ` (${data.thread.length}-tweet thread)` : ''}`,
);
textEl.value = '';
countEl.textContent = 0;
diff --git a/src/oracle.js b/src/oracle.js
index 61fdd815c..93267ce74 100644
--- a/src/oracle.js
+++ b/src/oracle.js
@@ -1011,8 +1011,7 @@ function moverCardHtml(m) {
: '';
return `<div class="mv-card mv-${m.delta >= 0 ? 'rising' : 'falling'}" role="button" tabindex="0"
- data-mint="${esc(m.mint)}" onclick="window.oracleOpenMover('${esc(m.mint)}')"
- onkeydown="if(event.key==='Enter'||event.key===' ')window.oracleOpenMover('${esc(m.mint)}')">
+ data-mint="${esc(m.mint)}">
<div class="mv-head">
${imgSrc}
<div class="mv-id">
@@ -1044,6 +1043,20 @@ function moverCardHtml(m) {
async function loadMovers(reset = false) {
const grid = $('#moversGrid');
if (!grid) return;
+ if (grid.dataset.loaded !== '1') {
+ const openFromCard = (el) => {
+ const mint = el?.dataset?.mint;
+ if (mint) openCoin(mint);
+ };
+ grid.addEventListener('click', (e) => openFromCard(e.target.closest('.mv-card')));
+ grid.addEventListener('keydown', (e) => {
+ if (e.key !== 'Enter' && e.key !== ' ') return;
+ const card = e.target.closest('.mv-card');
+ if (!card) return;
+ e.preventDefault();
+ openFromCard(card);
+ });
+ }
grid.dataset.loaded = '1';
const skels = Array.from({ length: 6 }, () =>
@@ -1068,8 +1081,6 @@ async function loadMovers(reset = false) {
grid.innerHTML = data.items.map(moverCardHtml).join('');
}
-window.oracleOpenMover = (mint) => openCoin(mint);
-
function winCardHtml(w, idx) {
const tier = w.tier || 'watch';
const athStr = w.ath_multiple != null ? `${Number(w.ath_multiple).toFixed(1)}×` : w.graduated ? 'Grad ✓' : '—';
@@ -1381,7 +1392,7 @@ async function loadRelatedCoins(mint, category) {
const imgEl = r.image_uri
? `<img src="${esc(r.image_uri)}" alt="" style="width:28px;height:28px;border-radius:7px;object-fit:cover;flex:none;border:1px solid var(--line)" loading="lazy">`
: `<div style="width:28px;height:28px;border-radius:7px;background:var(--line);display:grid;place-items:center;font:700 11px/1 var(--mono);color:var(--faint);flex:none">${esc((r.symbol||'?')[0])}</div>`;
- return `<button type="button" onclick="window.__oracleOpenRelated('${esc(r.mint)}')"
+ return `<button type="button" class="dr-related" data-related-mint="${esc(r.mint)}"
style="display:flex;align-items:center;gap:10px;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:8px 10px;cursor:pointer;text-align:left;width:100%;transition:background .12s"
onmouseover="this.style.background='rgba(255,255,255,0.05)'" onmouseout="this.style.background='var(--panel)'">
${imgEl}
@@ -1400,6 +1411,14 @@ async function loadRelatedCoins(mint, category) {
// Insert before the "Who's in" section.
const body = $('#drBody');
if (!body) return;
+ if (body.dataset.relatedWired !== '1') {
+ body.dataset.relatedWired = '1';
+ body.addEventListener('click', (e) => {
+ const btn = e.target.closest('.dr-related');
+ const mint = btn?.dataset?.relatedMint;
+ if (mint) openCoin(mint);
+ });
+ }
const whosSecEl = Array.from(body.querySelectorAll('.dr-sec')).find((el) => el.textContent.startsWith("Who's in"));
if (whosSecEl) {
whosSecEl.insertAdjacentHTML('beforebegin', html);
@@ -1408,8 +1427,6 @@ async function loadRelatedCoins(mint, category) {
}
}
-window.__oracleOpenRelated = (mint) => openCoin(mint);
-
function whoRow(w) {
const title = ARCH_TITLE[w.label] || 'Unproven';
const sub = [
diff --git a/src/safe-url.js b/src/safe-url.js
index c9059da8c..3b0306b63 100644
--- a/src/safe-url.js
+++ b/src/safe-url.js
@@ -4,8 +4,9 @@
* collapses to a safe placeholder, neutralising script-scheme injection in
* `href`, `src`, and CSS `url(...)` sinks.
*
- * Allowed: strings starting with `/`, `./`, `../`, `#`, or matching `^https?:`
- * (case-insensitive, after trimming surrounding whitespace).
+ * Allowed: site-relative paths (`/` but not protocol-relative `//`), `./`,
+ * `../`, in-page anchors (`#`), or http(s) URLs (`^https?:`, case-insensitive,
+ * after trimming surrounding whitespace).
*
* @param {unknown} url - candidate URL, typically user- or remote-controlled.
* @param {string} [fallback='#'] - returned when `url` is rejected.
@@ -15,7 +16,7 @@ export function safeUrl(url, fallback = '#') {
if (typeof url !== 'string') return fallback;
const trimmed = url.trim();
if (!trimmed) return fallback;
- if (/^(?:\/|\.\/|\.\.\/|#)/.test(trimmed)) return url;
+ if (/^(?:\/(?!\/)|\.\/|\.\.\/|#)/.test(trimmed)) return url;
if (/^https?:/i.test(trimmed)) return url;
return fallback;
}
diff --git a/src/three-allowance.js b/src/three-allowance.js
index 89fddf6fb..e44b2a89d 100644
--- a/src/three-allowance.js
+++ b/src/three-allowance.js
@@ -112,6 +112,10 @@ export async function grantAllowance({
'confirmed',
);
+ // Reconcile server-side so the registry flips this grant to active and the
+ // wallet panel shows the new cap immediately (best-effort; status read self-heals).
+ await confirmOnServer(prep.delegation_pda, { network }).catch(() => {});
+
onStatus('done');
return {
ok: true,
@@ -121,3 +125,55 @@ export async function grantAllowance({
expiry_ts: prep.expiry_ts,
};
}
+
+/** Tell the server a signed grant/revoke landed so it reconciles the registry now. */
+async function confirmOnServer(delegationPda, { revoked = false, network = 'mainnet' } = {}) {
+ const r = await fetch('/api/token/allowance-confirm', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ delegation_pda: delegationPda, revoked, network }),
+ });
+ return r.ok ? r.json() : null;
+}
+
+/**
+ * Revoke a delegation — cancel a spend cap and reclaim its rent. One signature.
+ * @param {{ delegationPda: string, network?: string, wallet?: any,
+ * onStatus?: (s: 'building'|'awaiting_signature'|'confirming'|'done') => void }} params
+ */
+export async function revokeAllowance({ delegationPda, network = 'mainnet', wallet, onStatus = () => {} }) {
+ if (!delegationPda) throw Object.assign(new Error('Missing allowance to revoke.'), { code: 'bad_input' });
+
+ onStatus('building');
+ const prepResp = await fetch('/api/token/allowance-revoke', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ delegation_pda: delegationPda, network }),
+ });
+ const prep = await prepResp.json();
+ if (!prepResp.ok) {
+ throw Object.assign(new Error(prep.error_description || 'could not build revoke'), { code: prep.error });
+ }
+
+ const web3 = await loadWeb3();
+ const { Connection, Transaction } = web3;
+ const provider = await getProvider(wallet);
+ const connection = new Connection(rpcEndpoint(), 'confirmed');
+ 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',
+ );
+ await confirmOnServer(delegationPda, { revoked: true, network }).catch(() => {});
+
+ onStatus('done');
+ return { ok: true, signature, delegation_pda: delegationPda };
+}
diff --git a/tests/agent-monetization.test.js b/tests/agent-monetization.test.js
index 9d4e94287..2f767d497 100644
--- a/tests/agent-monetization.test.js
+++ b/tests/agent-monetization.test.js
@@ -343,7 +343,11 @@ describe('Revenue Attribution', () => {
end_time: null,
},
]);
- // consumeIntent UPDATE and revenue event INSERT both hit empty queue → []
+ // consumeIntent UPDATE ... RETURNING id → this request wins the
+ // paid→consumed claim, so the revenue insert proceeds (gating the credit
+ // on the claim is what prevents double-credit under concurrency).
+ sqlState.queue.push([{ id: intentId }]);
+ // revenue event INSERT (ON CONFLICT DO NOTHING) → []
const { status, body } = await invoke(x402Handler, {
method: 'POST',
diff --git a/tests/monetization-service.test.js b/tests/monetization-service.test.js
index 07a2f0c0a..5bee01c05 100644
--- a/tests/monetization-service.test.js
+++ b/tests/monetization-service.test.js
@@ -188,10 +188,12 @@ describe('recordRevenueEvent', () => {
expect(findInsert().values[1]).toBe('sig-abc');
});
- it("falls back to 'direct' when neither intentId nor txHash is given", async () => {
+ it('falls back to a unique direct_ key when neither intentId nor txHash is given', async () => {
sqlState.queue.push([{ id: 'rev-5' }]);
await recordRevenueEvent({ ...baseEvent, intentId: undefined, txHash: undefined });
- expect(findInsert().values[1]).toBe('direct');
+ // intent_id is UNIQUE, so distinct direct credits must NOT collide on a
+ // shared literal — each gets its own synthetic key.
+ expect(findInsert().values[1]).toMatch(/^direct_[0-9a-f-]{36}$/);
});
it('rejects a non-positive amount before touching the database', async () => {
diff --git a/tests/src/vanity-address-match.test.js b/tests/src/vanity-address-match.test.js
new file mode 100644
index 000000000..1360a562c
--- /dev/null
+++ b/tests/src/vanity-address-match.test.js
@@ -0,0 +1,49 @@
+/**
+ * addressMatchesPattern is the server's security gate for adopting a vanity
+ * keypair the owner ground in their browser: /api/agents/:id/solana/vanity
+ * re-derives the address from the supplied secret_key and refuses to store it
+ * unless it actually satisfies the requested prefix/suffix. These tests pin the
+ * matching rules — especially the rejection paths, where a bug would let a
+ * client assign an address that doesn't match what they claimed.
+ */
+import { describe, it, expect } from 'vitest';
+import { addressMatchesPattern } from '../../api/_lib/pump-vanity.js';
+
+const ADDR = 'AGNTxK9pZqf3mWcVbN1rT7sQ4hLdJ2yUe8gKpRzaBca'; // starts 'AGNT', ends 'Bca'
+
+describe('addressMatchesPattern', () => {
+ it('accepts an exact case-sensitive prefix', () => {
+ expect(addressMatchesPattern(ADDR, { prefix: 'AGNT' })).toBe(true);
+ });
+
+ it('accepts an exact case-sensitive suffix', () => {
+ expect(addressMatchesPattern(ADDR, { suffix: 'Bca' })).toBe(true);
+ });
+
+ it('accepts a combined prefix + suffix', () => {
+ expect(addressMatchesPattern(ADDR, { prefix: 'AGN', suffix: 'ca' })).toBe(true);
+ });
+
+ it('rejects a case mismatch when case-sensitive (the security case)', () => {
+ // 'agnt' is NOT a prefix of 'AGNT…' unless the owner opted into ignoreCase.
+ expect(addressMatchesPattern(ADDR, { prefix: 'agnt' })).toBe(false);
+ });
+
+ it('accepts a case mismatch only when ignoreCase is set', () => {
+ expect(addressMatchesPattern(ADDR, { prefix: 'agnt', ignoreCase: true })).toBe(true);
+ expect(addressMatchesPattern(ADDR, { suffix: 'BCA', ignoreCase: true })).toBe(true);
+ });
+
+ it('rejects an address that does not match the claimed pattern', () => {
+ expect(addressMatchesPattern(ADDR, { prefix: 'ZZZ' })).toBe(false);
+ expect(addressMatchesPattern(ADDR, { suffix: 'xyz' })).toBe(false);
+ expect(addressMatchesPattern(ADDR, { prefix: 'AGN', suffix: 'XX' })).toBe(false);
+ });
+
+ it('rejects empty/missing patterns and bad input (no silent pass)', () => {
+ expect(addressMatchesPattern(ADDR, {})).toBe(false);
+ expect(addressMatchesPattern(ADDR, { prefix: '', suffix: '' })).toBe(false);
+ expect(addressMatchesPattern('', { prefix: 'AGNT' })).toBe(false);
+ expect(addressMatchesPattern(null, { prefix: 'AGNT' })).toBe(false);
+ });
+});
diff --git a/tests/token-allowance.test.js b/tests/token-allowance.test.js
index 861cc5a51..7dffa5e07 100644
--- a/tests/token-allowance.test.js
+++ b/tests/token-allowance.test.js
@@ -15,6 +15,7 @@ import {
eventAuthorityPda,
ixInitSubscriptionAuthority,
ixCreateFixedDelegation,
+ ixRevokeDelegation,
ixTransferFixed,
parseSubscriptionAuthorityInitId,
parseFixedDelegation,
@@ -88,6 +89,23 @@ describe('instruction encodings', () => {
expect(ix.keys[0].isSigner).toBe(true); // delegator signs the grant
});
+ it('revokeDelegation: discriminator 3, authority signs, delegation account is writable', () => {
+ const delegationPda = fixedDelegationPda({
+ subscriptionAuthority: subscriptionAuthorityPda(USER, MINT),
+ delegator: USER,
+ delegatee: DELEGATEE,
+ nonce: 3,
+ });
+ const ix = ixRevokeDelegation({ authority: USER, delegationPda });
+ expect([...ix.data]).toEqual([3]);
+ expect(ix.keys).toHaveLength(2);
+ expect(ix.keys[0].pubkey.equals(USER)).toBe(true);
+ expect(ix.keys[0].isSigner).toBe(true);
+ expect(ix.keys[1].pubkey.equals(delegationPda)).toBe(true);
+ expect(ix.keys[1].isWritable).toBe(true);
+ expect(ix.keys[1].isSigner).toBe(false);
+ });
+
it('transferFixed: disc 4 + amount(u64) + delegator(32) + mint(32); delegatee is the signer', () => {
const delegationPda = fixedDelegationPda({
subscriptionAuthority: subscriptionAuthorityPda(USER, MINT),
diff --git a/x402-payment-modal/server/checkout.js b/x402-payment-modal/server/checkout.js
index 19b2db0bf..10a3e2699 100644
--- a/x402-payment-modal/server/checkout.js
+++ b/x402-payment-modal/server/checkout.js
@@ -142,14 +142,44 @@ function uiToAtomic(uiAmount, decimals) {
}
// Short-lived caches so repeated prepare calls don't re-issue identical RPC
-// round-trips. Mint decimals are effectively immutable; a Solana blockhash stays
-// valid for ~60-90s, so a few seconds of reuse cuts redundant traffic without
-// handing out a blockhash too stale for the buyer's signed tx to land.
-const MINT_DECIMALS_TTL_MS = 5 * 60 * 1000;
-const BLOCKHASH_TTL_MS = 8 * 1000;
-const mintDecimalsCache = new Map(); // `${rpc}:${mint}` -> { decimals, at }
-const blockhashCache = new Map(); // rpc -> { blockhash, at }
-const tokenProgramCache = new Map(); // `${rpc}:${mint}` -> { programId, at }
+// round-trips. Mint decimals and the owning token program are immutable, so they
+// key by mint alone (shared across RPC providers on the same cluster). A Solana
+// blockhash stays valid ~60-90s; we amortize the fetch for a window but the
+// settle path tolerates a slightly older one. ATA existence only ever flips
+// false→true (an account, once created, persists), so we cache the positive.
+//
+// Keys are cluster-scoped ('mainnet'/'devnet'), never per-RPC-URL, so failover
+// between providers preserves cache hits. All caches are LRU-bounded so a stream
+// of distinct arbitrary mints can't grow them without limit on a warm instance.
+const MINT_META_TTL_MS = 30 * 60 * 1000;
+const BLOCKHASH_TTL_MS = 20 * 1000;
+const ATA_EXISTS_TTL_MS = 10 * 60 * 1000;
+const CACHE_MAX = 2000;
+const mintDecimalsCache = new Map(); // `${cluster}:${mint}` -> { decimals, at }
+const blockhashCache = new Map(); // cluster -> { blockhash, at }
+const tokenProgramCache = new Map(); // `${cluster}:${mint}` -> { programId, at }
+const ataExistsCache = new Map(); // `${cluster}:${ata}` -> { at }
+const connectionCache = new Map(); // rpcUrl -> Connection
+
+// Bounded insert: evict the oldest entry (Map preserves insertion order) once
+// the cap is hit, keeping memory flat under arbitrary-mint traffic.
+function cacheSet(map, key, value, max = CACHE_MAX) {
+ if (map.size >= max && !map.has(key)) {
+ const oldest = map.keys().next().value;
+ if (oldest !== undefined) map.delete(oldest);
+ }
+ map.set(key, value);
+}
+
+// Decimals + owning program for the assets the modal treats as first-class.
+// Short-circuiting these skips two RPC reads on the hot path (USDC is the bulk
+// of real traffic). THREE is Token-2022; the rest are legacy SPL Token.
+const WSOL_MINT = 'So11111111111111111111111111111111111111112';
+const WELL_KNOWN_MINT_META = Object.freeze({
+ [USDC_MINT_SOLANA]: { decimals: 6, legacy: true },
+ [THREE_MINT]: { decimals: 6, legacy: false },
+ [WSOL_MINT]: { decimals: 9, legacy: true },
+});
/** Thrown for any client-correctable problem; carries an HTTP `status` + `code`. */
export class CheckoutError extends Error {
@@ -169,9 +199,60 @@ export function isSolanaNetwork(network) {
);
}
-function rpcFor(network, { rpcUrl, devnetRpcUrl } = {}) {
- if (network === NETWORK_SOLANA_DEVNET) return devnetRpcUrl || DEFAULT_DEVNET_RPC;
- return rpcUrl || DEFAULT_MAINNET_RPC;
+function clusterFor(network) {
+ return network === NETWORK_SOLANA_DEVNET ? 'devnet' : 'mainnet';
+}
+
+let warnedDefaultRpc = false;
+
+// Resolve the ordered list of RPC endpoints to try. Accepts a single `rpcUrl`
+// or an `rpcUrls` array (for real failover); same for devnet. Falling back to
+// the rate-limited public RPC is a production footgun under load, so warn once.
+function rpcListFor(network, opts = {}) {
+ const devnet = network === NETWORK_SOLANA_DEVNET;
+ const single = devnet ? opts.devnetRpcUrl : opts.rpcUrl;
+ const many = devnet ? opts.devnetRpcUrls : opts.rpcUrls;
+ const list = []
+ .concat(Array.isArray(many) ? many : [])
+ .concat(single ? [single] : [])
+ .filter((u) => typeof u === 'string' && u.length);
+ if (list.length) return [...new Set(list)];
+ if (!warnedDefaultRpc) {
+ warnedDefaultRpc = true;
+ console.warn(
+ '[x402-payment-modal] No rpcUrl/rpcUrls configured — falling back to the public ' +
+ 'Solana RPC, which is heavily rate-limited and will fail under load. Pass a ' +
+ 'dedicated RPC (Helius/Triton/QuickNode) via { rpcUrls: [...] }.',
+ );
+ }
+ return [devnet ? DEFAULT_DEVNET_RPC : DEFAULT_MAINNET_RPC];
+}
+
+// Reuse one Connection per RPC URL so socket keep-alive survives across
+// requests on a warm instance instead of paying TCP/TLS setup every prepare.
+function getConnection(url) {
+ let conn = connectionCache.get(url);
+ if (!conn) {
+ conn = new Connection(url, 'confirmed');
+ cacheSet(connectionCache, url, conn, 50);
+ }
+ return conn;
+}
+
+// Run `fn(conn)` against each RPC in order, rotating to the next on a transient
+// RPC/network error. A CheckoutError is a deterministic client problem (bad
+// input, mint isn't an SPL token) — surface it immediately, don't retry.
+async function withFailover(urls, fn) {
+ let lastErr;
+ for (const url of urls) {
+ try {
+ return await fn(getConnection(url));
+ } catch (err) {
+ if (err instanceof CheckoutError) throw err;
+ lastErr = err;
+ }
+ }
+ throw lastErr || new Error('all RPC endpoints failed');
}
const BASE58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
@@ -213,36 +294,55 @@ function validateAccept(accept) {
// Pump.fun mints (including THREE) and many newer assets are Token-2022, whose
// program id differs; deriving ATAs or building transferChecked with the wrong
// program yields the wrong accounts and an unprocessable transaction. The owner
-// is immutable, so cache it like decimals.
-async function getTokenProgramId(conn, rpc, mint) {
- const key = `${rpc}:${mint.toBase58()}`;
+// is immutable, so cache it (and short-circuit the first-class assets entirely).
+async function getTokenProgramId(conn, cluster, mint) {
+ const base58 = mint.toBase58();
+ const known = WELL_KNOWN_MINT_META[base58];
+ if (known) return known.legacy ? TOKEN_PROGRAM_ID : TOKEN_2022_PROGRAM_ID;
+ const key = `${cluster}:${base58}`;
const hit = tokenProgramCache.get(key);
- if (hit && Date.now() - hit.at < MINT_DECIMALS_TTL_MS) return hit.programId;
+ if (hit && Date.now() - hit.at < MINT_META_TTL_MS) return hit.programId;
const info = await conn.getAccountInfo(mint, 'confirmed');
- if (!info) throw new CheckoutError(400, 'invalid_request', `mint ${mint.toBase58()} not found on this network`);
+ // A null here is usually a flaky RPC, not a missing mint — throw a plain Error
+ // so withFailover retries the next endpoint before giving up.
+ if (!info) throw new Error(`getAccountInfo returned null for mint ${base58}`);
const owner = info.owner;
let programId;
if (owner.equals(TOKEN_2022_PROGRAM_ID)) programId = TOKEN_2022_PROGRAM_ID;
else if (owner.equals(TOKEN_PROGRAM_ID)) programId = TOKEN_PROGRAM_ID;
- else throw new CheckoutError(400, 'invalid_request', `mint ${mint.toBase58()} is not an SPL token (owner ${owner.toBase58()})`);
- tokenProgramCache.set(key, { programId, at: Date.now() });
+ else throw new CheckoutError(400, 'invalid_request', `mint ${base58} is not an SPL token (owner ${owner.toBase58()})`);
+ cacheSet(tokenProgramCache, key, { programId, at: Date.now() });
return programId;
}
-async function getMintDecimals(conn, rpc, mint, programId) {
- const key = `${rpc}:${mint.toBase58()}`;
+async function getMintDecimals(conn, cluster, mint, programId) {
+ const base58 = mint.toBase58();
+ const known = WELL_KNOWN_MINT_META[base58];
+ if (known) return known.decimals;
+ const key = `${cluster}:${base58}`;
const hit = mintDecimalsCache.get(key);
- if (hit && Date.now() - hit.at < MINT_DECIMALS_TTL_MS) return hit.decimals;
+ if (hit && Date.now() - hit.at < MINT_META_TTL_MS) return hit.decimals;
const info = await getMint(conn, mint, 'confirmed', programId);
- mintDecimalsCache.set(key, { decimals: info.decimals, at: Date.now() });
+ cacheSet(mintDecimalsCache, key, { decimals: info.decimals, at: Date.now() });
return info.decimals;
}
-async function getRecentBlockhash(conn, rpc) {
- const hit = blockhashCache.get(rpc);
+// Whether the recipient's token account already exists. Once created it persists,
+// so a positive result is cached; a negative is not (we keep emitting the
+// idempotent-create instruction until the account shows up).
+async function receiverAtaExists(conn, cluster, ata) {
+ const key = `${cluster}:${ata.toBase58()}`;
+ if (ataExistsCache.has(key) && Date.now() - ataExistsCache.get(key).at < ATA_EXISTS_TTL_MS) return true;
+ const info = await conn.getAccountInfo(ata, 'confirmed');
+ if (info) cacheSet(ataExistsCache, key, { at: Date.now() });
+ return Boolean(info);
+}
+
+async function getRecentBlockhash(conn, cluster) {
+ const hit = blockhashCache.get(cluster);
if (hit && Date.now() - hit.at < BLOCKHASH_TTL_MS) return hit.blockhash;
const { blockhash } = await conn.getLatestBlockhash('confirmed');
- blockhashCache.set(rpc, { blockhash, at: Date.now() });
+ cacheSet(blockhashCache, cluster, { blockhash, at: Date.now() }, 8);
return blockhash;
}
@@ -255,15 +355,17 @@ async function getRecentBlockhash(conn, rpc) {
* @param {object} args.accept one x402 `accept` entry (scheme=exact, Solana)
* @param {string} args.buyer buyer's base58 Solana address
* @param {string} [args.rpcUrl] mainnet RPC URL override
+ * @param {string[]} [args.rpcUrls] mainnet RPC URLs for failover (preferred)
* @param {string} [args.devnetRpcUrl] devnet RPC URL override
+ * @param {string[]} [args.devnetRpcUrls] devnet RPC URLs for failover
* @returns {Promise<{ network: string, tx_base64: string, recent_blockhash: string }>}
*/
-export async function prepareSolanaCheckout({ accept, buyer, rpcUrl, devnetRpcUrl }) {
+export async function prepareSolanaCheckout({ accept, buyer, rpcUrl, rpcUrls, devnetRpcUrl, devnetRpcUrls }) {
validateAccept(accept);
assertPubkey(buyer, 'buyer');
- const rpc = rpcFor(accept.network, { rpcUrl, devnetRpcUrl });
- const conn = new Connection(rpc, 'confirmed');
+ const urls = rpcListFor(accept.network, { rpcUrl, rpcUrls, devnetRpcUrl, devnetRpcUrls });
+ const cluster = clusterFor(accept.network);
const mint = new PublicKey(accept.asset);
const payTo = new PublicKey(accept.payTo);
@@ -271,52 +373,61 @@ export async function prepareSolanaCheckout({ accept, buyer, rpcUrl, devnetRpcUr
const buyerPubkey = new PublicKey(buyer);
const amount = BigInt(accept.amount);
- // Pick the owning token program (legacy SPL Token vs Token-2022) so ATAs,
- // the idempotent create, and transferChecked all target the right program —
- // THREE and other pump.fun mints are Token-2022.
- const tokenProgramId = await getTokenProgramId(conn, rpc, mint);
+ return withFailover(urls, async (conn) => {
+ // Pick the owning token program (legacy SPL Token vs Token-2022) so ATAs,
+ // the idempotent create, and transferChecked all target the right program —
+ // THREE and other pump.fun mints are Token-2022. This must resolve first
+ // because the ATA derivations depend on it.
+ const tokenProgramId = await getTokenProgramId(conn, cluster, mint);
- const senderAta = getAssociatedTokenAddressSync(
- mint, buyerPubkey, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,
- );
- const receiverAta = getAssociatedTokenAddressSync(
- mint, payTo, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,
- );
- const mintDecimals = await getMintDecimals(conn, rpc, mint, tokenProgramId);
-
- const ixs = [
- ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),
- ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }),
- ];
- // Create the recipient's token account if it doesn't exist yet — idempotent,
- // paid for by the fee payer so the buyer is never charged extra SOL.
- const receiverInfo = await conn.getAccountInfo(receiverAta);
- if (!receiverInfo) {
+ const senderAta = getAssociatedTokenAddressSync(
+ mint, buyerPubkey, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ const receiverAta = getAssociatedTokenAddressSync(
+ mint, payTo, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+
+ // The three remaining reads are independent — fan them out in parallel
+ // instead of serially (cuts prepare latency ~40% on a cold cache, near
+ // zero when decimals/program/ATA are all cached).
+ const [mintDecimals, receiverPresent, blockhash] = await Promise.all([
+ getMintDecimals(conn, cluster, mint, tokenProgramId),
+ receiverAtaExists(conn, cluster, receiverAta),
+ getRecentBlockhash(conn, cluster),
+ ]);
+
+ const ixs = [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }),
+ ];
+ // Create the recipient's token account if it doesn't exist yet — idempotent,
+ // paid for by the fee payer so the buyer is never charged extra SOL.
+ if (!receiverPresent) {
+ ixs.push(
+ createAssociatedTokenAccountIdempotentInstruction(
+ feePayer, receiverAta, payTo, mint, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,
+ ),
+ );
+ }
ixs.push(
- createAssociatedTokenAccountIdempotentInstruction(
- feePayer, receiverAta, payTo, mint, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,
+ createTransferCheckedInstruction(
+ senderAta, mint, receiverAta, buyerPubkey, amount, mintDecimals, [], tokenProgramId,
),
);
- }
- ixs.push(
- createTransferCheckedInstruction(
- senderAta, mint, receiverAta, buyerPubkey, amount, mintDecimals, [], tokenProgramId,
- ),
- );
- const blockhash = await getRecentBlockhash(conn, rpc);
- const message = new TransactionMessage({
- payerKey: feePayer,
- recentBlockhash: blockhash,
- instructions: ixs,
- }).compileToV0Message();
- const vtx = new VersionedTransaction(message);
+ const message = new TransactionMessage({
+ payerKey: feePayer,
+ recentBlockhash: blockhash,
+ instructions: ixs,
+ }).compileToV0Message();
+ const vtx = new VersionedTransaction(message);
- return {
- network: accept.network,
- tx_base64: Buffer.from(vtx.serialize()).toString('base64'),
- recent_blockhash: blockhash,
- };
+ return {
+ network: accept.network,
+ tx_base64: Buffer.from(vtx.serialize()).toString('base64'),
+ recent_blockhash: blockhash,
+ };
+ });
}
const BUILDER_CODE_PATTERN = /^[a-z0-9_]{1,32}$/;
@@ -378,17 +489,20 @@ export function encodeX402Payment({ accept, signedTxBase64, resourceUrl, builder
* @param {object} args
* @param {'prepare'|'encode'} args.action
* @param {object} args.body parsed JSON request body
- * @param {object} [args.options] { rpcUrl, devnetRpcUrl }
+ * @param {object} [args.options] { rpcUrl, rpcUrls, devnetRpcUrl, devnetRpcUrls, logger }
* @returns {Promise<{ status: number, body: object }>}
*/
export async function handleCheckout({ action, body = {}, options = {} }) {
+ const log = typeof options.logger === 'function' ? options.logger : console.error;
try {
if (action === 'prepare') {
const data = await prepareSolanaCheckout({
accept: body.accept,
buyer: body.buyer,
rpcUrl: options.rpcUrl,
+ rpcUrls: options.rpcUrls,
devnetRpcUrl: options.devnetRpcUrl,
+ devnetRpcUrls: options.devnetRpcUrls,
});
return { status: 200, body: data };
}
@@ -409,8 +523,9 @@ export async function handleCheckout({ action, body = {}, options = {} }) {
if (err instanceof CheckoutError) {
return { status: err.status, body: { error: err.code, error_description: err.message } };
}
- // Unexpected (RPC down, malformed tx). Surface a generic 502 — the caller
- // shows "try again"; the real cause is in your server logs.
+ // Unexpected (RPC down, malformed tx). The caller sees a generic 502, but
+ // ops needs the root cause — log it instead of swallowing it silently.
+ log(`[x402-payment-modal] checkout ${action} failed:`, err?.stack || err?.message || err);
return {
status: 502,
body: { error: 'checkout_failed', error_description: 'Could not build the Solana payment. Try again.' },
diff --git a/x402-payment-modal/server/express.js b/x402-payment-modal/server/express.js
index f87c0caff..7ebf83c71 100644
--- a/x402-payment-modal/server/express.js
+++ b/x402-payment-modal/server/express.js
@@ -15,9 +15,12 @@ import { handleCheckout } from './checkout.js';
/**
* @param {object} [options]
- * @param {string} [options.rpcUrl] Solana mainnet RPC URL
- * @param {string} [options.devnetRpcUrl] Solana devnet RPC URL
- * @param {string} [options.origin] Access-Control-Allow-Origin (default '*')
+ * @param {string} [options.rpcUrl] Solana mainnet RPC URL
+ * @param {string[]} [options.rpcUrls] Solana mainnet RPC URLs for failover (preferred under load)
+ * @param {string} [options.devnetRpcUrl] Solana devnet RPC URL
+ * @param {string[]} [options.devnetRpcUrls] Solana devnet RPC URLs for failover
+ * @param {Function} [options.logger] called with the root cause on unexpected failures
+ * @param {string} [options.origin] Access-Control-Allow-Origin (default '*')
* @returns {import('express').RequestHandler}
*/
export function x402CheckoutRouter(options = {}) {
@@ -25,7 +28,7 @@ export function x402CheckoutRouter(options = {}) {
return async function x402CheckoutHandler(req, res) {
res.setHeader('Access-Control-Allow-Origin', allowOrigin);
res.setHeader('Access-Control-Allow-Methods', 'POST,OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'content-type');
+ res.setHeader('Access-Control-Allow-Headers', 'content-type, x-idempotency-key');
if (req.method === 'OPTIONS') {
res.status(204).end();
return;