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: user follows, walk social companions, and forge tier validation

nirholas1b7d29a87e58
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cbb6fc660..37a6f304a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,8 +11,10 @@ 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. You can see what your remaining cap covers, get a heads-up when it runs low, top it up, or revoke it in one click anytime. Prefer to sign each payment? Just leave it off. (`/three-token`) `[feature]`
- **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]`
- **Discover and character feeds load faster under heavy traffic** — The Discover grid and the published-agents (Characters) feed now serve from the edge cache, so a surge of visitors is absorbed at the CDN instead of re-running a database scan on every request. Pages stay fast and consistent even during a rush, and a stale-while-revalidate window keeps them warm between refreshes. (`/discover`) `[improvement, infra]`
+- **Every Forge quality tier now runs on free engines** — Forge's quality tiers — Draft, Standard, and High — all generate on zero-cost engines now: Draft and Standard on the fast free NVIDIA lane, and High on the higher-fidelity, fully textured free HuggingFace engine. Higher tiers buy you genuinely better geometry and textures, not a different bill behind the scenes. Photo-to-3D at any tier routes straight to a free engine too, so a generation never quietly falls back to a paid lane. The High tier stays a $THREE holder perk (or a one-off pay-per-use) — that's the price of premium quality, not a cost we're passing through. (`/forge`) `[improvement, feature]`
- **Forge hardened for a traffic surge — faster loads, protected free lanes** — We scaled Forge for the influx of new users. The engine catalog and live health status now serve from the edge cache, so the page loads instantly even under heavy traffic instead of recomputing on every visit. We also added a platform-wide safety valve on paid generation: if demand ever spikes past the shared paid budget, the free engines (NVIDIA and Hugging Face) stay fully open and you get a clear 'try a free engine' message instead of a hard failure — your own bring-your-own-key engines are never affected. Net result: Forge stays fast and available as we grow, and free 3D generation never gets crowded out. (`/forge`) `[infra, improvement]`
-- **Forge scales further — duplicate generations collapse, free lane protected, prices shown up front** — More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. Finally, the 3D viewer shows a loading shimmer instead of a dark void while your model paints in. (`/forge`) `[improvement, infra]`
+- **Forge scales further — duplicate generations collapse, free lane protected, prices shown up front** — More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. The engine picker also gained a small legend explaining the badges at a glance — which engines are free, which use your own key, and which are busy or unavailable. And the 3D viewer now shows a loading shimmer instead of a dark void while your model paints in. (`/forge`) `[improvement, infra]`
+- **Forge stays calm under a crowd: live countdown, graceful high-demand handling, one-tap model retry** — Generating a 3D model now feels steadier when lots of people are forging at once. The progress meter shows a real "~Ns left" countdown instead of a static estimate, so you can see it moving. If the free engines are momentarily at capacity during a rush, you get a friendly "high demand" notice with a live retry countdown that re-arms itself the moment a slot frees up — your spot in line, not a dead-end error — and you can keep refining a model you already have while you wait. And if a finished model ever fails to paint because of a brief network blip, a new Retry button reloads it in place instead of forcing a download. Behind the scenes, generation success rate and latency are now tracked so we can catch slowdowns before they reach you. (`/forge`) `[improvement, fix]`
- **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]`
- **Grind an agent's vanity wallet right on its page — with your CPU cores** — Giving an agent a custom wallet address used to run on our servers, so it was capped at short patterns and would time out and error on anything harder. Now the agent's Wallet → Vanity tab grinds the address in your own browser, exactly like the standalone /vanity-wallet tool: choose how many CPU cores to spend, match case-insensitively for a faster find, watch the live tries-per-second and ETA, and pause or resume anytime. Longer, rarer patterns are now possible with no timeouts. When a match is found, any SOL or tokens in the old wallet are still automatically swept to the new address before the key is swapped — funds are never stranded — and the server verifies the new address truly matches your pattern before storing it. `[fix, feature, improvement]`
diff --git a/api/_lib/coin/three-holders.js b/api/_lib/coin/three-holders.js
index 32771537c..d0a25a0f9 100644
--- a/api/_lib/coin/three-holders.js
+++ b/api/_lib/coin/three-holders.js
@@ -68,9 +68,18 @@ function ensureTables() {
* Called by the cron only. Returns { holders, scannedAt } for logging.
*/
export async function refreshThreeHolderSnapshot() {
+ const balances = await fetchHolderBalances({ mint: THREE_MINT });
+ return persistThreeHolderSnapshot(balances);
+}
+
+/**
+ * Persist an already-scanned Map<wallet, bigint> to the snapshot table. Split out
+ * of refreshThreeHolderSnapshot so the cold-fallback read path can reuse a single
+ * scan for BOTH the response and self-healing the cache — never scanning twice.
+ */
+export async function persistThreeHolderSnapshot(balances) {
if (!(await ensureTables())) throw new Error('three_holder_snapshot table unavailable');
- const balances = await fetchHolderBalances({ mint: THREE_MINT });
const wallets = [...balances.keys()].filter((w) => balances.get(w) > 0n);
const now = new Date();
@@ -185,17 +194,15 @@ async function coldFallbackScan() {
return fetchHolderBalances({ mint: THREE_MINT });
}
try {
- // Winner: refresh the shared snapshot so subsequent reads hit cache instead
- // of scanning. Fall back to a read-only scan if the refresh can't persist
- // (e.g. snapshot table not migrated yet) so the page still renders.
- try {
- await refreshThreeHolderSnapshot();
- const snap = await readThreeHolderSnapshot();
- if (snap) return snap;
- } catch (err) {
- console.warn('[three-holders] cold refresh failed, serving live scan:', err?.message || err);
- }
- return fetchHolderBalances({ mint: THREE_MINT });
+ // Winner: one live scan serves this response AND self-heals the shared
+ // snapshot, so subsequent reads hit cache instead of scanning. Persist is
+ // fire-and-forget — a write failure (e.g. snapshot table not migrated yet)
+ // must never break the page, and we never scan twice.
+ const balances = await fetchHolderBalances({ mint: THREE_MINT });
+ persistThreeHolderSnapshot(balances).catch((err) =>
+ console.warn('[three-holders] cold snapshot persist failed:', err?.message || err),
+ );
+ return balances;
} finally {
await releaseLock(COLD_SCAN_LOCK_KEY);
}
diff --git a/api/_lib/forge-scale.js b/api/_lib/forge-scale.js
index eede3ae43..17c8e28b0 100644
--- a/api/_lib/forge-scale.js
+++ b/api/_lib/forge-scale.js
@@ -169,8 +169,34 @@ export const SCALE_LIMITS = Object.freeze({
// Platform Replicate submits per 10s window before we shed to the free lane.
replicateSubmitLimit: intEnv('FORGE_REPLICATE_SUBMIT_LIMIT', 40),
replicateSubmitWindowS: 10,
+ // Max PLATFORM-keyed paid generations one identity (browser client) may run per
+ // UTC day — the layer per-IP and the global hourly cap don't cover.
+ paidDailyPerClient: intEnv('FORGE_PAID_DAILY_CAP', 60),
});
+// ── Per-identity daily paid cap ───────────────────────────────────────────────
+// Bounds how many PLATFORM-keyed paid generations a single identity can run per UTC
+// day, on top of the per-IP hourly limiter and the platform-wide hourly ceiling.
+// Closes the rotating-IP / multi-session abuse path: one actor can stay under every
+// per-request cap yet drain paid spend across a day. Keyed by the forge client id
+// (the identity the rest of forge already scopes by). Counts attempts — a protective
+// daily ceiling is allowed to be slightly conservative. Fail-open without Redis.
+
+const DAILY_PREFIX = 'fc:daily:';
+
+export async function dailyPaidAllowed(identity, { limit }) {
+ if (!redis || !identity) return { ok: true, used: 0, limit };
+ const day = Math.floor(Date.now() / 86_400_000); // UTC day index
+ const key = `${DAILY_PREFIX}${identity}:${day}`;
+ try {
+ const used = await redis.incr(key);
+ if (used === 1) await redis.expire(key, 86_400 + 3600);
+ return { ok: used <= limit, used, limit };
+ } catch {
+ return { ok: true, used: 0, limit };
+ }
+}
+
// ── Shared circuit breaker ────────────────────────────────────────────────────
// A consecutive-failure breaker whose state lives in Redis so EVERY serverless
// instance sees the same open/closed decision. Without it each instance
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 49a5a2892..febdc23ca 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -32,6 +32,30 @@ create unique index if not exists users_privy_did_unique on users(privy_did) whe
-- Case-insensitive username lookup on the login/signup hot path (auth/[action].js).
create index if not exists users_display_name_lower on users(lower(display_name)) where deleted_at is null;
+-- Public social-profile fields. Surfaced on /u/<username> and editable by the
+-- owner via PATCH /api/auth/profile. All nullable — a profile with none set
+-- still renders cleanly from the user's avatars/agents/coins.
+alter table users add column if not exists bio text;
+alter table users add column if not exists website text;
+alter table users add column if not exists location text;
+alter table users add column if not exists banner_url text;
+
+-- ── user_follows — the social graph ──────────────────────────────────────────
+-- A directed follow edge: follower_id follows following_id. Composite PK makes
+-- a follow idempotent (one edge per pair) and the toggle a single upsert/delete.
+-- The check blocks self-follows at the storage layer. Two covering indexes back
+-- the hot reads: "who follows X" (follower list + count) and "who X follows"
+-- (following list + count, and the feed fan-out join).
+create table if not exists user_follows (
+ follower_id uuid not null references users(id) on delete cascade,
+ following_id uuid not null references users(id) on delete cascade,
+ created_at timestamptz not null default now(),
+ primary key (follower_id, following_id),
+ check (follower_id <> following_id)
+);
+create index if not exists user_follows_following on user_follows(following_id, created_at desc);
+create index if not exists user_follows_follower on user_follows(follower_id, created_at desc);
+
-- SAML SSO subject link (set when a user signs in via an enterprise IdP).
alter table users add column if not exists saml_name_id text;
alter table users add column if not exists saml_issuer text;
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index 02b4bf534..175926109 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -53,6 +53,21 @@ export const username = z
.max(30)
.regex(/^[a-zA-Z0-9_-]+$/, 'username must be alphanumeric with _ or -');
+// ── public profile fields (PATCH /api/auth/profile) ─────────────────────────
+// All accept '' so the owner can clear a field; the handler normalises '' → null.
+export const bio = z.string().trim().max(280);
+export const profileLocation = z.string().trim().max(80);
+// http(s) URL or empty. Capped well under any column limit; rejects javascript:
+// and other schemes so a stored value can never become an XSS sink when rendered
+// into an href. Empty string clears the field.
+export const httpUrl = z
+ .string()
+ .trim()
+ .max(500)
+ .refine((v) => v === '' || /^https:\/\/[^\s]+$/i.test(v) || /^http:\/\/[^\s]+$/i.test(v), {
+ message: 'must be an http(s) URL',
+ });
+
export const registerBody = z.object({
email,
password,
diff --git a/api/auth/[action].js b/api/auth/[action].js
index 03da5ea23..de9e9b32f 100644
--- a/api/auth/[action].js
+++ b/api/auth/[action].js
@@ -13,7 +13,7 @@ import { randomToken, randomDigits, sha256 } from '../_lib/crypto.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse, loginBody, registerBody, usernameRegisterBody, username as usernameValidator, displayName, email, password } from '../_lib/validate.js';
+import { parse, loginBody, registerBody, usernameRegisterBody, username as usernameValidator, displayName, email, password, bio as bioValidator, profileLocation, httpUrl } from '../_lib/validate.js';
import { sendPasswordResetEmail, sendVerificationEmail } from '../_lib/email.js';
import { generateReferralCode } from '../_lib/referrals.js';
import { seedDefaultAgent } from '../_lib/seed-default-agent.js';
@@ -187,7 +187,23 @@ async function handleMe(req, res) {
const profileSchema = z.object({
username: usernameValidator.optional(),
display_name: displayName.optional(),
-}).refine((b) => b.username !== undefined || b.display_name !== undefined, { message: 'at least one field required' });
+ bio: bioValidator.optional(),
+ website: httpUrl.optional(),
+ location: profileLocation.optional(),
+ avatar_url: httpUrl.optional(),
+ banner_url: httpUrl.optional(),
+}).refine(
+ (b) => Object.keys(b).length > 0,
+ { message: 'at least one field required' },
+);
+
+// Trim, and treat an empty string as an explicit "clear this field" → null.
+// `undefined` (key omitted) leaves the stored value untouched.
+function profileField(value, current) {
+ if (value === undefined) return current;
+ const trimmed = String(value).trim();
+ return trimmed === '' ? null : trimmed;
+}
async function handleProfile(req, res) {
if (cors(req, res, { methods: 'PATCH,OPTIONS', credentials: true })) return;
@@ -198,20 +214,46 @@ async function handleProfile(req, res) {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
const body = parse(profileSchema, await readJson(req));
- if (body.username) {
+
+ const [current] = await sql`
+ select username, display_name, bio, website, location, avatar_url, banner_url
+ from users where id = ${user.id} and deleted_at is null limit 1
+ `;
+ if (!current) return error(res, 401, 'unauthenticated', 'not signed in');
+
+ if (body.username && body.username.toLowerCase() !== (current.username || '').toLowerCase()) {
const taken = await sql`select id from users where lower(username) = ${body.username.toLowerCase()} and id != ${user.id} and deleted_at is null limit 1`;
if (taken[0]) return error(res, 409, 'conflict', 'username already taken');
}
- const [updated] = await sql`update users set username = coalesce(${body.username ?? null}, username), display_name = coalesce(${body.display_name ?? null}, display_name), updated_at = now() where id = ${user.id} and deleted_at is null returning id, display_name, username`;
+
+ const next = {
+ // username can only be set/changed, never cleared (it's the profile URL).
+ username: body.username !== undefined ? body.username : current.username,
+ display_name: body.display_name !== undefined ? body.display_name : current.display_name,
+ bio: profileField(body.bio, current.bio),
+ website: profileField(body.website, current.website),
+ location: profileField(body.location, current.location),
+ avatar_url: profileField(body.avatar_url, current.avatar_url),
+ banner_url: profileField(body.banner_url, current.banner_url),
+ };
+
+ const [updated] = await sql`
+ update users set
+ username = ${next.username},
+ display_name = ${next.display_name},
+ bio = ${next.bio},
+ website = ${next.website},
+ location = ${next.location},
+ avatar_url = ${next.avatar_url},
+ banner_url = ${next.banner_url},
+ updated_at = now()
+ where id = ${user.id} and deleted_at is null
+ returning id, username, display_name, bio, website, location, avatar_url, banner_url
+ `;
logAudit({
userId: user.id,
action: 'update_profile',
- meta: {
- fields: [
- body.username !== undefined ? 'username' : null,
- body.display_name !== undefined ? 'display_name' : null,
- ].filter(Boolean),
- },
+ meta: { fields: Object.keys(body) },
req,
});
return json(res, 200, { user: updated });
diff --git a/api/forge.js b/api/forge.js
index fd9255346..a9c080db5 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -67,6 +67,7 @@ import {
registerInFlight,
acquireBlockingSlot,
providerSubmitAllowed,
+ dailyPaidAllowed,
SCALE_LIMITS,
} from './_lib/forge-scale.js';
import { env as _env } from './_lib/env.js';
@@ -560,6 +561,20 @@ async function startJob(req, res) {
'Paid 3D generation is at capacity right now — switch to a free engine (NVIDIA or Hugging Face), or try again shortly.',
);
}
+ // Per-identity daily ceiling: closes the rotating-IP abuse path the per-IP
+ // hourly cap and the global hourly cap leave open (one actor under every
+ // per-request limit can still drain paid spend over a day). Keyed by the
+ // forge client id. Free and BYOK lanes are never counted.
+ const daily = await dailyPaidAllowed(clientKeyFrom(req), {
+ limit: SCALE_LIMITS.paidDailyPerClient,
+ });
+ if (!daily.ok) {
+ return json(res, 429, {
+ error: 'daily_limit_reached',
+ message:
+ 'You’ve reached today’s limit for paid generations. Free engines (NVIDIA, Hugging Face) stay open, or try again tomorrow.',
+ });
+ }
}
}
diff --git a/api/users/[username].js b/api/users/[username].js
index 939ee576f..706819af5 100644
--- a/api/users/[username].js
+++ b/api/users/[username].js
@@ -16,7 +16,8 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
const [user] = await sql`
- select id, display_name, username, created_at, wallet_address
+ select id, display_name, username, created_at, wallet_address,
+ bio, website, location, avatar_url, banner_url
from users
where lower(username) = ${username} and deleted_at is null
limit 1
@@ -143,7 +144,9 @@ export default wrap(async (req, res) => {
where a.user_id = ${user.id} and a.is_public = true and a.deleted_at is null
and m.is_public = true and (m.expires_at is null or m.expires_at > now())) as memories_count,
(select coalesce(sum(view_count), 0)::bigint from widgets
- where user_id = ${user.id} and is_public = true and deleted_at is null) as total_widget_views
+ where user_id = ${user.id} and is_public = true and deleted_at is null) as total_widget_views,
+ (select count(*)::int from user_follows where following_id = ${user.id}) as followers_count,
+ (select count(*)::int from user_follows where follower_id = ${user.id}) as following_count
`,
]);
@@ -262,15 +265,23 @@ export default wrap(async (req, res) => {
coins: statsRow?.coins_count ?? 0,
memories: statsRow?.memories_count ?? 0,
widget_views: Number(statsRow?.total_widget_views ?? 0),
+ followers: statsRow?.followers_count ?? 0,
+ following: statsRow?.following_count ?? 0,
};
res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');
return json(res, 200, {
user: {
+ id: user.id,
username: user.username,
display_name: user.display_name || user.username,
wallet_address: user.wallet_address,
created_at: user.created_at,
+ bio: user.bio || null,
+ website: user.website || null,
+ location: user.location || null,
+ avatar_url: user.avatar_url || null,
+ banner_url: user.banner_url || null,
},
stats,
social,
diff --git a/api/users/[username]/follow.js b/api/users/[username]/follow.js
new file mode 100644
index 000000000..26a64d10f
--- /dev/null
+++ b/api/users/[username]/follow.js
@@ -0,0 +1,96 @@
+// /api/users/:username/follow — the social-graph edge for a public profile.
+//
+// GET → { following, followed_by, followers_count, following_count }
+// `following` = does the signed-in viewer follow this user
+// `followed_by` = does this user follow the viewer back
+// Both false for anonymous viewers. Never cached (viewer-specific).
+// POST → follow this user (idempotent; session + CSRF required)
+// DELETE → unfollow this user (idempotent; session + CSRF required)
+//
+// POST/DELETE return the same envelope as GET so the client can update the
+// button label and the follower count from a single round-trip.
+
+import { sql } from '../../_lib/db.js';
+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+
+async function counts(userId) {
+ const [row] = await sql`
+ select
+ (select count(*)::int from user_follows where following_id = ${userId}) as followers_count,
+ (select count(*)::int from user_follows where follower_id = ${userId}) as following_count
+ `;
+ return {
+ followers_count: row?.followers_count ?? 0,
+ following_count: row?.following_count ?? 0,
+ };
+}
+
+async function edges(viewerId, targetId) {
+ if (!viewerId) return { following: false, followed_by: false };
+ const rows = await sql`
+ select follower_id, following_id from user_follows
+ where (follower_id = ${viewerId} and following_id = ${targetId})
+ or (follower_id = ${targetId} and following_id = ${viewerId})
+ `;
+ let following = false;
+ let followed_by = false;
+ for (const r of rows) {
+ if (r.follower_id === viewerId) following = true;
+ if (r.follower_id === targetId) followed_by = true;
+ }
+ return { following, followed_by };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
+
+ const username = (req.query.username || '').toLowerCase().trim();
+ if (!username || !/^[a-z0-9_-]{3,30}$/.test(username)) {
+ return error(res, 400, 'validation_error', 'invalid username');
+ }
+
+ const [target] = await sql`
+ select id, username from users
+ where lower(username) = ${username} and deleted_at is null
+ limit 1
+ `;
+ if (!target) return error(res, 404, 'not_found', 'user not found');
+
+ const viewer = await getSessionUser(req).catch(() => null);
+
+ if (req.method === 'GET') {
+ const [c, e] = await Promise.all([counts(target.id), edges(viewer?.id, target.id)]);
+ return json(res, 200, { ...e, ...c });
+ }
+
+ // Mutations from here: require a session + CSRF.
+ if (!viewer) return error(res, 401, 'unauthorized', 'sign in to follow');
+ if (!(await requireCsrf(req, res, viewer.id))) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (viewer.id === target.id) {
+ return error(res, 400, 'bad_request', 'you cannot follow yourself');
+ }
+
+ if (req.method === 'POST') {
+ await sql`
+ insert into user_follows (follower_id, following_id)
+ values (${viewer.id}, ${target.id})
+ on conflict do nothing
+ `;
+ } else {
+ await sql`
+ delete from user_follows
+ where follower_id = ${viewer.id} and following_id = ${target.id}
+ `;
+ }
+
+ const [c, e] = await Promise.all([counts(target.id), edges(viewer.id, target.id)]);
+ return json(res, 200, { ...e, ...c });
+});
diff --git a/api/users/[username]/follows.js b/api/users/[username]/follows.js
new file mode 100644
index 000000000..a7034b602
--- /dev/null
+++ b/api/users/[username]/follows.js
@@ -0,0 +1,87 @@
+// GET /api/users/:username/follows?type=followers|following — the list behind
+// the follower / following counts on a profile.
+//
+// ?type=followers → users who follow :username (default)
+// ?type=following → users :username follows
+// ?limit=…&offset=… (limit 1..100, default 50)
+//
+// Each row carries `is_following`: whether the signed-in viewer already follows
+// that user, so the list can render an accurate Follow / Following button per
+// row without an N+1 of follow-state probes. Anonymous viewers get all false.
+
+import { sql } from '../../_lib/db.js';
+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { publicUrl } from '../../_lib/r2.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const username = (req.query.username || '').toLowerCase().trim();
+ if (!username || !/^[a-z0-9_-]{3,30}$/.test(username)) {
+ return error(res, 400, 'validation_error', 'invalid username');
+ }
+ const type = req.query.type === 'following' ? 'following' : 'followers';
+ const limit = Math.min(100, Math.max(1, parseInt(req.query.limit, 10) || 50));
+ const offset = Math.max(0, parseInt(req.query.offset, 10) || 0);
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const [target] = await sql`
+ select id from users where lower(username) = ${username} and deleted_at is null limit 1
+ `;
+ if (!target) return error(res, 404, 'not_found', 'user not found');
+
+ const viewer = await getSessionUser(req).catch(() => null);
+ const viewerId = viewer?.id ?? null;
+
+ // followers: rows where following_id = target, list the followers (f.follower_id).
+ // following: rows where follower_id = target, list the followees (f.following_id).
+ const rows = type === 'followers'
+ ? await sql`
+ select u.id, u.username, u.display_name, u.avatar_url, u.bio, f.created_at,
+ exists(
+ select 1 from user_follows v
+ where v.follower_id = ${viewerId} and v.following_id = u.id
+ ) as is_following
+ from user_follows f
+ join users u on u.id = f.follower_id and u.deleted_at is null
+ where f.following_id = ${target.id}
+ order by f.created_at desc
+ limit ${limit} offset ${offset}
+ `
+ : await sql`
+ select u.id, u.username, u.display_name, u.avatar_url, u.bio, f.created_at,
+ exists(
+ select 1 from user_follows v
+ where v.follower_id = ${viewerId} and v.following_id = u.id
+ ) as is_following
+ from user_follows f
+ join users u on u.id = f.following_id and u.deleted_at is null
+ where f.follower_id = ${target.id}
+ order by f.created_at desc
+ limit ${limit} offset ${offset}
+ `;
+
+ const users = rows
+ .filter((u) => u.username) // a profile is only reachable by username
+ .map((u) => ({
+ username: u.username,
+ display_name: u.display_name || u.username,
+ avatar_url: u.avatar_url ? (u.avatar_url.startsWith('http') ? u.avatar_url : publicUrl(u.avatar_url)) : null,
+ bio: u.bio || null,
+ followed_at: u.created_at,
+ is_following: viewerId ? Boolean(u.is_following) : false,
+ is_self: viewerId === u.id,
+ }));
+
+ return json(res, 200, {
+ type,
+ users,
+ has_more: rows.length === limit,
+ next_offset: offset + rows.length,
+ });
+});
diff --git a/data/changelog.json b/data/changelog.json
index a807d9726..1bc66820f 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,26 @@
{
"$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": "Every Forge quality tier now runs on free engines",
+ "summary": "Forge's quality tiers — Draft, Standard, and High — all generate on zero-cost engines now: Draft and Standard on the fast free NVIDIA lane, and High on the higher-fidelity, fully textured free HuggingFace engine. Higher tiers buy you genuinely better geometry and textures, not a different bill behind the scenes. Photo-to-3D at any tier routes straight to a free engine too, so a generation never quietly falls back to a paid lane. The High tier stays a $THREE holder perk (or a one-off pay-per-use) — that's the price of premium quality, not a cost we're passing through.",
+ "tags": [
+ "improvement",
+ "feature"
+ ],
+ "link": "/forge"
+ },
+ {
+ "date": "2026-06-21",
+ "title": "Forge stays calm under a crowd: live countdown, graceful high-demand handling, one-tap model retry",
+ "summary": "Generating a 3D model now feels steadier when lots of people are forging at once. The progress meter shows a real \"~Ns left\" countdown instead of a static estimate, so you can see it moving. If the free engines are momentarily at capacity during a rush, you get a friendly \"high demand\" notice with a live retry countdown that re-arms itself the moment a slot frees up — your spot in line, not a dead-end error — and you can keep refining a model you already have while you wait. And if a finished model ever fails to paint because of a brief network blip, a new Retry button reloads it in place instead of forcing a download. Behind the scenes, generation success rate and latency are now tracked so we can catch slowdowns before they reach you.",
+ "tags": [
+ "improvement",
+ "fix"
+ ],
+ "link": "/forge"
+ },
{
"date": "2026-06-21",
"title": "Live market feed stays up through provider blips",
@@ -80,7 +100,7 @@
{
"date": "2026-06-21",
"title": "Forge scales further — duplicate generations collapse, free lane protected, prices shown up front",
- "summary": "More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. Finally, the 3D viewer shows a loading shimmer instead of a dark void while your model paints in.",
+ "summary": "More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. The engine picker also gained a small legend explaining the badges at a glance — which engines are free, which use your own key, and which are busy or unavailable. And the 3D viewer now shows a loading shimmer instead of a dark void while your model paints in.",
"tags": [
"improvement",
"infra"
diff --git a/data/walk-social.json b/data/walk-social.json
new file mode 100644
index 000000000..7bef37b15
--- /dev/null
+++ b/data/walk-social.json
@@ -0,0 +1,26 @@
+[
+ {
+ "author": "three.ws",
+ "handle": "@trythreews",
+ "avatar": "/three.svg",
+ "url": "https://x.com/trythreews",
+ "quote": "Your avatar now walks anywhere on the web. Drop it on any page with one tag, drive it with WASD or a joystick, and let it read articles aloud as it strolls.",
+ "platform": "x"
+ },
+ {
+ "author": "three.ws Walk",
+ "handle": "@trythreews",
+ "avatar": "/three.svg",
+ "url": "https://three.ws/walk-embed?env=void&autoplay=true&controls=none",
+ "quote": "Six built-in worlds, real-time animation retargeting onto any humanoid rig, and a postMessage API so your site can steer the avatar. No app install — it just runs in the browser.",
+ "platform": "x"
+ },
+ {
+ "author": "three.ws Extension",
+ "handle": "@trythreews",
+ "avatar": "/three.svg",
+ "url": "https://three.ws/extension",
+ "quote": "Install the Chrome extension and your avatar follows you across the entire web — walking over real pages, narrating what you read, a living 3D browsing companion.",
+ "platform": "x"
+ }
+]
diff --git a/public/changelog.json b/public/changelog.json
index b696a4e0d..6634fa2b4 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T06:14:10.120Z",
+ "generated_at": "2026-06-21T06:17:17.544Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -58,6 +58,17 @@
"infra"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Every Forge quality tier now runs on free engines",
+ "summary": "Forge's quality tiers — Draft, Standard, and High — all generate on zero-cost engines now: Draft and Standard on the fast free NVIDIA lane, and High on the higher-fidelity, fully textured free HuggingFace engine. Higher tiers buy you genuinely better geometry and textures, not a different bill behind the scenes. Photo-to-3D at any tier routes straight to a free engine too, so a generation never quietly falls back to a paid lane. The High tier stays a $THREE holder perk (or a one-off pay-per-use) — that's the price of premium quality, not a cost we're passing through.",
+ "link": "/forge",
+ "tags": [
+ "improvement",
+ "feature"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
@@ -73,13 +84,24 @@
"date": "2026-06-21",
"type": "update",
"title": "Forge scales further — duplicate generations collapse, free lane protected, prices shown up front",
- "summary": "More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. Finally, the 3D viewer shows a loading shimmer instead of a dark void while your model paints in.",
+ "summary": "More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. The engine picker also gained a small legend explaining the badges at a glance — which engines are free, which use your own key, and which are busy or unavailable. And the 3D viewer now shows a loading shimmer instead of a dark void while your model paints in.",
"link": "/forge",
"tags": [
"improvement",
"infra"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Forge stays calm under a crowd: live countdown, graceful high-demand handling, one-tap model retry",
+ "summary": "Generating a 3D model now feels steadier when lots of people are forging at once. The progress meter shows a real \"~Ns left\" countdown instead of a static estimate, so you can see it moving. If the free engines are momentarily at capacity during a rush, you get a friendly \"high demand\" notice with a live retry countdown that re-arms itself the moment a slot frees up — your spot in line, not a dead-end error — and you can keep refining a model you already have while you wait. And if a finished model ever fails to paint because of a brief network blip, a new Retry button reloads it in place instead of forcing a download. Behind the scenes, generation success rate and latency are now tracked so we can catch slowdowns before they reach you.",
+ "link": "/forge",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 1ee0b8474..0df6f4c28 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -46,6 +46,14 @@
<category>improvement</category>
<description>The Discover grid and the published-agents (Characters) feed now serve from the edge cache, so a surge of visitors is absorbed at the CDN instead of re-running a database scan on every request. Pages stay fast and consistent even during a rush, and a stale-while-revalidate window keeps them warm between refreshes.</description>
</item>
+ <item>
+ <title>Every Forge quality tier now runs on free engines</title>
+ <link>https://three.ws/forge</link>
+ <guid isPermaLink="false">2026-06-21:Every Forge quality tier now runs on free engines</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Forge's quality tiers — Draft, Standard, and High — all generate on zero-cost engines now: Draft and Standard on the fast free NVIDIA lane, and High on the higher-fidelity, fully textured free HuggingFace engine. Higher tiers buy you genuinely better geometry and textures, not a different bill behind the scenes. Photo-to-3D at any tier routes straight to a free engine too, so a generation never quietly falls back to a paid lane. The High tier stays a $THREE holder perk (or a one-off pay-per-use) — that's the price of premium quality, not a cost we're passing through.</description>
+ </item>
<item>
<title>Forge hardened for a traffic surge — faster loads, protected free lanes</title>
<link>https://three.ws/forge</link>
@@ -60,7 +68,15 @@
<guid isPermaLink="false">2026-06-21:Forge scales further — duplicate generations collapse, free lane protected, prices shown up front</guid>
<pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
<category>improvement</category>
- <description>More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. Finally, the 3D viewer shows a loading shimmer instead of a dark void while your model paints in.</description>
+ <description>More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. The engine picker also gained a small legend explaining the badges at a glance — which engines are free, which use your own key, and which are busy or unavailable. And the 3D viewer now shows a loading shimmer instead of a dark void while your model paints in.</description>
+ </item>
+ <item>
+ <title>Forge stays calm under a crowd: live countdown, graceful high-demand handling, one-tap model retry</title>
+ <link>https://three.ws/forge</link>
+ <guid isPermaLink="false">2026-06-21:Forge stays calm under a crowd: live countdown, graceful high-demand handling, one-tap model retry</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Generating a 3D model now feels steadier when lots of people are forging at once. The progress meter shows a real &quot;~Ns left&quot; countdown instead of a static estimate, so you can see it moving. If the free engines are momentarily at capacity during a rush, you get a friendly &quot;high demand&quot; notice with a live retry countdown that re-arms itself the moment a slot frees up — your spot in line, not a dead-end error — and you can keep refining a model you already have while you wait. And if a finished model ever fails to paint because of a brief network blip, a new Retry button reloads it in place instead of forcing a download. Behind the scenes, generation success rate and latency are now tracked so we can catch slowdowns before they reach you.</description>
</item>
<item>
<title>forge_avatar — one call turns a prompt into a rigged, animation-ready avatar</title>
diff --git a/public/features.json b/public/features.json
index d42006538..6b79036bf 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T06:14:09.858Z",
+ "generated_at": "2026-06-21T06:17:17.655Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/x402-pay-core.js b/public/x402-pay-core.js
index eb2c011f5..0b7c280b8 100644
--- a/public/x402-pay-core.js
+++ b/public/x402-pay-core.js
@@ -129,6 +129,128 @@ export function friendlyError(err) {
return msg.slice(0, 240);
}
+// ───────────────────────────────────────────── pre-flight balance guard ───────
+//
+// The balance check is a UX guard, NOT a security gate: it spares the buyer from
+// signing a transaction that can only fail at settle with an opaque error, and
+// lets the UI offer "add funds" instead. It is deliberately fail-open — when the
+// balance can't be read (flaky RPC, provider quirk) it returns null and the
+// payment proceeds exactly as before. Only a POSITIVE shortfall blocks signing.
+
+// Render an atomic token amount as a trimmed decimal string (BigInt-safe — token
+// amounts can exceed Number's safe integer range).
+export function formatTokenAmount(atomic, decimals = 6) {
+ const neg = BigInt(atomic) < 0n;
+ const abs = neg ? -BigInt(atomic) : BigInt(atomic);
+ const base = 10n ** BigInt(decimals);
+ const whole = abs / base;
+ const frac = (abs % base).toString().padStart(decimals, '0').replace(/0+$/, '');
+ return `${neg ? '-' : ''}${whole}${frac ? `.${frac}` : ''}`;
+}
+
+// Structured insufficient-funds error so the UI can render an actionable state
+// (required / current / shortfall + an add-funds CTA) instead of a raw string.
+export function insufficientFundsError({ required, balance, accept }) {
+ const decimals = Number(accept?.extra?.decimals ?? 6);
+ const symbol = accept?.extra?.name || 'USDC';
+ const req = BigInt(required);
+ const bal = BigInt(balance);
+ const shortfall = req > bal ? req - bal : 0n;
+ const err = new Error(
+ `Not enough ${symbol} — you need ${formatTokenAmount(req, decimals)} ${symbol} but your wallet holds ${formatTokenAmount(bal, decimals)} ${symbol}.`,
+ );
+ err.code = 'insufficient_funds';
+ err.insufficient = {
+ symbol,
+ decimals,
+ network: accept?.network || null,
+ asset: accept?.asset || null,
+ required: req.toString(),
+ requiredFormatted: formatTokenAmount(req, decimals),
+ balance: bal.toString(),
+ balanceFormatted: formatTokenAmount(bal, decimals),
+ shortfall: shortfall.toString(),
+ shortfallFormatted: formatTokenAmount(shortfall, decimals),
+ };
+ return err;
+}
+
+// RPC endpoint for the Solana balance read. Overridable via meta tag / global so
+// a deployment can point at its own (Helius) RPC instead of the rate-limited
+// public one; mirrors the WalletConnect project-id resolution.
+function solanaRpcUrl() {
+ if (typeof document !== 'undefined') {
+ const meta = document.querySelector('meta[name="solana-rpc-url"]');
+ if (meta?.content) return meta.content;
+ }
+ if (typeof window !== 'undefined' && window.SOLANA_RPC_URL) return window.SOLANA_RPC_URL;
+ return 'https://api.mainnet-beta.solana.com';
+}
+
+// Sum the owner's SPL balance for `mint`. Returns a BigInt of atomic units, or
+// null when the read fails (→ caller proceeds without blocking).
+export async function readSolanaTokenBalance({ owner, mint, rpcUrl }) {
+ try {
+ const res = await fetch(rpcUrl || solanaRpcUrl(), {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'getTokenAccountsByOwner',
+ params: [owner, { mint }, { encoding: 'jsonParsed' }],
+ }),
+ });
+ if (!res.ok) return null;
+ const data = await res.json();
+ const accounts = data?.result?.value || [];
+ let total = 0n;
+ for (const acc of accounts) {
+ const amt = acc?.account?.data?.parsed?.info?.tokenAmount?.amount;
+ if (amt != null) total += BigInt(amt);
+ }
+ return total;
+ } catch {
+ return null;
+ }
+}
+
+// ERC-20 balanceOf(owner) calldata: selector 0x70a08231 + 32-byte left-padded owner.
+export function erc20BalanceOfCalldata(owner) {
+ return '0x70a08231' + String(owner).toLowerCase().replace(/^0x/, '').padStart(64, '0');
+}
+
+// Read an ERC-20 balance via the connected wallet provider (it IS the RPC for the
+// current chain — no external endpoint needed). Returns a BigInt, or null on failure.
+export async function readEvmTokenBalance({ provider, token, owner }) {
+ try {
+ const hex = await provider.request({
+ method: 'eth_call',
+ params: [{ to: token, data: erc20BalanceOfCalldata(owner) }, 'latest'],
+ });
+ if (!hex || hex === '0x') return null;
+ return BigInt(hex);
+ } catch {
+ return null;
+ }
+}
+
+// Throw insufficientFundsError ONLY when a balance was positively read and falls
+// short of accept.amount. A null read (inconclusive) never blocks the payment.
+export async function assertSufficientBalance({ accept, owner, provider, rpcUrl }) {
+ const required = BigInt(accept.amount);
+ let balance = null;
+ if (isSolanaNetwork(accept.network)) {
+ balance = await readSolanaTokenBalance({ owner, mint: accept.asset, rpcUrl });
+ } else if (isEvmNetwork(accept.network) && provider) {
+ balance = await readEvmTokenBalance({ provider, token: accept.asset, owner });
+ }
+ if (balance !== null && balance < required) {
+ throw insufficientFundsError({ required, balance, accept });
+ }
+ return balance;
+}
+
// ──────────────────────────────────────────── payment payload builders ────────
// Body for POST /api/x402-checkout?action=prepare. The server returns a
@@ -409,6 +531,10 @@ export async function paySolana({ accept, resourceUrl, walletName, onStatus, ori
const payerAddress = (conn?.publicKey || provider.publicKey)?.toString();
if (!payerAddress) throw new Error(`${label} did not return a public key`);
+ // Pre-flight: don't make the buyer sign a doomed transaction (fail-open).
+ onStatus?.('building', 'Checking your balance…');
+ await assertSufficientBalance({ accept, owner: payerAddress });
+
onStatus?.('building', 'Building payment…');
const prep = await postJson(
`${apiOrigin}/api/x402-checkout?action=prepare`,
@@ -507,6 +633,10 @@ export async function payEvm({ accept, resourceUrl, walletName, onStatus }) {
}
}
+ // Pre-flight: catch an underfunded wallet before the signature prompt (fail-open).
+ onStatus?.('signing', 'Checking your balance…');
+ await assertSufficientBalance({ accept, owner: payerAddress, provider: eth });
+
onStatus?.('signing', `Authorize payment in ${label}…`);
const { typedData, authorization } = buildEip3009TypedData({
accept,
@@ -556,5 +686,10 @@ if (typeof window !== 'undefined') {
explorerUrl,
getSolanaProvider,
getEvmProvider,
+ assertSufficientBalance,
+ readSolanaTokenBalance,
+ readEvmTokenBalance,
+ insufficientFundsError,
+ formatTokenAmount,
});
}
diff --git a/public/x402.js b/public/x402.js
index 0f4609a35..1df9493b5 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -172,6 +172,77 @@ function formatAmount(rawAtomics, decimals = 6) {
return n.toFixed(2);
}
+// Block-explorer link for a wallet ADDRESS (not a tx) — used by the
+// insufficient-funds state so the buyer can inspect/top up their own wallet.
+function addressExplorerUrl(net, addr) {
+ if (!addr) return null;
+ if (isSolanaNetwork(net)) return `https://solscan.io/account/${addr}`;
+ const base = EVM_NETWORKS[net]?.explorer; // e.g. https://basescan.org/tx/
+ return base ? `${base.replace(/tx\/?$/, '')}address/${addr}` : null;
+}
+
+// ── Pre-flight balance guard (UX, not security) ──────────────────────────────
+// Spares the buyer from signing a transaction that can only fail at settle.
+// Fail-open: a balance that can't be read (flaky RPC / provider quirk) returns
+// null and the payment proceeds unchanged — only a POSITIVE shortfall blocks.
+function solanaRpcUrl() {
+ const meta = typeof document !== 'undefined' && document.querySelector('meta[name="solana-rpc-url"]');
+ if (meta?.content) return meta.content;
+ if (typeof window !== 'undefined' && window.SOLANA_RPC_URL) return window.SOLANA_RPC_URL;
+ return 'https://api.mainnet-beta.solana.com';
+}
+async function readSolanaBalanceAtomic(owner, mint) {
+ try {
+ const res = await fetch(solanaRpcUrl(), {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0', id: 1, method: 'getTokenAccountsByOwner',
+ params: [owner, { mint }, { encoding: 'jsonParsed' }],
+ }),
+ });
+ if (!res.ok) return null;
+ const data = await res.json();
+ let total = 0n;
+ for (const acc of data?.result?.value || []) {
+ const amt = acc?.account?.data?.parsed?.info?.tokenAmount?.amount;
+ if (amt != null) total += BigInt(amt);
+ }
+ return total;
+ } catch (_) { return null; }
+}
+async function readEvmBalanceAtomic(provider, token, owner) {
+ try {
+ const data = '0x70a08231' + String(owner).toLowerCase().replace(/^0x/, '').padStart(64, '0');
+ const hex = await provider.request({ method: 'eth_call', params: [{ to: token, data }, 'latest'] });
+ if (!hex || hex === '0x') return null;
+ return BigInt(hex);
+ } catch (_) { return null; }
+}
+// Throws a structured insufficient-funds error (code + .insufficient) when a
+// balance is positively read and short; resolves otherwise.
+async function assertBalance({ accept, owner, provider }) {
+ const required = BigInt(accept.amount);
+ let balance = null;
+ if (isSolanaNetwork(accept.network)) balance = await readSolanaBalanceAtomic(owner, accept.asset);
+ else if (provider) balance = await readEvmBalanceAtomic(provider, accept.asset, owner);
+ if (balance === null || balance >= required) return;
+ const decimals = Number(accept.extra?.decimals ?? 6);
+ const symbol = accept.extra?.name || 'USDC';
+ const shortfall = required - balance;
+ const err = new Error(
+ `Not enough ${symbol} — you need ${formatAmount(required, decimals)} ${symbol} but your wallet holds ${formatAmount(balance, decimals)} ${symbol}.`,
+ );
+ err.code = 'insufficient_funds';
+ err.insufficient = {
+ symbol, network: accept.network, owner,
+ required: formatAmount(required, decimals),
+ balance: formatAmount(balance, decimals),
+ shortfall: formatAmount(shortfall, decimals),
+ };
+ throw err;
+}
+
function b64encode(obj) {
const json = JSON.stringify(obj);
if (typeof Buffer !== 'undefined') return Buffer.from(json, 'utf8').toString('base64');
@@ -1091,6 +1162,8 @@ class CheckoutModal {
return;
}
this.spendReservation = capCheck.reservation || null;
+ this.renderProgress('authorize', { text: 'Checking your balance…' });
+ await assertBalance({ accept, owner: payerAddress });
this.renderProgress('authorize', { text: `Building Solana payment for ${payerAddress.slice(0, 6)}…${payerAddress.slice(-4)}` });
// Only attach the donation when the buyer actually saw and kept the
diff --git a/scripts/audit-image-loading.mjs b/scripts/audit-image-loading.mjs
new file mode 100644
index 000000000..9d28f0c41
--- /dev/null
+++ b/scripts/audit-image-loading.mjs
@@ -0,0 +1,67 @@
+#!/usr/bin/env node
+/**
+ * Image loading-attribute guard.
+ *
+ * Every JS-rendered <img> in src/ pulls a remote thumbnail / avatar / coin
+ * image into a list, grid, modal or sidebar — off-fold content that must defer
+ * its network fetch (`loading="lazy"`) and decode off the main thread
+ * (`decoding="async"`). A new component that ships an <img> without these
+ * silently regresses scroll performance as feeds grow. This guard keeps the
+ * codebase self-defending: it reports — and in --strict mode fails the build on
+ * — any src/ <img> missing `loading=`.
+ *
+ * Scope: src/ only. Static-HTML <img> tags are intentionally NOT covered — most
+ * are above-the-fold logos/wordmarks (the LCP image) where lazy-loading hurts.
+ *
+ * To fix offenders in bulk: `node scripts/codemod-lazy-images.mjs`.
+ *
+ * Usage:
+ * node scripts/audit-image-loading.mjs # report only (exit 0)
+ * node scripts/audit-image-loading.mjs --strict # exit 1 if any offender
+ */
+import { readFileSync, readdirSync } from 'node:fs';
+import { resolve, dirname, join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const SRC_DIR = resolve(root, 'src');
+const strict = process.argv.includes('--strict');
+
+// A real <img> tag: `<img` + whitespace + an attribute name. Excludes bare
+// `<img>` that appears as literal text inside code comments.
+const IMG_TAG = /<img(\s+[a-zA-Z][^>]*?)?>/g;
+const REAL_IMG = /<img(?=\s+[a-zA-Z])([^>]*?)>/g;
+
+function walk(dir) {
+ const out = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const p = join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...walk(p));
+ else if (entry.isFile() && p.endsWith('.js')) out.push(p);
+ }
+ return out;
+}
+
+const offenders = [];
+for (const file of walk(SRC_DIR)) {
+ const src = readFileSync(file, 'utf8');
+ let m;
+ REAL_IMG.lastIndex = 0;
+ while ((m = REAL_IMG.exec(src)) !== null) {
+ const attrs = m[1] || '';
+ if (!/\bloading=/.test(attrs)) {
+ const line = src.slice(0, m.index).split('\n').length;
+ offenders.push(`${relative(root, file)}:${line}`);
+ }
+ }
+}
+
+if (offenders.length === 0) {
+ console.log('✓ image-loading guard: every src/ <img> declares loading=');
+ process.exit(0);
+}
+
+console.error(`✗ image-loading guard: ${offenders.length} <img> tag(s) missing loading=`);
+for (const o of offenders) console.error(` ${o}`);
+console.error('\nFix with: node scripts/codemod-lazy-images.mjs');
+process.exit(strict ? 1 : 0);
diff --git a/scripts/probe-app-empty-state.mjs b/scripts/probe-app-empty-state.mjs
index 76fea9582..b677ab1b8 100644
--- a/scripts/probe-app-empty-state.mjs
+++ b/scripts/probe-app-empty-state.mjs
@@ -3,7 +3,15 @@
import { chromium } from 'playwright';
const URL = process.env.PROBE_URL || 'http://localhost:3000/app';
-const browser = await chromium.launch();
+const browser = await chromium.launch({
+ args: [
+ '--use-gl=angle',
+ '--use-angle=swiftshader',
+ '--enable-unsafe-swiftshader',
+ '--disable-gpu-sandbox',
+ '--no-sandbox',
+ ],
+});
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });
const page = await ctx.newPage();
@@ -37,6 +45,9 @@ const report = await page.evaluate(() => {
};
});
-await page.screenshot({ path: '/tmp/app-fresh-user.png', fullPage: false });
console.log(JSON.stringify({ report, errors: errors.slice(0, 20) }, null, 2));
+await page
+ .screenshot({ path: '/tmp/app-fresh-user.png', fullPage: false, timeout: 5000, animations: 'disabled' })
+ .then(() => console.log('screenshot: /tmp/app-fresh-user.png'))
+ .catch(() => console.log('screenshot: skipped (animating canvas)'));
await browser.close();
diff --git a/src/walk-companion-transitions.js b/src/walk-companion-transitions.js
new file mode 100644
index 000000000..f5bcff4e8
--- /dev/null
+++ b/src/walk-companion-transitions.js
@@ -0,0 +1,491 @@
+// Walk-aware page transitions for the corner companion.
+// =====================================================
+// When a visitor with the Walk Companion enabled clicks a same-origin link, the
+// jump to the next page is dressed up to *match the destination*: walking to
+// /walk zooms the camera into the avatar, /pricing pulls a curtain down, an
+// /agent/* profile spotlights open from the click point, /marketplace dives
+// through a depth corridor, /dashboard glows softly, and everything else gets a
+// clean fade-and-slide. The effect is intentionally short (≈0.5s) so it reads as
+// a flourish, never a wait.
+//
+// We can't co-render the destination DOM during a full-document navigation, so
+// each preset animates over a *themed cover layer* drawn on top of the current
+// page, then commits the navigation as the cover finishes. The signature stays
+// `(fromEl, toEl, avatarEl) => Promise<void>` per the spec:
+// - fromEl the outgoing page surface (a snapshot host pinned over the page)
+// - toEl the themed destination cover the preset reveals
+// - avatarEl the companion's host element (for camera-zoom-into-avatar)
+//
+// Everything uses the Web Animations API (element.animate) — no libraries. With
+// `prefers-reduced-motion: reduce`, or when the visitor switches the feature off
+// from the companion settings, every preset collapses to a plain fade.
+//
+// This module is owned by src/walk-companion.js, which calls installTransitions()
+// once the companion mounts. It is side-effect free on import.
+
+import { prefersReducedMotion } from '../walk-sdk/src/internal/storage.js';
+
+// ── Preference (persisted, mirrors the companion's localStorage convention) ────
+// The companion stores its flags under `walk:companion:*`; we slot in alongside.
+const PREF_KEY = 'walk:companion:transitions';
+
+export function transitionsEnabled() {
+ try {
+ // Default ON: absent key means the visitor never opted out.
+ return localStorage.getItem(PREF_KEY) !== '0';
+ } catch {
+ return true;
+ }
+}
+
+function setTransitionsEnabled(on) {
+ try {
+ localStorage.setItem(PREF_KEY, on ? '1' : '0');
+ } catch {
+ /* private mode / disabled storage — non-fatal */
+ }
+}
+
+// ── Motion tokens (kept in lockstep with public/tokens.css) ───────────────────
+const EASE_EMPHASIZED = 'cubic-bezier(0.22, 1, 0.36, 1)';
+const EASE_STANDARD = 'cubic-bezier(0.2, 0.8, 0.2, 1)';
+const EASE_OUT = 'cubic-bezier(0, 0, 0.2, 1)';
+const DUR = 480; // --duration-slow-ish; reads as a flourish, not a wait
+const FADE_DUR = 280;
+
+const Z = 2147483600; // above the companion host (2147483000)
+
+function reduced() {
+ return prefersReducedMotion();
+}
+
+// Promise wrapper around an Animation; resolves on finish *or* cancel so a
+// double-navigation never leaves a dangling promise.
+function done(anim) {
+ return new Promise((resolve) => {
+ if (!anim) return resolve();
+ const fin = () => resolve();
+ anim.addEventListener('finish', fin, { once: true });
+ anim.addEventListener('cancel', fin, { once: true });
+ });
+}
+
+// ── Layer construction ────────────────────────────────────────────────────────
+// A full-viewport fixed layer used as a transition surface. Pointer-events are
+// off so a stray click during the (very short) animation can't be hijacked.
+function makeLayer(extra) {
+ const el = document.createElement('div');
+ el.style.cssText =
+ `position:fixed;inset:0;z-index:${Z};pointer-events:none;` +
+ `transform:translateZ(0);will-change:transform,opacity,clip-path;` +
+ (extra || '');
+ return el;
+}
+
+// The themed "destination" cover. We pull the brand surface colours straight
+// from the live CSS custom properties so the cover matches the site's theme
+// (and flips automatically under [data-theme='light']).
+function destinationColor() {
+ try {
+ const cs = getComputedStyle(document.documentElement);
+ return cs.getPropertyValue('--bg-0').trim() || '#0a0a0a';
+ } catch {
+ return '#0a0a0a';
+ }
+}
+function accentColor() {
+ try {
+ const cs = getComputedStyle(document.documentElement);
+ return cs.getPropertyValue('--accent').trim() || '#ffffff';
+ } catch {
+ return '#ffffff';
+ }
+}
+
+// ── Presets ───────────────────────────────────────────────────────────────────
+// Each: (fromEl, toEl, avatarEl) => Promise<void>. Under reduced motion they all
+// route through `simpleFade`.
+
+async function simpleFade(_fromEl, toEl) {
+ toEl.style.background = destinationColor();
+ toEl.style.opacity = '0';
+ return done(
+ toEl.animate([{ opacity: 0 }, { opacity: 1 }], {
+ duration: reduced() ? 180 : FADE_DUR,
+ easing: EASE_OUT,
+ fill: 'forwards',
+ }),
+ );
+}
+
+// default → simple fade + slide (task 32's baseline flourish)
+async function fadeSlide(_fromEl, toEl) {
+ if (reduced()) return simpleFade(_fromEl, toEl);
+ toEl.style.background = destinationColor();
+ return done(
+ toEl.animate(
+ [
+ { opacity: 0, transform: 'translateY(14px)' },
+ { opacity: 1, transform: 'translateY(0)' },
+ ],
+ { duration: DUR, easing: EASE_EMPHASIZED, fill: 'forwards' },
+ ),
+ );
+}
+
+// /walk → camera-zoom-into-avatar: the avatar grows to fill the viewport, then
+// crossfades into the destination surface.
+async function cameraZoomIntoAvatar(fromEl, toEl, avatarEl) {
+ if (reduced() || !avatarEl) return simpleFade(fromEl, toEl);
+
+ toEl.style.background = destinationColor();
+ toEl.style.opacity = '0';
+
+ // Compute the scale that blows the avatar host up to cover the viewport.
+ let scale = 8;
+ let originX = 50;
+ let originY = 50;
+ try {
+ const r = avatarEl.getBoundingClientRect();
+ const cx = r.left + r.width / 2;
+ const cy = r.top + r.height * 0.42; // head/torso, not feet
+ originX = (cx / window.innerWidth) * 100;
+ originY = (cy / window.innerHeight) * 100;
+ scale = Math.ceil((Math.max(window.innerWidth, window.innerHeight) / Math.min(r.width, r.height)) * 1.4);
+ } catch {
+ /* use defaults */
+ }
+
+ const prevTransform = avatarEl.style.transform;
+ const prevOrigin = avatarEl.style.transformOrigin;
+ const prevZ = avatarEl.style.zIndex;
+ avatarEl.style.transformOrigin = `${originX}% ${originY}%`;
+ avatarEl.style.zIndex = String(Z + 1);
+
+ const grow = avatarEl.animate(
+ [
+ { transform: 'scale(1)', opacity: 1 },
+ { transform: `scale(${scale})`, opacity: 0.85, offset: 0.72 },
+ { transform: `scale(${scale})`, opacity: 0 },
+ ],
+ { duration: DUR + 120, easing: EASE_EMPHASIZED, fill: 'forwards' },
+ );
+
+ const reveal = toEl.animate(
+ [
+ { opacity: 0, offset: 0 },
+ { opacity: 0, offset: 0.55 },
+ { opacity: 1, offset: 1 },
+ ],
+ { duration: DUR + 120, easing: EASE_OUT, fill: 'forwards' },
+ );
+
+ await Promise.all([done(grow), done(reveal)]);
+ // Best-effort restore — the page is about to be replaced anyway.
+ avatarEl.style.transform = prevTransform;
+ avatarEl.style.transformOrigin = prevOrigin;
+ avatarEl.style.zIndex = prevZ;
+}
+
+// /pricing → curtain-pull from the top.
+async function curtainPull(fromEl, toEl) {
+ if (reduced()) return simpleFade(fromEl, toEl);
+ toEl.style.background = destinationColor();
+ toEl.style.borderBottom = `2px solid ${accentColor()}`;
+ toEl.style.opacity = '1';
+ return done(
+ toEl.animate(
+ [
+ { transform: 'translateY(-100%)' },
+ { transform: 'translateY(0)' },
+ ],
+ { duration: DUR, easing: EASE_EMPHASIZED, fill: 'forwards' },
+ ),
+ );
+}
+
+// /agent/* → spotlight expand from the click origin point.
+async function spotlightExpand(fromEl, toEl, _avatarEl, origin) {
+ if (reduced()) return simpleFade(fromEl, toEl);
+ toEl.style.background = destinationColor();
+ toEl.style.opacity = '1';
+ const x = origin ? origin.x : window.innerWidth / 2;
+ const y = origin ? origin.y : window.innerHeight / 2;
+ const r = Math.hypot(
+ Math.max(x, window.innerWidth - x),
+ Math.max(y, window.innerHeight - y),
+ );
+ return done(
+ toEl.animate(
+ [
+ { clipPath: `circle(0px at ${x}px ${y}px)` },
+ { clipPath: `circle(${Math.ceil(r)}px at ${x}px ${y}px)` },
+ ],
+ { duration: DUR, easing: EASE_EMPHASIZED, fill: 'forwards' },
+ ),
+ );
+}
+
+// /marketplace → corridor depth zoom: the outgoing page recedes into the
+// distance while the destination rushes forward.
+async function corridorDepthZoom(fromEl, toEl) {
+ if (reduced()) return simpleFade(fromEl, toEl);
+ toEl.style.background = destinationColor();
+ toEl.style.opacity = '0';
+
+ const recede = fromEl
+ ? fromEl.animate(
+ [
+ { transform: 'perspective(1200px) translateZ(0) scale(1)', opacity: 1 },
+ { transform: 'perspective(1200px) translateZ(-600px) scale(0.78)', opacity: 0 },
+ ],
+ { duration: DUR, easing: EASE_STANDARD, fill: 'forwards' },
+ )
+ : null;
+
+ const rush = toEl.animate(
+ [
+ { transform: 'perspective(1200px) translateZ(420px) scale(1.25)', opacity: 0, offset: 0 },
+ { transform: 'perspective(1200px) translateZ(0) scale(1)', opacity: 1, offset: 1 },
+ ],
+ { duration: DUR, easing: EASE_EMPHASIZED, fill: 'forwards' },
+ );
+
+ await Promise.all([done(recede), done(rush)]);
+}
+
+// /dashboard → softer fade with a subtle glow bloom.
+async function softGlowFade(fromEl, toEl) {
+ if (reduced()) return simpleFade(fromEl, toEl);
+ const accent = accentColor();
+ toEl.style.background =
+ `radial-gradient(120% 120% at 50% 30%, ${accent}14, transparent 60%), ${destinationColor()}`;
+ return done(
+ toEl.animate(
+ [
+ { opacity: 0, filter: 'brightness(1.6) blur(6px)' },
+ { opacity: 1, filter: 'brightness(1) blur(0px)' },
+ ],
+ { duration: DUR + 60, easing: EASE_OUT, fill: 'forwards' },
+ ),
+ );
+}
+
+// ── Route → preset registry ───────────────────────────────────────────────────
+// First matching pattern wins; `*` is a path-segment-spanning glob. The default
+// entry (pattern '*') always matches last.
+export const PRESETS = [
+ { pattern: '/walk', preset: cameraZoomIntoAvatar, name: 'camera-zoom-into-avatar' },
+ { pattern: '/pricing', preset: curtainPull, name: 'curtain-pull' },
+ { pattern: '/agent/*', preset: spotlightExpand, name: 'spotlight-expand' },
+ { pattern: '/marketplace', preset: corridorDepthZoom, name: 'corridor-depth-zoom' },
+ { pattern: '/dashboard', preset: softGlowFade, name: 'soft-glow-fade' },
+ { pattern: '*', preset: fadeSlide, name: 'fade-slide' },
+];
+
+// Glob match: '/agent/*' matches '/agent/abc' and '/agent/abc/x'; '/walk'
+// matches '/walk' and '/walk/anything'. '*' matches everything.
+function pathMatches(pattern, path) {
+ if (pattern === '*') return true;
+ if (pattern.endsWith('/*')) {
+ const base = pattern.slice(0, -2);
+ return path === base || path.startsWith(base + '/');
+ }
+ return path === pattern || path.startsWith(pattern + '/');
+}
+
+export function presetForPath(path) {
+ const clean = (path || '/').replace(/\/+$/, '') || '/';
+ for (const entry of PRESETS) {
+ if (pathMatches(entry.pattern, clean)) return entry;
+ }
+ return PRESETS[PRESETS.length - 1];
+}
+
+// ── Runner ────────────────────────────────────────────────────────────────────
+// Builds the from/to layers, runs the matched preset, then commits the
+// navigation. Resolves only after the navigation is committed (or immediately if
+// the destination ends up being the same path). The outgoing layer is left in
+// place so the freshly-revealed cover hides the old page until the unload paints.
+let _running = false;
+
+export async function runTransition(destUrl, origin, getAvatarEl) {
+ if (_running) return; // a second click during the flourish is ignored
+ _running = true;
+
+ const path = destUrl.pathname;
+ const { preset } = presetForPath(path);
+
+ // Outgoing surface: we don't clone the DOM (expensive + fragile); the live
+ // page *is* the from-surface, so fromEl is a transparent layer the depth-zoom
+ // preset can transform if it wants a recede effect. Presets that don't use it
+ // simply ignore it.
+ const fromEl = makeLayer('background:transparent;');
+ const toEl = makeLayer('opacity:0;');
+ document.body.appendChild(fromEl);
+ document.body.appendChild(toEl);
+
+ const avatarEl = (() => {
+ try {
+ return getAvatarEl?.() || null;
+ } catch {
+ return null;
+ }
+ })();
+
+ const cleanup = () => {
+ fromEl.remove();
+ toEl.remove();
+ _running = false;
+ };
+
+ try {
+ await preset(fromEl, toEl, avatarEl, origin);
+ } catch {
+ // Animation failure must never strand the visitor — fall through to nav.
+ cleanup();
+ window.location.href = destUrl.href;
+ return;
+ }
+
+ // Hold the cover in place and commit the navigation. We do NOT remove the
+ // layers here: the cover should mask the current page right up until the new
+ // document paints, which avoids a flash of the old page during unload.
+ window.location.href = destUrl.href;
+
+ // Safety valve: if the navigation is somehow cancelled (e.g. beforeunload
+ // prompt declined), tear the cover back down so the page stays usable.
+ setTimeout(() => {
+ if (document.visibilityState === 'visible') cleanup();
+ }, 2500);
+}
+
+// ── Link interception ─────────────────────────────────────────────────────────
+// Capture-phase, registered ahead of the SDK companion's own click handler so we
+// see the click first. The companion's handler still runs (it plays the wave and
+// sets the greet flag from task 32) — we only *defer* the actual navigation, we
+// never preventDefault its wave. We let the native link default happen too, so
+// non-companion navigation paths are untouched when transitions are off.
+
+function isEligibleLink(e) {
+ if (e.defaultPrevented || e.button !== 0) return null;
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return null;
+ const a = e.target.closest?.('a[href]');
+ if (!a) return null;
+ if (a.target && a.target !== '_self') return null;
+ if (a.hasAttribute('download')) return null;
+ if (a.dataset?.noTransition === '1') return null;
+ const href = a.getAttribute('href');
+ if (!href || href.startsWith('#')) return null;
+ let url;
+ try {
+ url = new URL(href, location.href);
+ } catch {
+ return null;
+ }
+ if (url.origin !== location.origin) return null;
+ const here = location.pathname.replace(/\/+$/, '') || '/';
+ const there = url.pathname.replace(/\/+$/, '') || '/';
+ if (there === here) return null; // same page — nothing to transition to
+ return url;
+}
+
+let _clickHandler = null;
+let _getAvatarEl = null;
+
+function onClickCapture(e) {
+ if (!transitionsEnabled()) return; // honour the toggle; native nav proceeds
+ // Note: reduced-motion is NOT a reason to skip — the preset itself degrades to
+ // a plain fade, which is still smoother than a hard cut.
+ const url = isEligibleLink(e);
+ if (!url) return;
+ // Take ownership of the navigation so we can play the themed cover first.
+ e.preventDefault();
+ runTransition(url, { x: e.clientX, y: e.clientY }, _getAvatarEl);
+}
+
+// ── Settings toggle (injected into the companion's own control cluster) ────────
+// The companion host carries a close (×) and swap (⇄) button in its top-right.
+// We add a matching pill that flips "Themed transitions" and persists it.
+function injectSettingsToggle(hostEl) {
+ if (!hostEl || hostEl.querySelector('.walk-companion-fx-toggle')) return;
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'walk-companion-swap walk-companion-fx-toggle';
+ btn.setAttribute('aria-label', 'Toggle themed page transitions');
+ btn.setAttribute('aria-pressed', transitionsEnabled() ? 'true' : 'false');
+ btn.title = transitionsEnabled() ? 'Themed transitions: on' : 'Themed transitions: off';
+ btn.textContent = '✦';
+
+ // Position it to the left of the existing swap/close buttons. The host already
+ // styles `.walk-companion-swap` at right:28px; nudge this one further left so
+ // the three controls sit in a neat row.
+ btn.style.right = '54px';
+ syncToggleVisual(btn);
+
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const next = !transitionsEnabled();
+ setTransitionsEnabled(next);
+ syncToggleVisual(btn);
+ });
+ hostEl.appendChild(btn);
+}
+
+function syncToggleVisual(btn) {
+ const on = transitionsEnabled();
+ btn.setAttribute('aria-pressed', on ? 'true' : 'false');
+ btn.title = on ? 'Themed transitions: on' : 'Themed transitions: off';
+ btn.style.opacity = ''; // let the host's hover/focus rules own visibility
+ btn.style.color = on ? '#fff' : 'rgba(255,255,255,.5)';
+ btn.style.background = on ? 'rgba(122,162,255,.35)' : 'rgba(12,14,20,.55)';
+}
+
+// ── Public install / uninstall ────────────────────────────────────────────────
+/**
+ * Wire themed page transitions to the companion.
+ * @param {object} opts
+ * @param {() => (HTMLElement|null)} opts.getAvatarEl returns the companion host
+ * element used by the camera-zoom-into-avatar preset.
+ * @param {() => (HTMLElement|null)} [opts.getHostEl] returns the companion host
+ * for injecting the settings toggle (defaults to getAvatarEl).
+ * @returns {() => void} uninstall function.
+ */
+export function installTransitions({ getAvatarEl, getHostEl } = {}) {
+ if (typeof document === 'undefined') return () => {};
+ _getAvatarEl = typeof getAvatarEl === 'function' ? getAvatarEl : () => null;
+
+ // Idempotent: a re-mount (playground return) shouldn't double-bind.
+ if (!_clickHandler) {
+ _clickHandler = onClickCapture;
+ // Capture phase so we run before the SDK companion's bubble/capture click
+ // listeners and before the link's default navigation.
+ document.addEventListener('click', _clickHandler, { capture: true });
+ }
+
+ // The host may not exist yet on the very first tick after mount; poll briefly.
+ const hostGetter = typeof getHostEl === 'function' ? getHostEl : _getAvatarEl;
+ let tries = 0;
+ const tryInject = () => {
+ const host = (() => {
+ try {
+ return hostGetter();
+ } catch {
+ return null;
+ }
+ })();
+ if (host) {
+ injectSettingsToggle(host);
+ return;
+ }
+ if (tries++ < 30) requestAnimationFrame(tryInject);
+ };
+ tryInject();
+
+ return function uninstall() {
+ if (_clickHandler) {
+ document.removeEventListener('click', _clickHandler, { capture: true });
+ _clickHandler = null;
+ }
+ };
+}
diff --git a/src/walk-companion.js b/src/walk-companion.js
index 016c3fc3e..a624b9434 100644
--- a/src/walk-companion.js
+++ b/src/walk-companion.js
@@ -13,6 +13,7 @@
// lazy import() chunk and isn't pulled in until the avatar detaches.
import { createWalkCompanion } from '../walk-sdk/src/companion.js';
+import { installTransitions } from './walk-companion-transitions.js';
const walk = createWalkCompanion({
// Static GLBs and the animation manifest are served from this origin.
@@ -27,4 +28,12 @@ const walk = createWalkCompanion({
// Walk button, react to ?walk= overrides). Keep the surface it relies on.
window.__walkCompanion = walk;
+// Walk-aware page transitions (task 33): dress the jump between pages to match
+// the destination. The runner needs the companion's host element — both for the
+// camera-zoom-into-avatar preset and for slotting the "Themed transitions"
+// settings pill into the companion's existing control cluster. We read it lazily
+// off the live instance so this survives avatar swaps and playground round-trips.
+const companionHost = () => walk.instance?.host || null;
+installTransitions({ getAvatarEl: companionHost, getHostEl: companionHost });
+
walk.bootstrap();
diff --git a/tests/api/forge-tiers.test.js b/tests/api/forge-tiers.test.js
index 8c5b15d8b..743e5ba36 100644
--- a/tests/api/forge-tiers.test.js
+++ b/tests/api/forge-tiers.test.js
@@ -88,6 +88,7 @@ describe('forge-tiers — NVIDIA NIM backend registration', () => {
it('surfaces the backend in the public catalog with honest estimates', () => {
process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.HF_TOKEN = 'hf_test';
const cat = buildCatalog();
const nv = cat.backends.find((b) => b.id === 'nvidia');
expect(nv).toBeTruthy();
@@ -97,10 +98,10 @@ describe('forge-tiers — NVIDIA NIM backend registration', () => {
const draftEst = nv.estimates.image.find((e) => e.tier === 'draft');
expect(draftEst.eta_seconds).toBeGreaterThan(0);
expect(draftEst.credits).toBeNull();
- // The tier-aware default map advertises the free lane for draft and standard.
+ // The tier-aware default map advertises a free engine for every tier.
expect(cat.default_backend_for_tier.draft.image).toBe('nvidia');
expect(cat.default_backend_for_tier.standard.image).toBe('nvidia');
- expect(cat.default_backend_for_tier.high.image).toBe('trellis');
+ expect(cat.default_backend_for_tier.high.image).toBe('huggingface');
});
// NVIDIA's hosted TRELLIS preview is text-only (rejects every user-image
@@ -138,9 +139,15 @@ describe('forge-tiers — NVIDIA NIM backend registration', () => {
// explicit opt-in (never the silent auto-default).
describe('forge-tiers — HuggingFace free image lane', () => {
const prev = process.env.HF_TOKEN;
+ const prevNv = process.env.NVIDIA_API_KEY;
+ beforeEach(() => {
+ delete process.env.NVIDIA_API_KEY;
+ });
afterEach(() => {
if (prev === undefined) delete process.env.HF_TOKEN;
else process.env.HF_TOKEN = prev;
+ if (prevNv === undefined) delete process.env.NVIDIA_API_KEY;
+ else process.env.NVIDIA_API_KEY = prevNv;
});
it('registers a free, platform-keyed image backend that accepts user photos', () => {
@@ -182,13 +189,24 @@ describe('forge-tiers — HuggingFace free image lane', () => {
).toBe('huggingface');
});
- // An explicit opt-in lane, not a silent default — the standing image default
- // stays trellis (which free-firsts to HF internally), so resolution without an
- // explicit pick never surprises a caller onto the HF Spaces lane.
- it('is never the auto-resolved default for the image path', () => {
+ // Free-for-us routing: the HF lane is the auto default for the cases NVIDIA's
+ // text-only preview can't serve — photo submissions at any tier, and the
+ // higher-quality High tier — so a free deployment never falls onto the paid
+ // Replicate lane for them.
+ it('becomes the auto default for photo submissions and the high tier when configured', () => {
+ process.env.HF_TOKEN = 'hf_test';
+ delete process.env.NVIDIA_API_KEY;
+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true })).toBe('huggingface');
+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true })).toBe('huggingface');
+ expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('huggingface');
+ expect(resolveBackendId({ path: 'image', tier: 'high', userImages: true })).toBe('huggingface');
+ });
+
+ it('falls back to the paid lane only when no free engine is configured', () => {
delete process.env.HF_TOKEN;
- expect(resolveBackendId({ path: 'image', tier: 'standard' })).not.toBe('huggingface');
- expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true })).not.toBe('huggingface');
+ delete process.env.NVIDIA_API_KEY;
+ expect(resolveBackendId({ path: 'image', tier: 'standard' })).toBe('trellis');
+ expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('trellis');
});
});
diff --git a/tests/forge-scale.test.js b/tests/forge-scale.test.js
index a8b10424b..7e449cdd6 100644
--- a/tests/forge-scale.test.js
+++ b/tests/forge-scale.test.js
@@ -6,6 +6,10 @@ import {
registerInFlight,
acquireBlockingSlot,
providerSubmitAllowed,
+ dailyPaidAllowed,
+ circuitState,
+ circuitRecordFailure,
+ circuitRecordSuccess,
SCALE_LIMITS,
} from '../api/_lib/forge-scale.js';
@@ -76,6 +80,34 @@ describe('fail-open behavior without Redis', () => {
it('providerSubmitAllowed allows', async () => {
expect(await providerSubmitAllowed('replicate', { limit: 1, windowS: 10 })).toBe(true);
});
+
+ it('dailyPaidAllowed allows and reports the limit', async () => {
+ const r = await dailyPaidAllowed('client-abc', { limit: 60 });
+ expect(r.ok).toBe(true);
+ expect(r.limit).toBe(60);
+ });
+
+ it('dailyPaidAllowed no-ops on an empty identity', async () => {
+ expect((await dailyPaidAllowed('', { limit: 60 })).ok).toBe(true);
+ });
+});
+
+describe('shared circuit breaker (in-memory fallback)', () => {
+ it('opens after the threshold and resets on success', async () => {
+ // Without Redis the breaker uses a per-instance map keyed by name — exercise
+ // the full open/close cycle on a name unique to this test.
+ const name = 'test-breaker';
+ expect((await circuitState(name)).open).toBe(false);
+ await circuitRecordFailure(name, { threshold: 3, baseMs: 60_000 });
+ await circuitRecordFailure(name, { threshold: 3, baseMs: 60_000 });
+ expect((await circuitState(name)).open).toBe(false); // 2 < threshold
+ await circuitRecordFailure(name, { threshold: 3, baseMs: 60_000 });
+ const open = await circuitState(name);
+ expect(open.open).toBe(true);
+ expect(open.failures).toBe(3);
+ await circuitRecordSuccess(name);
+ expect((await circuitState(name)).open).toBe(false);
+ });
});
describe('SCALE_LIMITS', () => {
diff --git a/x402-payment-modal/src/index.js b/x402-payment-modal/src/index.js
index 99d518f50..e145c1ff1 100644
--- a/x402-payment-modal/src/index.js
+++ b/x402-payment-modal/src/index.js
@@ -494,118 +494,218 @@ async function loadEvmChecksum() {
// ───────────────────────────────────────────────────────────────── styles ────
const STYLE_ID = 'x402-styles';
-const STYLES = `
-:root {
+// Full design-token surface. Hosts brand-match by setting any of these on
+// `.x402-overlay` (via configure({ cssVars }) or their own CSS) — no !important,
+// no specificity battles. Dark values are applied both by the OS preference and
+// by an explicit `.x402-theme-dark` class (configure({ theme })).
+const TOKENS_LIGHT = `
--x402-z: 2147483600;
+ --x402-font: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ --x402-mono: ui-monospace, "JetBrains Mono", "SF Mono", Menlo, monospace;
+ --x402-scrim: rgba(8, 10, 18, 0.55);
+ --x402-surface: #ffffff;
+ --x402-surface-2: #f7f8fa;
+ --x402-fg: #0f1116;
+ --x402-muted: #646b7a;
+ --x402-faint: #9aa1ad;
+ --x402-border: #ecedf1;
+ --x402-border-strong: #d8dce4;
+ --x402-accent: #635bff;
+ --x402-accent-hover: #524bdb;
+ --x402-accent-weak: #f2f1ff;
+ --x402-accent-fg: #ffffff;
+ --x402-success: #16a34a;
+ --x402-success-fg: #15803d;
+ --x402-success-bg: #f0fdf4;
+ --x402-success-border: #bbf7d0;
+ --x402-error: #dc2626;
+ --x402-error-fg: #b91c1c;
+ --x402-error-bg: #fef2f2;
+ --x402-error-border: #fecaca;
+ --x402-warn-fg: #b45309;
+ --x402-warn-bg: #fffbeb;
+ --x402-warn-border: #fde68a;
+ --x402-link: #524bdb;
+ --x402-radius: 18px;
+ --x402-radius-md: 12px;
+ --x402-radius-sm: 9px;
+ --x402-shadow: 0 24px 80px rgba(8, 10, 18, 0.28), 0 4px 16px rgba(8, 10, 18, 0.12);
+ --x402-btn-bg: #0f1116;
+ --x402-btn-fg: #ffffff;
+ --x402-btn-hover: #242833;
+ --x402-btn-shadow: 0 1px 2px rgba(8, 10, 18, 0.18), inset 0 1px 0 rgba(255, 255, 255, 0.12);
+`;
+const TOKENS_DARK = `
+ --x402-scrim: rgba(0, 0, 0, 0.62);
+ --x402-surface: #161616;
+ --x402-surface-2: #1d1d1d;
+ --x402-fg: #e6e8f0;
+ --x402-muted: #9aa1b4;
+ --x402-faint: #6b7088;
+ --x402-border: #2a2a2a;
+ --x402-border-strong: #3a3a40;
+ --x402-accent: #8b85ff;
+ --x402-accent-hover: #a29cff;
+ --x402-accent-weak: #1e1b3a;
+ --x402-accent-fg: #ffffff;
+ --x402-success: #22c55e;
+ --x402-success-fg: #4ade80;
+ --x402-success-bg: #0b1f17;
+ --x402-success-border: #14532d;
+ --x402-error: #ef4444;
+ --x402-error-fg: #fca5a5;
+ --x402-error-bg: #1f1416;
+ --x402-error-border: #7f1d1d;
+ --x402-warn-fg: #fcd34d;
+ --x402-warn-bg: #2a1d10;
+ --x402-warn-border: #78350f;
+ --x402-link: #a29cff;
+ --x402-shadow: 0 24px 80px rgba(0, 0, 0, 0.6);
+ --x402-btn-bg: #ffffff;
+ --x402-btn-fg: #0f1116;
+ --x402-btn-hover: #e7e9ee;
+ --x402-btn-shadow: 0 1px 2px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.5);
+`;
+
+const STYLES = `
+.x402-overlay { ${TOKENS_LIGHT} }
+.x402-overlay.x402-theme-dark { ${TOKENS_DARK} }
+@media (prefers-color-scheme: dark) {
+ .x402-overlay:not(.x402-theme-light) { ${TOKENS_DARK} }
}
.x402-overlay {
position: fixed; inset: 0;
- background: rgba(8, 10, 18, 0.55);
+ background: var(--x402-scrim);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
display: flex; align-items: center; justify-content: center;
z-index: var(--x402-z);
opacity: 0; transition: opacity 0.16s ease-out;
- font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ font-family: var(--x402-font);
-webkit-font-smoothing: antialiased;
- color: #0f0f0f;
+ color: var(--x402-fg);
}
.x402-overlay.x402-open { opacity: 1; }
.x402-overlay * { box-sizing: border-box; }
+.x402-overlay :focus-visible {
+ outline: 2px solid var(--x402-accent);
+ outline-offset: 2px;
+}
.x402-modal {
width: calc(100% - 32px); max-width: 420px;
- background: #ffffff;
- border-radius: 18px;
- box-shadow: 0 24px 80px rgba(8, 10, 18, 0.28), 0 4px 16px rgba(8, 10, 18, 0.12);
+ background: var(--x402-surface);
+ border-radius: var(--x402-radius);
+ box-shadow: var(--x402-shadow);
overflow: hidden;
transform: translateY(8px) scale(0.985);
- transition: transform 0.18s ease-out;
+ transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1);
display: flex; flex-direction: column;
max-height: calc(100dvh - 32px);
}
.x402-overlay.x402-open .x402-modal { transform: translateY(0) scale(1); }
.x402-head {
padding: 18px 20px 14px;
- border-bottom: 1px solid #eef0f4;
+ border-bottom: 1px solid var(--x402-border);
display: flex; align-items: center; gap: 12px;
}
-.x402-head .x402-merchant {
- flex: 1; min-width: 0;
-}
+.x402-head .x402-merchant { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; }
+.x402-head .x402-merchant-text { min-width: 0; }
+.x402-brand-logo { width: 30px; height: 30px; flex: 0 0 auto; border-radius: 8px; object-fit: cover; }
.x402-merchant .x402-name {
- font-size: 12px; color: #5a6378; font-weight: 600; letter-spacing: 0.02em; text-transform: uppercase;
+ font-size: 12px; color: var(--x402-muted); font-weight: 600; letter-spacing: 0.02em; text-transform: uppercase;
margin-bottom: 2px;
}
.x402-merchant .x402-action {
- font-size: 17px; font-weight: 700; color: #0f0f0f;
+ font-size: 17px; font-weight: 700; color: var(--x402-fg);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
letter-spacing: -0.01em;
}
.x402-close {
- width: 32px; height: 32px;
- border-radius: 8px; border: none; background: #f3f4f7;
- font-size: 16px; color: #5a6378; cursor: pointer;
+ width: 32px; height: 32px; flex: 0 0 auto;
+ border-radius: 8px; border: none; background: var(--x402-surface-2);
+ color: var(--x402-muted); cursor: pointer;
display: flex; align-items: center; justify-content: center;
- transition: background 0.12s;
+ transition: background 0.12s, color 0.12s;
}
-.x402-close:hover { background: #e7e9ee; color: #0f0f0f; }
+.x402-close:hover { background: var(--x402-border-strong); color: var(--x402-fg); }
+.x402-close svg { width: 14px; height: 14px; }
.x402-price-row {
padding: 18px 20px;
- display: flex; align-items: baseline; justify-content: space-between;
- background: linear-gradient(180deg, #fafbfc 0%, #ffffff 100%);
- border-bottom: 1px solid #eef0f4;
+ display: flex; align-items: baseline; justify-content: space-between; gap: 12px;
+ background: var(--x402-surface-2);
+ border-bottom: 1px solid var(--x402-border);
}
+.x402-price-main { min-width: 0; }
.x402-price {
- font-size: 32px; font-weight: 700; letter-spacing: -0.02em; color: #0f0f0f;
+ font-size: 32px; font-weight: 700; letter-spacing: -0.02em; color: var(--x402-fg);
font-variant-numeric: tabular-nums;
}
-.x402-price .x402-currency { font-size: 14px; color: #5a6378; font-weight: 600; margin-left: 6px; letter-spacing: 0; }
+.x402-price .x402-currency { font-size: 14px; color: var(--x402-muted); font-weight: 600; margin-left: 6px; letter-spacing: 0; }
+.x402-price-sub { font-size: 11px; color: var(--x402-muted); margin-top: 3px; font-weight: 500; }
.x402-network {
- font-size: 12px; color: #5a6378; font-weight: 500;
- background: #f3f4f7; padding: 5px 10px; border-radius: 99px;
+ font-size: 12px; color: var(--x402-muted); font-weight: 500; flex: 0 0 auto;
+ background: var(--x402-surface); border: 1px solid var(--x402-border);
+ padding: 5px 10px; border-radius: 99px;
display: inline-flex; align-items: center; gap: 6px;
}
.x402-network::before {
content: ''; width: 6px; height: 6px; border-radius: 50%;
- background: #22c55e;
+ background: var(--x402-success);
+ box-shadow: 0 0 0 0 var(--x402-success);
+ animation: x402-pulse 2s ease-out infinite;
+}
+@keyframes x402-pulse {
+ 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--x402-success) 55%, transparent); }
+ 70% { box-shadow: 0 0 0 5px transparent; }
+ 100% { box-shadow: 0 0 0 0 transparent; }
}
.x402-body {
- padding: 16px 20px 18px;
+ padding: 16px 20px max(18px, env(safe-area-inset-bottom));
flex: 1 1 auto; overflow-y: auto;
display: flex; flex-direction: column; gap: 10px;
}
+.x402-body > * { animation: x402-fade 0.16s ease-out both; }
+@keyframes x402-fade { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
.x402-step {
display: flex; gap: 12px; align-items: flex-start;
padding: 10px 0;
}
-.x402-step + .x402-step { border-top: 1px solid #f3f4f7; }
+.x402-step + .x402-step { border-top: 1px solid var(--x402-border); }
.x402-step-num {
width: 22px; height: 22px; flex: 0 0 auto;
- border-radius: 50%; border: 1.5px solid #d0d4dd; background: #fff;
- color: #5a6378;
+ border-radius: 50%; border: 1.5px solid var(--x402-border-strong); background: var(--x402-surface);
+ color: var(--x402-muted);
font-size: 11px; font-weight: 700;
display: flex; align-items: center; justify-content: center;
}
.x402-step.x402-active .x402-step-num {
- border-color: #0a84ff; background: #0a84ff; color: #fff;
+ border-color: var(--x402-accent); background: var(--x402-accent); color: var(--x402-accent-fg);
animation: x402-spin 1.2s linear infinite;
}
.x402-step.x402-done .x402-step-num {
- border-color: #22c55e; background: #22c55e; color: #fff;
+ border-color: var(--x402-success); background: var(--x402-success); color: #fff;
}
.x402-step.x402-error .x402-step-num {
- border-color: #ef4444; background: #ef4444; color: #fff;
+ border-color: var(--x402-error); background: var(--x402-error); color: #fff;
}
@keyframes x402-spin {
- from { box-shadow: 0 0 0 0 rgba(10, 132, 255, 0.4); }
- to { box-shadow: 0 0 0 8px rgba(10, 132, 255, 0); }
+ from { box-shadow: 0 0 0 0 color-mix(in srgb, var(--x402-accent) 40%, transparent); }
+ to { box-shadow: 0 0 0 8px transparent; }
}
.x402-step-body { flex: 1; min-width: 0; }
-.x402-step-label { font-size: 14px; font-weight: 600; color: #0f0f0f; line-height: 1.35; }
-.x402-step-meta { font-size: 12px; color: #5a6378; margin-top: 2px; font-feature-settings: 'tnum' 1; }
-.x402-step.x402-error .x402-step-meta { color: #ef4444; }
+.x402-step-label { font-size: 14px; font-weight: 600; color: var(--x402-fg); line-height: 1.35; }
+.x402-step-meta { font-size: 12px; color: var(--x402-muted); margin-top: 2px; font-feature-settings: 'tnum' 1; }
+.x402-step.x402-error .x402-step-meta { color: var(--x402-error-fg); }
+
+.x402-skeleton {
+ border-radius: 6px;
+ background: linear-gradient(100deg, var(--x402-surface-2) 30%, var(--x402-border) 50%, var(--x402-surface-2) 70%);
+ background-size: 200% 100%;
+ animation: x402-shimmer 1.3s ease-in-out infinite;
+}
+@keyframes x402-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
.x402-wallet-buttons {
display: flex; flex-direction: column; gap: 8px;
@@ -613,26 +713,30 @@ const STYLES = `
}
.x402-wallet-btn {
width: 100%; padding: 13px 14px;
- background: #ffffff; border: 1.5px solid #e2e5ec; border-radius: 11px;
- font-size: 14px; font-weight: 600; color: #0f0f0f;
+ background: var(--x402-surface); border: 1.5px solid var(--x402-border-strong); border-radius: 11px;
+ font-size: 14px; font-weight: 600; color: var(--x402-fg);
cursor: pointer; font-family: inherit;
display: flex; align-items: center; gap: 12px;
transition: border-color 0.12s, background 0.12s, transform 0.05s;
}
-.x402-wallet-btn:hover:not(:disabled) { border-color: #0a84ff; background: #f7faff; }
+.x402-wallet-btn:hover:not(:disabled) { border-color: var(--x402-accent); background: var(--x402-accent-weak); }
.x402-wallet-btn:active:not(:disabled) { transform: translateY(1px); }
.x402-wallet-btn:disabled { opacity: 0.45; cursor: not-allowed; }
.x402-wallet-icon {
width: 28px; height: 28px; flex: 0 0 auto;
border-radius: 7px;
display: flex; align-items: center; justify-content: center;
- font-size: 16px;
- background: #f3f4f7;
+ background: var(--x402-surface-2); overflow: hidden;
}
-.x402-wallet-icon.x402-phantom { background: linear-gradient(135deg, #ab9ff2, #534bb1); color: #fff; }
-.x402-wallet-icon.x402-metamask { background: linear-gradient(135deg, #f6851b, #e2761b); color: #fff; }
+.x402-wallet-icon svg, .x402-wallet-icon img { width: 18px; height: 18px; }
.x402-wallet-name { flex: 1; text-align: left; }
-.x402-wallet-meta { font-size: 11px; color: #8a90a8; font-weight: 500; }
+.x402-wallet-meta { font-size: 11px; color: var(--x402-muted); font-weight: 500; }
+.x402-wallet-install {
+ font-size: 12px; color: var(--x402-muted); line-height: 1.5; text-align: center;
+ padding: 4px 0 2px;
+}
+.x402-wallet-install a { color: var(--x402-link); text-decoration: none; font-weight: 600; }
+.x402-wallet-install a:hover { text-decoration: underline; }
.x402-token-row {
display: flex; gap: 8px; margin-bottom: 10px;
@@ -640,142 +744,148 @@ const STYLES = `
.x402-token-pill {
flex: 1; min-width: 0; cursor: pointer; font-family: inherit;
padding: 9px 12px; border-radius: 10px;
- background: #ffffff; border: 1.5px solid #e2e5ec;
+ background: var(--x402-surface); border: 1.5px solid var(--x402-border-strong);
display: flex; flex-direction: column; align-items: flex-start; gap: 2px;
- transition: border-color 0.12s, background 0.12s, transform 0.05s;
+ transition: border-color 0.12s, background 0.12s, transform 0.05s, box-shadow 0.12s;
}
-.x402-token-pill:hover { border-color: #c3c9d6; background: #f9fafc; }
+.x402-token-pill:hover { border-color: var(--x402-accent); background: var(--x402-accent-weak); }
.x402-token-pill:active { transform: translateY(1px); }
-.x402-token-pill.x402-on { border-color: #0f0f0f; background: #f7faff; }
-.x402-token-sym { font-size: 13px; font-weight: 700; color: #0f0f0f; letter-spacing: -0.005em; }
-.x402-token-amt { font-size: 11px; color: #8a90a8; font-weight: 600; font-variant-numeric: tabular-nums; }
+.x402-token-pill.x402-on {
+ border-color: var(--x402-accent); background: var(--x402-accent-weak);
+ box-shadow: inset 0 0 0 1px var(--x402-accent);
+}
+.x402-token-sym { font-size: 13px; font-weight: 700; color: var(--x402-fg); letter-spacing: -0.005em; }
+.x402-token-amt { font-size: 11px; color: var(--x402-muted); font-weight: 600; font-variant-numeric: tabular-nums; }
.x402-pay-btn {
width: 100%; padding: 14px 16px;
- background: #0f0f0f; color: #fff; border: none;
- border-radius: 12px;
+ background: var(--x402-btn-bg); color: var(--x402-btn-fg); border: none;
+ border-radius: var(--x402-radius-md);
font-size: 15px; font-weight: 700; font-family: inherit;
cursor: pointer; letter-spacing: -0.005em;
- transition: background 0.12s, transform 0.05s;
+ box-shadow: var(--x402-btn-shadow);
+ transition: background 0.12s, transform 0.1s, box-shadow 0.12s;
margin-top: 4px;
display: flex; align-items: center; justify-content: center; gap: 8px;
}
-.x402-pay-btn:hover:not(:disabled) { background: #1d1d1d; }
-.x402-pay-btn:active:not(:disabled) { transform: translateY(1px); }
-.x402-pay-btn:disabled { background: #c8ccd4; cursor: not-allowed; }
+.x402-pay-btn:hover:not(:disabled) { background: var(--x402-btn-hover); transform: translateY(-1px); }
+.x402-pay-btn:active:not(:disabled) { transform: translateY(0); }
+.x402-pay-btn:disabled { opacity: 0.5; cursor: not-allowed; box-shadow: none; }
.x402-pay-secondary {
width: 100%; padding: 12px 14px;
- background: #ffffff; color: #0f0f0f;
- border: 1.5px solid #e2e5ec; border-radius: 11px;
+ background: var(--x402-surface); color: var(--x402-fg);
+ border: 1.5px solid var(--x402-border-strong); border-radius: 11px;
font-size: 14px; font-weight: 600; font-family: inherit;
cursor: pointer; letter-spacing: -0.005em;
margin-top: 6px;
transition: border-color 0.12s, background 0.12s, transform 0.05s;
}
-.x402-pay-secondary:hover:not(:disabled) { border-color: #0a84ff; background: #f7faff; }
+.x402-pay-secondary:hover:not(:disabled) { border-color: var(--x402-accent); background: var(--x402-accent-weak); }
.x402-pay-secondary:active:not(:disabled) { transform: translateY(1px); }
+.x402-trust {
+ font-size: 11.5px; color: var(--x402-muted); text-align: center;
+ margin-top: 10px; line-height: 1.45;
+ display: flex; align-items: center; justify-content: center; gap: 6px;
+}
+.x402-trust svg { width: 12px; height: 12px; flex: 0 0 auto; color: var(--x402-success); }
+
.x402-siwx-hint {
- font-size: 11px; color: #5a6378; text-align: center;
+ font-size: 11px; color: var(--x402-muted); text-align: center;
margin-top: 8px; line-height: 1.4;
}
.x402-siwx-fallback {
- font-size: 12px; color: #b45309; line-height: 1.45;
+ font-size: 12px; color: var(--x402-warn-fg); line-height: 1.45;
padding: 8px 10px; border-radius: 8px;
- background: #fffbeb; border: 1px solid #fde68a;
+ background: var(--x402-warn-bg); border: 1px solid var(--x402-warn-border);
margin-bottom: 6px;
}
.x402-error-box {
padding: 12px 14px; border-radius: 10px;
- background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c;
- font-size: 13px; line-height: 1.45;
- font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+ background: var(--x402-error-bg); border: 1px solid var(--x402-error-border); color: var(--x402-error-fg);
+ font-size: 13.5px; line-height: 1.5;
word-break: break-word;
}
-.x402-error-box strong { font-weight: 700; }
+.x402-error-box .x402-error-title { font-weight: 700; margin-bottom: 2px; }
+.x402-error-box .x402-error-detail { opacity: 0.85; font-size: 12.5px; }
.x402-receipt {
- padding: 14px 16px; border-radius: 12px;
- background: linear-gradient(180deg, #f0fdf4 0%, #ffffff 100%);
- border: 1px solid #bbf7d0;
+ padding: 16px; border-radius: var(--x402-radius-md);
+ background: var(--x402-success-bg);
+ border: 1px solid var(--x402-success-border);
+ animation: x402-pop 0.34s cubic-bezier(0.16, 1, 0.3, 1) both;
+}
+@keyframes x402-pop { from { opacity: 0; transform: scale(0.94); } to { opacity: 1; transform: scale(1); } }
+.x402-receipt-check {
+ width: 40px; height: 40px; margin: 2px auto 10px;
+ border-radius: 50%; background: var(--x402-success);
+ display: flex; align-items: center; justify-content: center;
+ animation: x402-check-pop 0.4s cubic-bezier(0.16, 1, 0.3, 1) 0.08s both;
}
+.x402-receipt-check svg { width: 22px; height: 22px; color: #fff; }
+.x402-receipt-check svg path { stroke-dasharray: 24; stroke-dashoffset: 24; animation: x402-draw 0.4s ease-out 0.22s forwards; }
+@keyframes x402-check-pop { 0% { transform: scale(0); } 60% { transform: scale(1.12); } 100% { transform: scale(1); } }
+@keyframes x402-draw { to { stroke-dashoffset: 0; } }
.x402-receipt-title {
- font-size: 11px; font-weight: 700; color: #15803d;
- text-transform: uppercase; letter-spacing: 0.06em;
- margin-bottom: 8px;
- display: flex; align-items: center; gap: 6px;
+ font-size: 15px; font-weight: 700; color: var(--x402-fg);
+ text-align: center; margin-bottom: 10px; letter-spacing: -0.01em;
}
-.x402-receipt-title::before { content: '✓'; font-size: 14px; }
.x402-receipt-row {
display: flex; justify-content: space-between; gap: 12px;
- font-size: 12px; padding: 2px 0;
- font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+ font-size: 12px; padding: 3px 0;
+ font-family: var(--x402-mono);
}
-.x402-receipt-row .x402-k { color: #5a6378; }
-.x402-receipt-row .x402-v { color: #0f0f0f; text-align: right; word-break: break-all; }
-.x402-receipt-row a { color: #0a84ff; text-decoration: none; }
+.x402-receipt-row .x402-k { color: var(--x402-muted); }
+.x402-receipt-row .x402-v { color: var(--x402-fg); text-align: right; word-break: break-all; }
+.x402-receipt-row a { color: var(--x402-link); text-decoration: none; }
.x402-receipt-row a:hover { text-decoration: underline; }
.x402-result {
padding: 12px 14px; border-radius: 10px;
- background: #fafbfc; border: 1px solid #e2e5ec;
+ background: var(--x402-surface-2); border: 1px solid var(--x402-border);
max-height: 240px; overflow: auto;
- font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
- font-size: 12px; line-height: 1.5; color: #0f0f0f;
+ font-family: var(--x402-mono);
+ font-size: 12px; line-height: 1.5; color: var(--x402-fg);
white-space: pre-wrap; word-break: break-word;
}
+.x402-result.x402-prose { font-family: var(--x402-font); font-size: 13.5px; line-height: 1.55; }
.x402-foot {
- padding: 10px 20px 14px;
- border-top: 1px solid #eef0f4;
+ padding: 10px 20px max(14px, env(safe-area-inset-bottom));
+ border-top: 1px solid var(--x402-border);
display: flex; align-items: center; justify-content: space-between;
- font-size: 11px; color: #8a90a8;
+ font-size: 11px; color: var(--x402-muted);
}
-.x402-foot a { color: #5a6378; text-decoration: none; font-weight: 600; }
-.x402-foot a:hover { color: #0f0f0f; }
+.x402-foot a { color: var(--x402-muted); text-decoration: none; font-weight: 600; }
+.x402-foot a:hover { color: var(--x402-fg); }
.x402-foot .x402-secure { display: flex; align-items: center; gap: 5px; }
-.x402-foot .x402-secure::before { content: '🔒'; font-size: 10px; }
+.x402-foot .x402-secure svg { width: 11px; height: 11px; }
-@media (max-width: 480px) {
- .x402-modal { max-width: none; width: calc(100% - 16px); border-radius: 16px; }
- .x402-price { font-size: 26px; }
+.x402-sr-only {
+ position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
+ overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
}
-@media (prefers-color-scheme: dark) {
- .x402-overlay { color: #e6e8f0; }
- .x402-modal { background: #161616; box-shadow: 0 24px 80px rgba(0, 0, 0, 0.6); }
- .x402-head, .x402-price-row, .x402-foot { border-color: #272727; }
- .x402-step + .x402-step { border-top-color: #272727; }
- .x402-merchant .x402-name { color: #8a90a8; }
- .x402-merchant .x402-action, .x402-price, .x402-step-label { color: #e6e8f0; }
- .x402-step-meta { color: #8a90a8; }
- .x402-close { background: #222222; color: #8a90a8; }
- .x402-close:hover { background: #2e2e2e; color: #e6e8f0; }
- .x402-price-row { background: linear-gradient(180deg, #1d1d1d 0%, #161616 100%); }
- .x402-network { background: #222222; color: #b0b6cc; }
- .x402-wallet-btn { background: #1d1d1d; border-color: #2e2e2e; color: #e6e8f0; }
- .x402-wallet-btn:hover:not(:disabled) { background: #252525; border-color: #0a84ff; }
- .x402-wallet-icon { background: #2e2e2e; }
- .x402-wallet-meta { color: #6b7088; }
- .x402-pay-btn { background: #ffffff; color: #0f0f0f; }
- .x402-pay-btn:hover:not(:disabled) { background: #e7e9ee; }
- .x402-pay-btn:disabled { background: #2e2e2e; color: #5a6378; }
- .x402-pay-secondary { background: #1d1d1d; border-color: #2e2e2e; color: #e6e8f0; }
- .x402-pay-secondary:hover:not(:disabled) { background: #252525; border-color: #0a84ff; }
- .x402-siwx-hint { color: #8a90a8; }
- .x402-siwx-fallback { background: #2a1d10; border-color: #78350f; color: #fcd34d; }
- .x402-step-num { background: #161616; border-color: #2e2e2e; color: #8a90a8; }
- .x402-result { background: #1d1d1d; border-color: #2e2e2e; color: #e6e8f0; }
- .x402-receipt { background: linear-gradient(180deg, #0b1f17 0%, #161616 100%); border-color: #14532d; }
- .x402-receipt-title { color: #4ade80; }
- .x402-receipt-row .x402-k { color: #8a90a8; }
- .x402-receipt-row .x402-v { color: #e6e8f0; }
- .x402-receipt-row a { color: #60a5fa; }
- .x402-error-box { background: #1f1416; border-color: #7f1d1d; color: #fca5a5; }
- .x402-foot a { color: #b0b6cc; }
- .x402-foot a:hover { color: #ffffff; }
+@media (max-width: 520px) {
+ .x402-overlay { align-items: flex-end; }
+ .x402-modal {
+ max-width: none; width: 100%;
+ border-radius: var(--x402-radius) var(--x402-radius) 0 0;
+ max-height: 92dvh;
+ transform: translateY(100%);
+ }
+ .x402-overlay.x402-open .x402-modal { transform: translateY(0); }
+ .x402-price { font-size: 28px; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .x402-overlay, .x402-modal, .x402-body > *,
+ .x402-receipt, .x402-receipt-check, .x402-receipt-check svg path { animation: none !important; transition: none !important; }
+ .x402-step.x402-active .x402-step-num { animation: none; }
+ .x402-network::before { animation: none; }
+ .x402-receipt-check svg path { stroke-dashoffset: 0; }
}
`;