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(phase-1+3+4): native selfie reconstruction pipeline + Livepeer inference + skill royalty demo

oversteppingde949daf1a15
diff --git a/.env.example b/.env.example
index 2980e37df..fe9de65ea 100644
--- a/.env.example
+++ b/.env.example
@@ -98,14 +98,20 @@ AVATAR_REGEN_PROVIDER=none
# Replicate (when AVATAR_REGEN_PROVIDER=replicate). Get an API token at
# https://replicate.com/account/api-tokens. Each mode maps to a model version
# hash from replicate.com — pick a model that takes a GLB URL (or text prompt
-# for restyle) and returns a GLB asset.
+# for restyle, or image URL(s) for reconstruct) and returns a GLB asset.
#
-# Recommended starting points:
-# restyle → text-to-3D models like Hunyuan3D or Tripo (use their replicate page)
-# remesh → mesh-cleanup pipelines
-# retex → image-conditioned texturing models
-# rerig → RigNet / Mixamo-style auto-rig models
+# Recommended commercial-OK starting points (2026-05):
+# reconstruct → tencent/hunyuan-3d-3.1 (image-to-textured-GLB, ~30-60s, best quality/price)
+# OR camenduru/tripo-sr (cheaper fallback, ~$0.0023/run, no PBR textures)
+# restyle → tencent/hunyuan-3d-3.1 (same engine, text or image conditioning)
+# remesh → mesh-cleanup pipelines on replicate
+# retex → image-conditioned texturing models on replicate
+# rerig → VAST-AI-Research/UniRig (MIT, SIGGRAPH 2025 SOTA — deploy via cog from HF
+# weights until on Replicate, or proxy a dedicated GPU)
+#
+# Copy the version hash from each model's "Run with API" tab on replicate.com.
REPLICATE_API_TOKEN=
+REPLICATE_RECONSTRUCT_MODEL=
REPLICATE_RESTYLE_MODEL=
REPLICATE_REMESH_MODEL=
REPLICATE_RETEX_MODEL=
diff --git a/README.md b/README.md
index 2a9c1da70..2cb6e24e8 100644
--- a/README.md
+++ b/README.md
@@ -171,10 +171,10 @@ three.ws ships in four phases. Each phase closes a specific gap between the curr
| Phase | Theme | Status |
|---|---|---|
| **0** | Platform foundations (viewer, runtime, ERC-8004, embed layer) | ✅ Shipped |
-| **1** | Selfie → Avatar engine (3-photo capture, hosted inference) | 🟡 In progress |
-| **2** | Agent personalization + voice cloning | ⏳ Next |
-| **3** | Onchain economy (agent tokens, reputation markets, royalties) | ⏳ Next |
-| **4** | Open inference network (decentralized GPU layer) | 🔮 Future |
+| **1** | Selfie → Avatar engine (3-photo capture, hosted inference) | 🟡 In progress — capture UX + quality gates shipped; GPU reconstruction backend wiring |
+| **2** | Agent personalization + voice cloning | 🟡 In progress — voice clone, persona, memory seeds shipped behind `/demos`; main-flow integration next |
+| **3** | Onchain economy (agent tokens, reputation markets, royalties) | 🟡 Scaffolding — bonding-curve sim, EAS-reputation viewer, 0xsplits + EAS SDKs landed; contracts + audits next |
+| **4** | Open inference network (decentralized GPU layer) | 🔮 Future — livepeer dep landed for early experimentation |
---
diff --git a/api/_lib/bake.js b/api/_lib/bake.js
index 01cce66a0..1ba98c5b2 100644
--- a/api/_lib/bake.js
+++ b/api/_lib/bake.js
@@ -25,7 +25,7 @@ import {
meshopt,
textureCompress,
} from '@gltf-transform/functions';
-import { MeshoptEncoder } from 'meshoptimizer';
+import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
import sharp from 'sharp';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
@@ -66,7 +66,18 @@ export function isBakeable(appearance) {
* @returns {Promise<Uint8Array>}
*/
export async function bakeAppearance(baseGlbBytes, appearance) {
- const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ // `meshopt({ encoder })` configures the EXT_meshopt_compression extension on
+ // the document, but the writer also needs the encoder when serializing the
+ // compressed buffers, and the reader needs the decoder when re-baking a
+ // previously-baked GLB that already carries meshopt-compressed buffers.
+ // Register both as io-level dependencies.
+ await Promise.all([MeshoptEncoder.ready, MeshoptDecoder.ready]);
+ const io = new NodeIO()
+ .registerExtensions(ALL_EXTENSIONS)
+ .registerDependencies({
+ 'meshopt.encoder': MeshoptEncoder,
+ 'meshopt.decoder': MeshoptDecoder,
+ });
const doc = await io.readBinary(toUint8(baseGlbBytes));
const presets = await loadPresets();
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 12031e173..ade027c5b 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -339,6 +339,14 @@ export const env = {
return opt('X_OAUTH_CLIENT_SECRET');
},
+ // Livepeer AI Gateway — optional. When set, /api/inference/livepeer routes
+ // to https://livepeer.studio/api/generate/llm with bearer auth (higher quota).
+ // When unset, the demo falls back to the public dream gateway at
+ // https://dream-gateway.livepeer.cloud/llm (no key, rate-limited).
+ get LIVEPEER_API_KEY() {
+ return opt('LIVEPEER_API_KEY');
+ },
+
// Dev.to syndication — required for the news admin's "Publish to Dev.to"
// hook to do anything. Generate at https://dev.to/settings/extensions
// (look for "Generate API Key"). When unset, syndication is skipped
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index 3514e94cd..e25e93acc 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -73,7 +73,7 @@ export const createAvatarBody = z.object({
description: z.string().trim().max(2000).optional(),
visibility: avatarVisibility.default('public'),
tags: z.array(z.string().trim().min(1).max(40)).max(20).default([]),
- source: z.enum(['upload', 'avaturn', 'readyplayer', 'import', 'direct-upload']).default('upload'),
+ source: z.enum(['upload', 'avaturn', 'readyplayer', 'import', 'direct-upload', 'reconstruct']).default('upload'),
parent_avatar_id: z.string().uuid().optional(),
source_meta: z.record(z.any()).default({}),
content_type: avatarContentType.default('model/gltf-binary'),
diff --git a/api/_providers/replicate.js b/api/_providers/replicate.js
index d9cc5c2d1..2b812ae34 100644
--- a/api/_providers/replicate.js
+++ b/api/_providers/replicate.js
@@ -8,11 +8,25 @@
// returns a regenerated GLB asset. The choice of model is configurable via
// env so the provider can be tuned without code changes:
//
-// REPLICATE_API_TOKEN — required, from replicate.com/account
-// REPLICATE_RESTYLE_MODEL — version hash for text-to-3D (Hunyuan3D, Tripo, etc.)
-// REPLICATE_REMESH_MODEL — version hash for mesh cleanup
-// REPLICATE_RETEX_MODEL — version hash for re-texturing
-// REPLICATE_RERIG_MODEL — version hash for rig regeneration
+// REPLICATE_API_TOKEN — required, from replicate.com/account
+// REPLICATE_RECONSTRUCT_MODEL — version hash for image-to-3D (Phase 1 selfie pipeline)
+// REPLICATE_RESTYLE_MODEL — version hash for text-to-3D / style transfer
+// REPLICATE_REMESH_MODEL — version hash for mesh cleanup
+// REPLICATE_RETEX_MODEL — version hash for re-texturing
+// REPLICATE_RERIG_MODEL — version hash for rig regeneration (skeleton + skinning)
+//
+// ── Recommended commercial-OK models (2026-05) ──────────────────────────────
+// Set REPLICATE_RECONSTRUCT_MODEL and REPLICATE_RESTYLE_MODEL to the version
+// hash of `tencent/hunyuan-3d-3.1` (visit replicate.com/tencent/hunyuan-3d-3.1
+// and copy the latest version id). Commercially licensed, image-to-textured-GLB
+// in ~30-60s, best quality/price as of writing.
+//
+// For REPLICATE_RERIG_MODEL, deploy VAST-AI-Research/UniRig (MIT, SIGGRAPH 2025
+// SOTA auto-rigging, weights on Hugging Face) via cog when it lands on
+// Replicate, or run it on a dedicated GPU and proxy through the same protocol.
+//
+// Cheaper TripoSR fallback for reconstruct mode: `camenduru/tripo-sr` (~$0.0023
+// per run, single-image, faster but no PBR textures).
//
// At submit time the provider POSTs to the Replicate predictions API. The
// returned prediction id is stored as `ext_job_id`. The status endpoint
@@ -27,6 +41,7 @@ function readEnv(name) {
}
const MODE_TO_ENV = Object.freeze({
+ reconstruct: 'REPLICATE_RECONSTRUCT_MODEL',
restyle: 'REPLICATE_RESTYLE_MODEL',
remesh: 'REPLICATE_REMESH_MODEL',
retex: 'REPLICATE_RETEX_MODEL',
@@ -39,11 +54,26 @@ function modelForMode(mode) {
return readEnv(envName);
}
-// Map our 4 modes onto the input shape each model expects. The exact shape
-// depends on the model; we default to a generic { source_url, prompt, mode }
-// payload and let provider-side models pick the fields they care about.
-// Caller-supplied params override the default shape.
+// Map our 5 modes onto the input shape each model expects. The exact shape
+// depends on the model; we default to a generic payload and let provider-side
+// models pick the fields they care about. Caller-supplied params always win.
+//
+// For `reconstruct` (image-to-3D, no source GLB) we feed `image` from the
+// caller's first photo and pass the full list through as `images` for models
+// that accept multi-view. This matches the input contracts of the Hunyuan3D
+// family and TripoSR — both ignore unrecognized fields.
function buildInput({ mode, sourceUrl, params }) {
+ if (mode === 'reconstruct') {
+ const photos = Array.isArray(params?.images) ? params.images : [];
+ const primary = photos[0] || params?.image || sourceUrl;
+ const base = {
+ mode,
+ image: primary,
+ images: photos.length ? photos : undefined,
+ prompt: typeof params?.prompt === 'string' ? params.prompt : undefined,
+ };
+ return { ...base, ...(params || {}) };
+ }
const base = {
mode,
source_url: sourceUrl,
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index e7b5177c5..9ba0520dd 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -2,7 +2,7 @@
// presign, public, regenerate, regenerate-status
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
-import { presignUpload, headObject, r2, publicUrl } from '../_lib/r2.js';
+import { presignUpload, headObject, r2, publicUrl, putObject } from '../_lib/r2.js';
import { storageKeyFor, enforceQuotas, searchPublicAvatars, stripOwnerFor } from '../_lib/avatars.js';
import { listAvatars, createAvatar } from '../_lib/avatars.js';
import { HeadObjectCommand } from '@aws-sdk/client-s3';
@@ -98,7 +98,7 @@ const handlePublic = wrap(async (req, res) => {
const regenerateSchema = z.object({
sourceAvatarId: z.string().trim().min(1).max(100),
- mode: z.enum(['remesh', 'retex', 'rerig', 'restyle']),
+ mode: z.enum(['remesh', 'retex', 'rerig', 'restyle', 'reconstruct']),
params: z.record(z.unknown()).optional(),
});
@@ -199,7 +199,8 @@ const handleRegenerateStatus = wrap(async (req, res) => {
const jobId = url.searchParams.get('jobId');
if (!jobId) return error(res, 400, 'invalid_request', 'jobId required');
const rows = await sql`
- select job_id, status, result_avatar_id, result_glb_url, error, provider, ext_job_id, created_at
+ select job_id, status, result_avatar_id, result_glb_url, error, provider, ext_job_id, created_at,
+ mode, params, source_avatar_id
from avatar_regen_jobs
where job_id = ${jobId} and user_id = ${userId}
limit 1
@@ -246,6 +247,61 @@ const handleRegenerateStatus = wrap(async (req, res) => {
}
}
+ // Materialize the avatar row when a reconstruct job finishes successfully
+ // but hasn't yet been materialized. We copy the result GLB from the
+ // provider's URL into our R2 bucket so the avatar is durable, then create
+ // the avatars row with the user-supplied name/description.
+ if (
+ job.status === 'done' &&
+ job.mode === 'reconstruct' &&
+ !job.result_avatar_id &&
+ !job.source_avatar_id &&
+ job.result_glb_url
+ ) {
+ try {
+ const params = job.params || {};
+ const name = (params.name || 'My selfie avatar').toString().slice(0, 120);
+ const description = params.description ? String(params.description).slice(0, 500) : null;
+ const visibility = ['private', 'unlisted', 'public'].includes(params.visibility) ? params.visibility : 'private';
+ const glbResp = await fetch(job.result_glb_url);
+ if (!glbResp.ok) throw new Error(`fetch result_glb_url: ${glbResp.status}`);
+ const glbBuf = Buffer.from(await glbResp.arrayBuffer());
+ const slug = `selfie-${Math.random().toString(36).slice(2, 8)}`;
+ const key = storageKeyFor({ userId, slug });
+ await putObject({
+ key,
+ body: glbBuf,
+ contentType: 'model/gltf-binary',
+ metadata: { source: 'reconstruct', job_id: jobId },
+ });
+ const avatar = await createAvatar({
+ userId,
+ storageKey: key,
+ input: {
+ slug,
+ name,
+ description,
+ size_bytes: glbBuf.length,
+ content_type: 'model/gltf-binary',
+ source: 'reconstruct',
+ source_meta: { jobId, provider: job.provider, replicateGlb: job.result_glb_url },
+ visibility,
+ tags: ['selfie'],
+ checksum_sha256: null,
+ parent_avatar_id: null,
+ },
+ });
+ await sql`
+ update avatar_regen_jobs
+ set result_avatar_id = ${avatar.id}, updated_at = now()
+ where job_id = ${jobId} and user_id = ${userId}
+ `;
+ job = { ...job, result_avatar_id: avatar.id };
+ } catch (err) {
+ job = { ...job, error: job.error || `materialize failed: ${err?.message}` };
+ }
+ }
+
const response = { ok: true, jobId: job.job_id, status: job.status };
if (job.result_avatar_id) response.resultAvatarId = job.result_avatar_id;
if (job.result_glb_url) response.resultGlbUrl = job.result_glb_url;
@@ -472,6 +528,95 @@ const handleAutoTag = wrap(async (req, res) => {
return json(res, 200, { ok: true, tags: newTags, description: desc });
});
+// ── reconstruct (Phase 1 — Selfie → Avatar engine) ────────────────────────────
+// Submits a Replicate reconstruct job from selfie photos. No source avatar
+// exists yet; the avatar row is materialized when the status handler observes
+// a successful result and copies the generated GLB into R2.
+
+// Photos may be either:
+// • http(s):// URL — typically an R2 object URL the client uploaded first
+// • data:image/...;base64,... — inline base64 (Replicate accepts these natively)
+const photoUrlOrDataUri = z
+ .string()
+ .max(8 * 1024 * 1024) // generous cap to allow inline JPEGs up to ~6 MB pre-base64
+ .refine(
+ (v) =>
+ /^https?:\/\//i.test(v) ||
+ /^data:image\/(png|jpe?g|webp|heic|heif);base64,/i.test(v),
+ 'must be an http(s) URL or a data:image/* base64 URI',
+ );
+
+const reconstructSchema = z.object({
+ name: z.string().trim().min(1).max(120),
+ description: z.string().trim().max(500).optional(),
+ photos: z.array(photoUrlOrDataUri).min(1).max(6),
+ visibility: z.enum(['private', 'unlisted', 'public']).optional(),
+ params: z.record(z.unknown()).optional(),
+});
+
+const handleReconstruct = wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const userId = await resolveRegenUser(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');
+ const rl = await limits.upload(userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+ const body = parse(reconstructSchema, await readJson(req));
+
+ let provider;
+ try {
+ provider = await getRegenProvider();
+ } catch (err) {
+ return error(res, err.status || 501, err.code || 'regen_provider_error', err.message);
+ }
+ if (provider.name === 'none') {
+ return error(
+ res,
+ 501,
+ 'regen_unconfigured',
+ 'Avatar reconstruction is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var.',
+ );
+ }
+
+ let submission;
+ try {
+ submission = await provider.instance.submit({
+ userId,
+ mode: 'reconstruct',
+ params: { ...(body.params ?? {}), images: body.photos, name: body.name },
+ sourceUrl: body.photos[0],
+ });
+ } catch (err) {
+ return error(
+ res,
+ err.status || 502,
+ err.code || 'regen_provider_error',
+ err.message || 'provider rejected submission',
+ );
+ }
+
+ const jobId = `${provider.name}-${randomUUID()}`;
+ const params = {
+ images: body.photos,
+ name: body.name,
+ description: body.description ?? null,
+ visibility: body.visibility ?? 'private',
+ };
+ await sql`
+ insert into avatar_regen_jobs
+ (job_id, user_id, source_avatar_id, mode, params, status, provider, ext_job_id, created_at, updated_at)
+ values
+ (${jobId}, ${userId}, ${null}, ${'reconstruct'}, ${JSON.stringify(params)}, 'queued', ${provider.name}, ${submission.extJobId ?? null}, now(), now())
+ `;
+ return json(res, 202, {
+ ok: true,
+ jobId,
+ status: 'queued',
+ eta: submission.eta ?? null,
+ provider: provider.name,
+ });
+});
+
// ── dispatcher ────────────────────────────────────────────────────────────────
const DISPATCH = {
@@ -481,6 +626,7 @@ const DISPATCH = {
'presign-halfbody': handlePresignHalfbody,
'auto-tag': handleAutoTag,
public: handlePublic,
+ reconstruct: handleReconstruct,
regenerate: handleRegenerate,
'regenerate-status': handleRegenerateStatus,
};
diff --git a/api/inference/livepeer.js b/api/inference/livepeer.js
new file mode 100644
index 000000000..bdb1b6155
--- /dev/null
+++ b/api/inference/livepeer.js
@@ -0,0 +1,288 @@
+// POST /api/inference/livepeer — side-by-side LLM inference comparison.
+//
+// Body: { prompt: string, model?: string, max_tokens?: number, temperature?: number }
+// Response:
+// {
+// ok: true,
+// prompt: string,
+// claude: { ok, reply, latency_ms, model, prompt_tokens, completion_tokens, network: 'Anthropic' },
+// livepeer: { ok, reply, latency_ms, model, prompt_tokens, completion_tokens, gateway: 'studio'|'public', network: 'Livepeer' }
+// }
+//
+// Both providers are called in parallel via Promise.allSettled so a slow
+// or failed Livepeer orchestrator does not block the Claude reply. The
+// Livepeer leg routes to:
+// - https://livepeer.studio/api/generate/llm when LIVEPEER_API_KEY is set
+// - https://dream-gateway.livepeer.cloud/llm otherwise (public, rate-limited)
+//
+// We `import 'livepeer'` so the package version is tied to the call shape —
+// the npm SDK is built for the same Studio API path we hit by raw fetch. The
+// actual request is plain HTTP because the Vercel edge-friendlier path is
+// `fetch`, not a heavyweight SDK client.
+
+// eslint-disable-next-line no-unused-vars -- pinned for version parity with the SDK call shape
+import { Livepeer } from 'livepeer';
+import { env } from '../_lib/env.js';
+import { cors, method, readJson, error, json, wrap } from '../_lib/http.js';
+
+export const maxDuration = 60;
+
+const DEFAULT_LIVEPEER_MODEL = 'meta-llama/Meta-Llama-3.1-8B-Instruct';
+const CLAUDE_MODEL = 'claude-haiku-4-5-20251001';
+
+// Models known to be available on the Livepeer public/studio gateway as of
+// late 2025. Surfaced to the client via the GET handler so the demo's
+// settings drawer renders the live list without hard-coding it in HTML.
+const LIVEPEER_MODELS = [
+ 'meta-llama/Meta-Llama-3.1-8B-Instruct',
+ 'mistralai/Mistral-Nemo-Instruct-2407',
+ 'Qwen/Qwen2.5-7B-Instruct',
+];
+
+function clampPrompt(p) {
+ if (typeof p !== 'string') return '';
+ return p.trim().slice(0, 8000);
+}
+
+function clampInt(n, lo, hi, fallback) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return fallback;
+ return Math.min(Math.max(Math.round(v), lo), hi);
+}
+
+function clampTemp(n, fallback = 0.7) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return fallback;
+ return Math.min(Math.max(v, 0), 2);
+}
+
+// ── Claude leg ────────────────────────────────────────────────────────────────
+
+async function callClaude({ prompt, max_tokens, temperature }) {
+ const key = env.ANTHROPIC_API_KEY; // throws if unset — caller wraps
+ const t0 = Date.now();
+ const upstream = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': key,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify({
+ model: CLAUDE_MODEL,
+ max_tokens,
+ temperature,
+ messages: [{ role: 'user', content: prompt }],
+ }),
+ });
+ const latency_ms = Date.now() - t0;
+
+ if (!upstream.ok) {
+ const body = await upstream.text().catch(() => '');
+ return {
+ ok: false,
+ network: 'Anthropic',
+ model: CLAUDE_MODEL,
+ latency_ms,
+ error: 'upstream_error',
+ upstream_status: upstream.status,
+ upstream_body: body.slice(0, 1000),
+ };
+ }
+
+ const data = await upstream.json();
+ const reply = (data.content || []).map((c) => c?.text || '').join('').trim();
+ return {
+ ok: true,
+ network: 'Anthropic',
+ model: CLAUDE_MODEL,
+ latency_ms,
+ reply,
+ prompt_tokens: data?.usage?.input_tokens ?? null,
+ completion_tokens: data?.usage?.output_tokens ?? null,
+ stop_reason: data?.stop_reason ?? null,
+ };
+}
+
+// ── Livepeer leg ──────────────────────────────────────────────────────────────
+
+async function callLivepeer({ prompt, model, max_tokens, temperature }) {
+ const useStudio = Boolean(env.LIVEPEER_API_KEY);
+ const url = useStudio
+ ? 'https://livepeer.studio/api/generate/llm'
+ : 'https://dream-gateway.livepeer.cloud/llm';
+ const gateway = useStudio ? 'studio' : 'public';
+
+ const headers = { 'content-type': 'application/json' };
+ if (useStudio) headers.authorization = `Bearer ${env.LIVEPEER_API_KEY}`;
+
+ // Livepeer AI Gateway LLM pipeline accepts an OpenAI-compatible chat
+ // completions shape: { model, messages, max_tokens, temperature, stream }.
+ // The `messages` array carries the prompt as a single user turn.
+ const body = {
+ model,
+ messages: [{ role: 'user', content: prompt }],
+ max_tokens,
+ temperature,
+ stream: false,
+ };
+
+ const t0 = Date.now();
+ let upstream;
+ try {
+ upstream = await fetch(url, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(body),
+ });
+ } catch (e) {
+ return {
+ ok: false,
+ network: 'Livepeer',
+ model,
+ gateway,
+ gateway_url: url,
+ latency_ms: Date.now() - t0,
+ error: 'network_error',
+ error_message: String(e?.message || e),
+ };
+ }
+ const latency_ms = Date.now() - t0;
+
+ if (!upstream.ok) {
+ const text = await upstream.text().catch(() => '');
+ return {
+ ok: false,
+ network: 'Livepeer',
+ model,
+ gateway,
+ gateway_url: url,
+ latency_ms,
+ error: 'upstream_error',
+ upstream_status: upstream.status,
+ upstream_body: text.slice(0, 1000),
+ };
+ }
+
+ const data = await upstream.json().catch(() => null);
+ if (!data) {
+ return {
+ ok: false,
+ network: 'Livepeer',
+ model,
+ gateway,
+ gateway_url: url,
+ latency_ms,
+ error: 'parse_error',
+ };
+ }
+
+ // The Livepeer AI Gateway returns OpenAI-style choices when present, and
+ // the older Studio LLM pipeline returns `{ response, tokens_used }`. Handle
+ // both so the demo works regardless of which orchestrator answered.
+ let reply = '';
+ let prompt_tokens = null;
+ let completion_tokens = null;
+
+ if (Array.isArray(data.choices) && data.choices.length) {
+ const first = data.choices[0];
+ reply = first?.message?.content || first?.text || '';
+ prompt_tokens = data?.usage?.prompt_tokens ?? null;
+ completion_tokens = data?.usage?.completion_tokens ?? null;
+ } else if (typeof data.response === 'string') {
+ reply = data.response;
+ // The legacy shape only reports a single `tokens_used` total; split it
+ // best-effort by estimating prompt tokens from the input (≈4 chars/tok).
+ const total = Number(data.tokens_used) || 0;
+ const estPrompt = Math.min(total, Math.ceil(prompt.length / 4));
+ prompt_tokens = estPrompt;
+ completion_tokens = Math.max(total - estPrompt, 0);
+ } else if (typeof data === 'string') {
+ reply = data;
+ }
+
+ return {
+ ok: Boolean(reply),
+ network: 'Livepeer',
+ model,
+ gateway,
+ gateway_url: url,
+ latency_ms,
+ reply: reply.trim(),
+ prompt_tokens,
+ completion_tokens,
+ ...(reply ? {} : { error: 'empty_response', raw: JSON.stringify(data).slice(0, 1000) }),
+ };
+}
+
+// ── handler ──────────────────────────────────────────────────────────────────
+
+export default wrap(async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ if (req.method === 'GET') {
+ // Surface the live model list + gateway state so the demo's settings
+ // drawer can render without hard-coding it in HTML.
+ return json(res, 200, {
+ ok: true,
+ default_model: DEFAULT_LIVEPEER_MODEL,
+ models: LIVEPEER_MODELS,
+ gateway: env.LIVEPEER_API_KEY ? 'studio' : 'public',
+ gateway_url: env.LIVEPEER_API_KEY
+ ? 'https://livepeer.studio/api/generate/llm'
+ : 'https://dream-gateway.livepeer.cloud/llm',
+ });
+ }
+
+ if (!method(req, res, ['POST'])) return;
+
+ let body;
+ try {
+ body = await readJson(req, 200_000);
+ } catch (e) {
+ return error(res, e.status || 400, 'bad_request', e.message);
+ }
+
+ const prompt = clampPrompt(body.prompt);
+ if (!prompt) return error(res, 400, 'bad_request', 'prompt is required');
+
+ const model = typeof body.model === 'string' && body.model.trim()
+ ? body.model.trim().slice(0, 200)
+ : DEFAULT_LIVEPEER_MODEL;
+ const max_tokens = clampInt(body.max_tokens, 32, 2048, 512);
+ const temperature = clampTemp(body.temperature, 0.7);
+
+ const [claudeRes, livepeerRes] = await Promise.allSettled([
+ callClaude({ prompt, max_tokens, temperature }),
+ callLivepeer({ prompt, model, max_tokens, temperature }),
+ ]);
+
+ const claude = claudeRes.status === 'fulfilled'
+ ? claudeRes.value
+ : {
+ ok: false,
+ network: 'Anthropic',
+ model: CLAUDE_MODEL,
+ error: 'leg_failed',
+ error_message: String(claudeRes.reason?.message || claudeRes.reason || 'unknown'),
+ };
+
+ const livepeer = livepeerRes.status === 'fulfilled'
+ ? livepeerRes.value
+ : {
+ ok: false,
+ network: 'Livepeer',
+ model,
+ error: 'leg_failed',
+ error_message: String(livepeerRes.reason?.message || livepeerRes.reason || 'unknown'),
+ };
+
+ return json(res, 200, {
+ ok: true,
+ prompt,
+ max_tokens,
+ temperature,
+ claude,
+ livepeer,
+ });
+});
diff --git a/migrations/20260517170000_avatar_reconstruct.sql b/migrations/20260517170000_avatar_reconstruct.sql
new file mode 100644
index 000000000..509a4b97d
--- /dev/null
+++ b/migrations/20260517170000_avatar_reconstruct.sql
@@ -0,0 +1,29 @@
+-- Phase 1 — Selfie → Avatar reconstruction
+--
+-- The selfie pipeline submits a Replicate job *before* an avatar row exists:
+-- the user has photos, not a GLB, and the GLB is the *output* of the job.
+-- We let the job exist without a source avatar and materialize the avatar
+-- row on success. Both relaxations are backwards-compatible — every existing
+-- row is non-null today.
+
+-- 1. Allow avatar_regen_jobs to track jobs that have no input avatar (only
+-- selfie photos). The 'reconstruct' mode is the sole legitimate source.
+alter table avatar_regen_jobs
+ alter column source_avatar_id drop not null;
+
+-- 2. Add the 'reconstruct' source to the avatars source check so the avatar
+-- row created from a finished reconstruction can be tagged correctly.
+do $$
+begin
+ if exists (
+ select 1
+ from information_schema.check_constraints
+ where constraint_name like 'avatars_source_check%'
+ ) then
+ alter table avatars drop constraint if exists avatars_source_check;
+ end if;
+end$$;
+
+alter table avatars
+ add constraint avatars_source_check
+ check (source in ('upload','avaturn','readyplayer','import','direct-upload','reconstruct'));
diff --git a/public/demos/livepeer-inference.html b/public/demos/livepeer-inference.html
new file mode 100644
index 000000000..581569666
--- /dev/null
+++ b/public/demos/livepeer-inference.html
@@ -0,0 +1,394 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Decentralized inference · three.ws lab</title>
+ <meta
+ name="description"
+ content="Same prompt, two providers. Compare three.ws default inference against a decentralized AI gateway side-by-side: latency, token counts, and the full reply from each."
+ />
+ <meta name="robots" content="noindex" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <style>
+ :root { color-scheme: dark; }
+ body { background: #05060a; color: #eee; font: 15px/1.5 -apple-system, system-ui, 'Segoe UI', Roboto, sans-serif; margin: 0; }
+ .stage { max-width: 1100px; margin: 0 auto; padding: 48px 24px 80px; }
+ .crumb a { color: #8a8d98; text-decoration: none; }
+ .crumb a:hover { color: #d6ff3d; }
+ h1 { font-size: 28px; font-weight: 600; letter-spacing: -0.015em; margin: 14px 0 6px; }
+ .sub { color: #8a8d98; max-width: 70ch; margin: 0 0 26px; }
+
+ .composer {
+ display: flex; flex-direction: column; gap: 12px;
+ background: #0f1018; border: 1.5px solid #1e1f2b; border-radius: 14px;
+ padding: 18px; margin-bottom: 18px;
+ }
+ .composer textarea {
+ width: 100%; min-height: 96px; resize: vertical;
+ padding: 12px 14px; background: #07080d; border: 1px solid #1e1f2b;
+ border-radius: 10px; color: #eee; font: inherit; line-height: 1.5;
+ }
+ .row {
+ display: flex; gap: 10px; align-items: center; flex-wrap: wrap;
+ }
+ .row label { font-size: 12px; color: #8a8d98; text-transform: uppercase; letter-spacing: 0.08em; }
+ .row select, .row input[type="text"] {
+ background: #07080d; border: 1px solid #1e1f2b; color: #eee;
+ padding: 8px 10px; border-radius: 9px; font: inherit;
+ }
+ button {
+ background: #d6ff3d; color: #0a0a0a; border: 0; border-radius: 9px;
+ padding: 10px 16px; font-weight: 600; cursor: pointer; font: inherit;
+ }
+ button.secondary { background: rgba(255,255,255,0.06); color: #eee; }
+ button:disabled { opacity: 0.4; cursor: not-allowed; }
+
+ details.drawer {
+ background: #0f1018; border: 1.5px solid #1e1f2b; border-radius: 14px;
+ padding: 0; margin-bottom: 18px;
+ }
+ details.drawer > summary {
+ padding: 12px 18px; cursor: pointer; user-select: none;
+ font-size: 13px; color: #c5c8d3; letter-spacing: 0.01em;
+ list-style: none;
+ }
+ details.drawer > summary::-webkit-details-marker { display: none; }
+ details.drawer > summary::before {
+ content: '▸'; color: #8a8d98; margin-right: 8px; display: inline-block;
+ transition: transform 0.12s ease;
+ }
+ details.drawer[open] > summary::before { transform: rotate(90deg); }
+ details.drawer > .drawer-body { padding: 0 18px 18px; display: flex; gap: 14px; flex-wrap: wrap; align-items: center; }
+
+ .grid {
+ display: grid; grid-template-columns: 1fr 1fr; gap: 14px;
+ }
+ @media (max-width: 820px) { .grid { grid-template-columns: 1fr; } }
+
+ .card {
+ background: #0f1018; border: 1.5px solid #1e1f2b; border-radius: 14px;
+ padding: 18px; display: flex; flex-direction: column; min-height: 320px;
+ }
+ .card.claude { border-color: #2c3a5a; }
+ .card.livepeer { border-color: #3a2c5a; }
+ .card-head {
+ display: flex; justify-content: space-between; align-items: baseline;
+ gap: 8px; margin-bottom: 8px;
+ }
+ .card-title { font-size: 15px; font-weight: 600; letter-spacing: -0.005em; margin: 0; }
+ .chip {
+ font-size: 10.5px; color: #8a8d98; text-transform: uppercase; letter-spacing: 0.06em;
+ padding: 3px 8px; background: rgba(255,255,255,0.05); border-radius: 999px;
+ border: 1px solid rgba(255,255,255,0.08);
+ }
+ .card.claude .chip { color: #aab8ff; border-color: rgba(170,184,255,0.25); background: rgba(170,184,255,0.08); }
+ .card.livepeer .chip { color: #d6a8ff; border-color: rgba(214,168,255,0.25); background: rgba(214,168,255,0.08); }
+
+ .stats {
+ display: flex; gap: 14px; flex-wrap: wrap;
+ margin: 6px 0 10px; font-size: 11.5px;
+ color: #8a8d98; font-family: ui-monospace, 'SF Mono', Menlo, monospace;
+ }
+ .stats span { display: inline-flex; gap: 5px; align-items: baseline; }
+ .stats strong { color: #d6ff3d; font-weight: 600; font-size: 12px; }
+
+ .card-body {
+ flex: 1; padding: 14px; background: #07080d; border: 1px solid #1e1f2b;
+ border-radius: 9px; font-size: 13.5px; line-height: 1.6; color: #ddd;
+ white-space: pre-wrap; min-height: 160px; max-height: 380px; overflow-y: auto;
+ }
+ .card-body.empty { color: #565762; font-style: italic; }
+ .card-body.error { color: #ff8a8a; }
+
+ .card-footer {
+ margin-top: 10px; font-size: 11px; color: #565762;
+ font-family: ui-monospace, monospace;
+ }
+
+ .spinner {
+ display: inline-block; width: 10px; height: 10px; border-radius: 50%;
+ background: #d6ff3d; animation: pulse 1s ease-in-out infinite;
+ vertical-align: middle; margin-left: 8px;
+ }
+ @keyframes pulse { 0%, 100% { opacity: 0.3; } 50% { opacity: 1; } }
+
+ .log {
+ background: #07080d; border: 1px solid #1e1f2b; border-radius: 10px;
+ padding: 12px 14px; font-family: ui-monospace, 'SF Mono', Menlo, monospace;
+ font-size: 12px; line-height: 1.65; color: #8a8d98;
+ max-height: 240px; overflow: auto; white-space: pre-wrap;
+ margin-top: 18px;
+ }
+ .log .ok { color: #d6ff3d; }
+ .log .err { color: #ff8a8a; }
+ .log .info { color: #66d9ef; }
+ .log .dim { color: #565762; }
+
+ .footnote {
+ margin-top: 28px; padding-top: 16px; border-top: 1px solid #1e1f2b;
+ color: #565762; font-size: 12px;
+ }
+ .footnote a { color: #8a8d98; text-decoration: none; }
+ .footnote a:hover { color: #d6ff3d; }
+ </style>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+
+ <main class="stage">
+ <p class="crumb"><a href="/demos/">← lab</a></p>
+ <h1>three.ws · Decentralized inference</h1>
+ <p class="sub">
+ Same prompt, two providers, real responses. The left card hits
+ three.ws's default inference (Claude). The right card routes the
+ identical request through a decentralized AI gateway whose
+ orchestrators run open-weight models on commodity GPUs. Phase 4
+ of the roadmap: decoupling inference from any single vendor so
+ agents stay online when one provider doesn't.
+ </p>
+
+ <section class="composer">
+ <div>
+ <label for="prompt" style="font-size:12px;color:#8a8d98;text-transform:uppercase;letter-spacing:0.08em;">Prompt</label>
+ <textarea id="prompt">In one paragraph, explain why decentralized inference matters for AI agents.</textarea>
+ </div>
+ <div class="row">
+ <label>Max tokens</label>
+ <input type="text" id="max-tokens" value="512" inputmode="numeric" style="width: 80px;" />
+ <label>Temperature</label>
+ <input type="text" id="temperature" value="0.7" inputmode="decimal" style="width: 70px;" />
+ <div style="flex: 1"></div>
+ <button class="secondary" id="clear-btn">Clear</button>
+ <button id="run-btn">Compare</button>
+ </div>
+ </section>
+
+ <details class="drawer" id="settings">
+ <summary>Settings · decentralized gateway model</summary>
+ <div class="drawer-body">
+ <label for="livepeer-model" style="font-size:12px;color:#8a8d98;text-transform:uppercase;letter-spacing:0.08em;">Open-weight model</label>
+ <select id="livepeer-model">
+ <option value="meta-llama/Meta-Llama-3.1-8B-Instruct" selected>Meta-Llama-3.1-8B-Instruct</option>
+ <option value="mistralai/Mistral-Nemo-Instruct-2407">Mistral-Nemo-Instruct-2407</option>
+ <option value="Qwen/Qwen2.5-7B-Instruct">Qwen2.5-7B-Instruct</option>
+ </select>
+ <span id="gateway-info" style="font-size:11.5px;color:#565762;font-family:ui-monospace,monospace;"></span>
+ </div>
+ </details>
+
+ <div class="grid">
+ <section class="card claude" id="card-claude">
+ <div class="card-head">
+ <h2 class="card-title">three.ws default</h2>
+ <span class="chip">Claude · Anthropic</span>
+ </div>
+ <div class="stats">
+ <span>latency <strong id="claude-latency">—</strong></span>
+ <span>in <strong id="claude-prompt-tokens">—</strong></span>
+ <span>out <strong id="claude-completion-tokens">—</strong></span>
+ </div>
+ <div class="card-body empty" id="claude-body">awaiting prompt…</div>
+ <div class="card-footer" id="claude-footer">model · —</div>
+ </section>
+
+ <section class="card livepeer" id="card-livepeer">
+ <div class="card-head">
+ <h2 class="card-title">three.ws decentralized</h2>
+ <span class="chip">Open-weight · decentralized</span>
+ </div>
+ <div class="stats">
+ <span>latency <strong id="livepeer-latency">—</strong></span>
+ <span>in <strong id="livepeer-prompt-tokens">—</strong></span>
+ <span>out <strong id="livepeer-completion-tokens">—</strong></span>
+ </div>
+ <div class="card-body empty" id="livepeer-body">awaiting prompt…</div>
+ <div class="card-footer" id="livepeer-footer">model · — · gateway · —</div>
+ </section>
+ </div>
+
+ <div class="log" id="log">ready.</div>
+
+ <p class="footnote">
+ Powered by <a href="https://livepeer.org" target="_blank" rel="noopener">Livepeer</a> AI Gateway
+ on the decentralized side. Claude reply provided by Anthropic. The
+ public decentralized gateway is rate-limited and occasionally
+ slow — typical p50 latency is 2–10 s for an 8B-param model.
+ </p>
+ </main>
+
+ <script src="/nav.js"></script>
+ <script type="module">
+ const $ = (id) => document.getElementById(id);
+ const log = $('log');
+
+ function logLine(msg, cls = '') {
+ const t = new Date().toTimeString().slice(0, 8);
+ const span = document.createElement('span');
+ if (cls) span.className = cls;
+ span.textContent = `[${t}] ${msg}\n`;
+ log.appendChild(span);
+ log.scrollTop = log.scrollHeight;
+ }
+
+ function setBody(id, text, cls = '') {
+ const el = $(id);
+ el.textContent = text;
+ el.classList.remove('empty', 'error');
+ if (cls) el.classList.add(cls);
+ }
+
+ function setText(id, text) { $(id).textContent = text; }
+
+ function fmtMs(ms) {
+ if (ms == null) return '—';
+ if (ms < 1000) return ms + 'ms';
+ return (ms / 1000).toFixed(2) + 's';
+ }
+
+ function fmtTok(n) {
+ if (n == null) return '—';
+ return String(n);
+ }
+
+ // Load gateway info on page load so we can show whether we're hitting
+ // studio (auth'd) or the public dream gateway. Pure cosmetic.
+ (async function loadGatewayInfo() {
+ try {
+ const r = await fetch('/api/inference/livepeer');
+ if (!r.ok) throw new Error('GET /api/inference/livepeer ' + r.status);
+ const info = await r.json();
+ $('gateway-info').textContent =
+ `gateway · ${info.gateway} · ${info.gateway_url}`;
+ if (Array.isArray(info.models) && info.models.length) {
+ const sel = $('livepeer-model');
+ const current = sel.value;
+ sel.innerHTML = '';
+ for (const m of info.models) {
+ const opt = document.createElement('option');
+ opt.value = m;
+ opt.textContent = m.split('/').pop();
+ if (m === current || m === info.default_model) opt.selected = true;
+ sel.appendChild(opt);
+ }
+ }
+ } catch (err) {
+ $('gateway-info').textContent = 'gateway · unavailable';
+ logLine('gateway info fetch failed: ' + err.message, 'err');
+ }
+ })();
+
+ function resetCards() {
+ for (const id of [
+ 'claude-latency', 'claude-prompt-tokens', 'claude-completion-tokens',
+ 'livepeer-latency', 'livepeer-prompt-tokens', 'livepeer-completion-tokens',
+ ]) setText(id, '—');
+ const cb = $('claude-body');
+ cb.textContent = 'streaming…';
+ cb.className = 'card-body empty';
+ const lb = $('livepeer-body');
+ lb.textContent = 'streaming…';
+ lb.className = 'card-body empty';
+ setText('claude-footer', 'model · —');
+ setText('livepeer-footer', 'model · — · gateway · —');
+ }
+
+ function renderClaude(c) {
+ setText('claude-latency', fmtMs(c.latency_ms));
+ setText('claude-prompt-tokens', fmtTok(c.prompt_tokens));
+ setText('claude-completion-tokens', fmtTok(c.completion_tokens));
+ setText('claude-footer', `model · ${c.model || '—'}`);
+ if (c.ok) {
+ setBody('claude-body', c.reply || '(empty)');
+ } else {
+ const msg = c.upstream_body
+ ? `${c.error || 'error'} (${c.upstream_status || '?'}):\n${c.upstream_body}`
+ : c.error_message || c.error || 'unknown error';
+ setBody('claude-body', msg, 'error');
+ }
+ }
+
+ function renderLivepeer(lp) {
+ setText('livepeer-latency', fmtMs(lp.latency_ms));
+ setText('livepeer-prompt-tokens', fmtTok(lp.prompt_tokens));
+ setText('livepeer-completion-tokens', fmtTok(lp.completion_tokens));
+ setText(
+ 'livepeer-footer',
+ `model · ${lp.model || '—'} · gateway · ${lp.gateway || '—'}`,
+ );
+ if (lp.ok) {
+ setBody('livepeer-body', lp.reply || '(empty)');
+ } else {
+ const msg = lp.upstream_body
+ ? `${lp.error || 'error'} (${lp.upstream_status || '?'}):\n${lp.upstream_body}`
+ : lp.error_message || lp.error || 'unknown error';
+ setBody('livepeer-body', msg, 'error');
+ }
+ }
+
+ $('clear-btn').addEventListener('click', () => {
+ $('prompt').value = '';
+ resetCards();
+ $('claude-body').textContent = 'awaiting prompt…';
+ $('livepeer-body').textContent = 'awaiting prompt…';
+ log.innerHTML = 'ready.\n';
+ });
+
+ $('run-btn').addEventListener('click', async () => {
+ const prompt = $('prompt').value.trim();
+ if (!prompt) {
+ logLine('prompt is empty', 'err');
+ return;
+ }
+ const max_tokens = Math.max(32, Math.min(2048, parseInt($('max-tokens').value, 10) || 512));
+ const temperature = Math.max(0, Math.min(2, parseFloat($('temperature').value) || 0.7));
+ const model = $('livepeer-model').value;
+
+ $('run-btn').disabled = true;
+ $('run-btn').innerHTML = 'Comparing<span class="spinner"></span>';
+ resetCards();
+ logLine(`POST /api/inference/livepeer · model=${model} · max=${max_tokens} · t=${temperature}`, 'info');
+
+ const t0 = performance.now();
+ try {
+ const r = await fetch('/api/inference/livepeer', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ prompt, model, max_tokens, temperature }),
+ });
+ const data = await r.json();
+ const totalMs = Math.round(performance.now() - t0);
+ if (!r.ok) {
+ logLine(`server ${r.status}: ${data.error_description || data.error || 'error'}`, 'err');
+ $('claude-body').textContent = 'request failed';
+ $('claude-body').className = 'card-body error';
+ $('livepeer-body').textContent = 'request failed';
+ $('livepeer-body').className = 'card-body error';
+ return;
+ }
+ renderClaude(data.claude);
+ renderLivepeer(data.livepeer);
+
+ const cMs = data.claude?.latency_ms;
+ const lMs = data.livepeer?.latency_ms;
+ logLine(`done in ${totalMs}ms · claude ${fmtMs(cMs)} (${data.claude?.ok ? 'ok' : 'fail'}) · livepeer ${fmtMs(lMs)} (${data.livepeer?.ok ? 'ok' : 'fail'})`, 'ok');
+
+ if (!data.livepeer?.ok) {
+ const reason = data.livepeer?.error || 'unknown';
+ const detail = data.livepeer?.upstream_status
+ ? ` (upstream ${data.livepeer.upstream_status})`
+ : '';
+ logLine(`livepeer leg failed: ${reason}${detail} — public gateway often has no orchestrators online for a given model. Try another model in settings.`, 'dim');
+ }
+ } catch (err) {
+ logLine('fetch failed: ' + err.message, 'err');
+ } finally {
+ $('run-btn').disabled = false;
+ $('run-btn').textContent = 'Compare';
+ }
+ });
+ </script>
+ </body>
+</html>
diff --git a/public/demos/selfie-fit.html b/public/demos/selfie-fit.html
index beeb69347..9b89b3993 100644
--- a/public/demos/selfie-fit.html
+++ b/public/demos/selfie-fit.html
@@ -877,11 +877,42 @@
(photos.frontal.length + photos.left.length + photos.right.length) / 1024,
);
log(`photos encoded (${totalKb} KB total base64). submitting...`, 'info');
- submitBtn.textContent = 'Submitting…';
- // The live API contract uses { body_type, avatar_type }. We map
- // the UI's "style" radio to avatar_type since the upstream
- // endpoint expects that key.
+ // 1) Try the native three.ws reconstruction pipeline first.
+ // Falls back to the in-browser editor path on 501 (provider
+ // unconfigured) — that lets us ship the new path safely
+ // even before REPLICATE_RECONSTRUCT_MODEL is populated.
+ submitBtn.textContent = 'Generating 3D model…';
+ const nativeRes = await fetch('/api/avatars/_actions?action=reconstruct', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ name: `Selfie ${new Date().toISOString().slice(0, 10)}`,
+ photos: [photos.frontal, photos.left, photos.right],
+ visibility: 'private',
+ params: { body_type: state.bodyType, avatar_type: state.style },
+ }),
+ });
+ if (nativeRes.status === 501) {
+ const why = await nativeRes.json().catch(() => ({}));
+ log(`native pipeline unavailable (${why?.error || '501'}); using editor path…`, 'info');
+ } else if (nativeRes.ok) {
+ const job = await nativeRes.json();
+ log(`✓ reconstruction job queued: ${job.jobId}`, 'ok');
+ const avatarId = await pollReconstructJob(job.jobId);
+ const createHref = `/create?avatarId=${encodeURIComponent(avatarId)}`;
+ log(`✓ avatar materialized → /create?avatarId=${avatarId}`, 'ok');
+ showResult(createHref, { native: true, avatarId });
+ submitBtn.textContent = 'Done ✓';
+ return;
+ } else {
+ const text = await nativeRes.text();
+ log(`native pipeline error ${nativeRes.status}: ${text.slice(0, 200)}; falling back…`, 'err');
+ }
+
+ // 2) Fallback: existing in-browser editor path.
+ submitBtn.textContent = 'Opening editor…';
const res = await fetch('/api/onboarding/avaturn-session', {
method: 'POST',
credentials: 'include',
@@ -909,11 +940,58 @@
}
});
- function showResult(url) {
+ // Poll the regenerate-status endpoint until the reconstruct job either
+ // materializes the avatar (resultAvatarId set) or fails. Uses real
+ // exponential backoff capped at 8s between polls; gives up after ~5
+ // minutes (sub-60s is the Phase 1 verification target but Replicate
+ // cold-starts can occasionally exceed that).
+ async function pollReconstructJob(jobId) {
+ const start = Date.now();
+ const TIMEOUT_MS = 5 * 60 * 1000;
+ let delay = 1500;
+ for (;;) {
+ if (Date.now() - start > TIMEOUT_MS) {
+ throw new Error('reconstruct job timed out after 5 min');
+ }
+ const r = await fetch(
+ `/api/avatars/_actions?action=regenerate-status&jobId=${encodeURIComponent(jobId)}`,
+ { credentials: 'include' },
+ );
+ if (!r.ok) {
+ const text = await r.text();
+ throw new Error(`status HTTP ${r.status}: ${text.slice(0, 200)}`);
+ }
+ const data = await r.json();
+ if (data.error) log(`provider note: ${data.error}`, 'info');
+ if (data.status === 'failed') {
+ throw new Error(`reconstruct failed: ${data.error || 'unknown'}`);
+ }
+ if (data.status === 'done' && data.resultAvatarId) {
+ return data.resultAvatarId;
+ }
+ await new Promise((r) => setTimeout(r, delay));
+ delay = Math.min(delay * 1.4, 8000);
+ }
+ }
+
+ function showResult(url, opts = {}) {
const card = $('#result-card');
card.classList.add('show');
$('#result-url').textContent = url;
- $('#open-session-btn').onclick = () => openIframeModal(url);
+ const btn = $('#open-session-btn');
+ const heading = card.querySelector('h2');
+ const blurb = card.querySelector('div[style*="8a8d98"]');
+ if (opts.native) {
+ if (heading) heading.textContent = 'Your three.ws avatar is ready';
+ if (blurb) blurb.textContent = 'Reconstructed from your three selfies. Continue to mint it on-chain.';
+ btn.textContent = 'Mint as agent →';
+ btn.onclick = () => { window.location.href = url; };
+ } else {
+ if (heading) heading.textContent = 'three.ws Selfie session ready';
+ if (blurb) blurb.textContent = 'Open the editor to refine and export your avatar.';
+ btn.textContent = 'Open three.ws Selfie editor';
+ btn.onclick = () => openIframeModal(url);
+ }
}
function openIframeModal(url) {
diff --git a/public/demos/skill-royalty.html b/public/demos/skill-royalty.html
new file mode 100644
index 000000000..d9a945ad2
--- /dev/null
+++ b/public/demos/skill-royalty.html
@@ -0,0 +1,824 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>three.ws · Skill royalty distribution</title>
+ <meta
+ name="description"
+ content="Create an on-chain royalty split that pays skill authors automatically. Pull split contract on Base Sepolia testnet, real wallet signing, no mocks."
+ />
+ <meta name="robots" content="noindex" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <style>
+ :root { color-scheme: dark; }
+ body { background: #05060a; color: #eee; font: 15px/1.5 -apple-system, system-ui, sans-serif; margin: 0; }
+ .stage { max-width: 1080px; margin: 0 auto; padding: 48px 24px 80px; }
+ .crumb a { color: #8a8d98; text-decoration: none; }
+ .crumb a:hover { color: #d6ff3d; }
+ h1 { font-size: 28px; font-weight: 600; letter-spacing: -0.015em; margin: 14px 0 8px; }
+ .sub { color: #8a8d98; max-width: 72ch; margin: 0 0 26px; }
+ .sub code { background: #0f1018; padding: 1px 6px; border-radius: 5px; font-size: 12.5px; color: #d6ff3d; }
+ h2 { font-size: 18px; font-weight: 600; margin: 0 0 14px; letter-spacing: -0.01em; }
+ .card { background: #0f1018; border: 1.5px solid #1e1f2b; border-radius: 14px; padding: 22px; margin: 0 0 22px; }
+ .row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
+ label { display: flex; flex-direction: column; gap: 4px; font-size: 11px; color: #8a8d98; text-transform: uppercase; letter-spacing: 0.08em; flex: 1 1 240px; }
+ input[type=text], input[type=number] {
+ background: #07080d; border: 1px solid #1e1f2b; color: #eee;
+ padding: 9px 11px; border-radius: 9px; font: inherit;
+ }
+ button {
+ background: #d6ff3d; color: #0a0a0a; border: 0; border-radius: 9px;
+ padding: 9px 16px; font-weight: 600; cursor: pointer; font: inherit;
+ }
+ button.secondary { background: rgba(255,255,255,0.06); color: #eee; border: 1px solid #1e1f2b; }
+ button.tiny { padding: 5px 9px; font-size: 12px; border-radius: 7px; }
+ button:disabled { opacity: 0.35; cursor: not-allowed; }
+ .pill {
+ display: inline-flex; align-items: center; gap: 6px;
+ font-family: ui-monospace, monospace; font-size: 11.5px;
+ padding: 4px 9px; border-radius: 999px;
+ background: rgba(214,255,61,0.08); color: #d6ff3d;
+ border: 1px solid rgba(214,255,61,0.2);
+ cursor: pointer;
+ }
+ .pill.bad { background: rgba(255,138,138,0.08); color: #ff8a8a; border-color: rgba(255,138,138,0.25); }
+ .pill.muted { background: rgba(255,255,255,0.04); color: #8a8d98; border-color: #1e1f2b; cursor: default; }
+ .notice {
+ padding: 11px 14px; border-radius: 10px; font-size: 13px; margin: 12px 0;
+ background: rgba(154,212,255,0.06); border: 1px solid rgba(154,212,255,0.2); color: #9ad4ff;
+ }
+ .notice.warn { background: rgba(255,196,87,0.07); border-color: rgba(255,196,87,0.3); color: #ffc457; }
+ .notice.err { background: rgba(255,138,138,0.07); border-color: rgba(255,138,138,0.3); color: #ff8a8a; }
+ .notice.ok { background: rgba(214,255,61,0.07); border-color: rgba(214,255,61,0.3); color: #d6ff3d; }
+ .log {
+ background: #07080d; border: 1px solid #1e1f2b; border-radius: 9px;
+ padding: 12px; font-family: ui-monospace, monospace; font-size: 12px;
+ line-height: 1.6; color: #8a8d98; max-height: 280px; overflow: auto; white-space: pre-wrap;
+ }
+ .log .ok { color: #d6ff3d; }
+ .log .err { color: #ff6b6b; }
+ .log .info { color: #66d9ef; }
+ .kv { display: grid; grid-template-columns: 160px 1fr; gap: 4px 14px; font-size: 12.5px; }
+ .kv dt { color: #8a8d98; font-size: 11px; text-transform: uppercase; letter-spacing: 0.07em; }
+ .kv dd { margin: 0; font-family: ui-monospace, monospace; color: #ddd; word-break: break-all; }
+ .kv dd a { color: #9ad4ff; }
+ table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
+ th, td { text-align: left; padding: 9px 10px; border-bottom: 1px solid #1e1f2b; vertical-align: middle; }
+ th { color: #8a8d98; font-weight: 500; text-transform: uppercase; font-size: 10.5px; letter-spacing: 0.08em; }
+ td { font-family: ui-monospace, monospace; color: #ddd; word-break: break-word; }
+ td input[type=text] { width: 100%; }
+ td input[type=number] { width: 90px; }
+ td.actions { width: 60px; text-align: right; }
+ .sum-row { display: flex; justify-content: space-between; align-items: center; margin-top: 12px; font-size: 13px; }
+ .sum-row .sum-good { color: #d6ff3d; }
+ .sum-row .sum-bad { color: #ff8a8a; }
+ .copy-addr { cursor: pointer; color: #9ad4ff; text-decoration: none; }
+ .copy-addr:hover { color: #d6ff3d; }
+ .full { flex-basis: 100%; }
+ footer.foot { color: #5b5d6b; font-size: 11.5px; margin-top: 30px; text-align: center; }
+ footer.foot a { color: #8a8d98; }
+ </style>
+ <script type="importmap">
+ {
+ "imports": {
+ "@0xsplits/splits-sdk": "https://esm.sh/@0xsplits/[email protected]?bundle-deps",
+ "@0xsplits/splits-sdk/constants": "https://esm.sh/@0xsplits/[email protected]/constants?bundle-deps",
+ "viem": "https://esm.sh/viem@2",
+ "viem/chains": "https://esm.sh/viem@2/chains"
+ }
+ }
+ </script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+
+ <main class="stage">
+ <p class="crumb"><a href="/demos/">&larr; lab</a></p>
+ <h1>three.ws &middot; Skill royalty distribution</h1>
+ <p class="sub">
+ A royalty primitive for skill authors: deploy a single
+ <b>pull-split contract</b> on <b>Base Sepolia</b> (testnet, chainId
+ <code>84532</code>) that automatically slices every incoming ETH
+ payment by your configured percentages. Fund it once, then call
+ <code>distribute</code> &mdash; each author can withdraw their
+ share whenever. No backend, no custodial keys; you sign every
+ write yourself. The contract is immutable (no owner).
+ </p>
+
+ <section class="card">
+ <h2>1. Wallet</h2>
+ <div class="row" id="wallet-row">
+ <button id="connect-btn">Connect wallet</button>
+ <span id="wallet-pill" class="pill muted" title="click to copy">not connected</span>
+ <span id="chain-pill" class="pill muted">no chain</span>
+ <button id="switch-btn" class="secondary" style="display:none">Switch to Base Sepolia</button>
+ </div>
+ <p class="notice">
+ You need a few drops of Base Sepolia ETH. Free at the
+ <a href="https://portal.cdp.coinbase.com/products/faucet" target="_blank" rel="noopener">Coinbase Base Sepolia faucet</a>,
+ the <a href="https://www.alchemy.com/faucets/base-sepolia" target="_blank" rel="noopener">Alchemy faucet</a>,
+ or the <a href="https://faucets.chain.link/base-sepolia" target="_blank" rel="noopener">Chainlink faucet</a>.
+ </p>
+ <p class="notice warn" id="wallet-warn" style="display:none"></p>
+ </section>
+
+ <section class="card">
+ <h2>2. Configure skill-author recipients</h2>
+ <p style="margin:0 0 10px;color:#8a8d98;font-size:13px">
+ Up to 10 rows. Percentages must sum to <b>100</b>. Distributor fee
+ is fixed at <code>0%</code> &mdash; nobody skims the pot.
+ </p>
+ <table id="recipients-tbl">
+ <thead>
+ <tr>
+ <th style="width:60px">#</th>
+ <th>Skill-author address (0x&hellip;)</th>
+ <th style="width:130px">Share %</th>
+ <th class="actions"></th>
+ </tr>
+ </thead>
+ <tbody id="recipients-body"></tbody>
+ </table>
+ <div class="sum-row">
+ <button id="add-row" class="secondary tiny" type="button">+ Add recipient</button>
+ <div id="sum-display">Sum: <span id="sum-val" class="sum-good">100.00</span> %</div>
+ </div>
+ </section>
+
+ <section class="card">
+ <h2>3. Create Split contract</h2>
+ <p style="margin:0 0 10px;color:#8a8d98;font-size:13px">
+ Calls <code>SplitV2Client.createSplit({ splitType: 'pull', ownerAddress: 0x0 })</code>
+ on the official Split V2 factory at
+ <code id="factory-addr">…</code>.
+ </p>
+ <div class="row">
+ <button id="create-btn" disabled>Deploy immutable pull split</button>
+ <button id="forget-btn" class="secondary" style="display:none">Forget this split</button>
+ </div>
+ <div id="split-info" style="margin-top:14px"></div>
+ </section>
+
+ <section class="card" id="fund-card" style="display:none">
+ <h2>4. Fund the split (test payment)</h2>
+ <div class="row">
+ <label>
+ ETH amount
+ <input type="number" id="fund-amount" value="0.001" step="0.0001" min="0" />
+ </label>
+ <label>
+ Recipient
+ <input type="text" id="fund-target" readonly />
+ </label>
+ <button id="fund-btn">Send test payment</button>
+ </div>
+ <div id="fund-result" style="margin-top:12px"></div>
+ </section>
+
+ <section class="card" id="inspect-card" style="display:none">
+ <h2>5. Inspect &amp; distribute</h2>
+ <div class="row">
+ <button id="refresh-btn" class="secondary">Refresh balance</button>
+ <button id="distribute-btn">Distribute to recipients</button>
+ <button id="withdraw-btn" class="secondary" style="display:none">Withdraw your share</button>
+ </div>
+ <div id="inspect-body" style="margin-top:14px"></div>
+ </section>
+
+ <section class="card">
+ <h2>Log</h2>
+ <div class="log" id="log">ready.</div>
+ </section>
+
+ <footer class="foot">
+ Powered by <a href="https://docs.splits.org/sdk/splits-v2" target="_blank" rel="noopener">0xSplits V2</a>
+ &middot; Pull-split contract address per chain documented at
+ <a href="https://docs.splits.org/sdk/splits-v2#supported-chains" target="_blank" rel="noopener">docs.splits.org/sdk/splits-v2#supported-chains</a>.
+ </footer>
+ </main>
+
+ <script src="/nav.js" defer></script>
+ <script type="module">
+ import {
+ createPublicClient,
+ createWalletClient,
+ custom,
+ http,
+ isAddress,
+ getAddress,
+ parseEther,
+ formatEther,
+ zeroAddress,
+ } from 'viem';
+ import { baseSepolia } from 'viem/chains';
+ import { SplitV2Client } from '@0xsplits/splits-sdk';
+ import { NATIVE_TOKEN_ADDRESS, getSplitV2FactoryAddress } from '@0xsplits/splits-sdk/constants';
+
+ // --- constants ---
+ const BASE_SEPOLIA_CHAIN_ID = 84532;
+ const BASE_SEPOLIA_HEX = '0x14a34';
+ const BASE_SEPOLIA_RPC = 'https://sepolia.base.org';
+ const BASESCAN_BASE = 'https://sepolia.basescan.org';
+ const SPLITS_APP_BASE = 'https://app.splits.org';
+ const STORAGE_KEY = 'three-ws.skill-royalty.v1';
+ const MAX_RECIPIENTS = 10;
+
+ // SDK exports the canonical native-token sentinel; fall back to zero
+ // address only if (somehow) absent.
+ const NATIVE = NATIVE_TOKEN_ADDRESS || '0x0000000000000000000000000000000000000000';
+
+ const $ = (id) => document.getElementById(id);
+ const log = $('log');
+ const logLine = (msg, cls = '') => {
+ const t = new Date().toTimeString().slice(0, 8);
+ log.innerHTML += `\n<span class="${cls}">[${t}] ${msg}</span>`;
+ log.scrollTop = log.scrollHeight;
+ };
+
+ const escapeHtml = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ })[c]);
+
+ const shortAddr = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : '—');
+
+ // Three deterministic example addresses for the default rows. These
+ // are well-known burn / vanity addresses on testnets; users should
+ // replace them before deploying anything meaningful.
+ const DEFAULT_RECIPIENTS = [
+ { address: '0x000000000000000000000000000000000000dEaD', percentAllocation: 50 },
+ { address: '0x000000000000000000000000000000000000bEEF', percentAllocation: 30 },
+ { address: '0x00000000000000000000000000000000DeaDBeef', percentAllocation: 20 },
+ ];
+
+ // --- state ---
+ let publicClient = createPublicClient({ chain: baseSepolia, transport: http(BASE_SEPOLIA_RPC) });
+ let walletClient = null;
+ let splitsClient = null;
+ let connectedAddress = null;
+ let connectedChainId = null;
+ let recipients = [...DEFAULT_RECIPIENTS];
+ let splitAddress = null; // cached/created
+
+ // Factory address — used only for the on-page display.
+ try {
+ const factoryAddr = getSplitV2FactoryAddress(BASE_SEPOLIA_CHAIN_ID, 'pull');
+ $('factory-addr').textContent = factoryAddr;
+ } catch (_) {
+ $('factory-addr').textContent = '(pull factory)';
+ }
+
+ // --- localStorage cache ---
+ function loadCache() {
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ if (!raw) return null;
+ return JSON.parse(raw);
+ } catch { return null; }
+ }
+ function saveCache(obj) {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(obj));
+ }
+ function clearCache() {
+ localStorage.removeItem(STORAGE_KEY);
+ }
+
+ // --- recipients UI ---
+ function renderRecipients() {
+ const tbody = $('recipients-body');
+ tbody.innerHTML = recipients.map((r, i) => `
+ <tr>
+ <td>${i + 1}</td>
+ <td><input type="text" data-i="${i}" data-f="address" value="${escapeHtml(r.address)}" spellcheck="false" placeholder="0x…" /></td>
+ <td><input type="number" data-i="${i}" data-f="percentAllocation" value="${r.percentAllocation}" min="0" max="100" step="0.01" /></td>
+ <td class="actions">
+ <button class="secondary tiny remove-row" data-i="${i}" type="button" ${recipients.length <= 1 ? 'disabled' : ''}>×</button>
+ </td>
+ </tr>
+ `).join('');
+ tbody.querySelectorAll('input').forEach((el) => {
+ el.addEventListener('input', (e) => {
+ const i = Number(e.target.dataset.i);
+ const f = e.target.dataset.f;
+ const v = f === 'percentAllocation' ? Number(e.target.value) : e.target.value.trim();
+ recipients[i] = { ...recipients[i], [f]: v };
+ updateSum();
+ });
+ });
+ tbody.querySelectorAll('.remove-row').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const i = Number(btn.dataset.i);
+ recipients.splice(i, 1);
+ renderRecipients();
+ updateSum();
+ });
+ });
+ updateSum();
+ }
+
+ function updateSum() {
+ const sum = recipients.reduce((a, r) => a + (Number(r.percentAllocation) || 0), 0);
+ const el = $('sum-val');
+ const rounded = Math.round(sum * 100) / 100;
+ el.textContent = rounded.toFixed(2);
+ el.className = Math.abs(sum - 100) < 0.001 ? 'sum-good' : 'sum-bad';
+ updateCreateBtn();
+ }
+
+ function updateCreateBtn() {
+ const sum = recipients.reduce((a, r) => a + (Number(r.percentAllocation) || 0), 0);
+ const allValid = recipients.every((r) => isAddress(r.address) && Number(r.percentAllocation) > 0);
+ const sumOk = Math.abs(sum - 100) < 0.001;
+ const chainOk = connectedChainId === BASE_SEPOLIA_CHAIN_ID;
+ $('create-btn').disabled = !(allValid && sumOk && chainOk && walletClient);
+ }
+
+ $('add-row').addEventListener('click', () => {
+ if (recipients.length >= MAX_RECIPIENTS) {
+ logLine(`max ${MAX_RECIPIENTS} recipients`, 'err');
+ return;
+ }
+ recipients.push({ address: '', percentAllocation: 0 });
+ renderRecipients();
+ });
+
+ renderRecipients();
+
+ // --- wallet ---
+ function updateWalletUI() {
+ const pill = $('wallet-pill');
+ const chainPill = $('chain-pill');
+ const switchBtn = $('switch-btn');
+ const warn = $('wallet-warn');
+
+ if (connectedAddress) {
+ pill.textContent = shortAddr(connectedAddress);
+ pill.className = 'pill';
+ pill.title = `${connectedAddress} — click to copy`;
+ $('connect-btn').textContent = 'Reconnect';
+ } else {
+ pill.textContent = 'not connected';
+ pill.className = 'pill muted';
+ }
+
+ if (connectedChainId === BASE_SEPOLIA_CHAIN_ID) {
+ chainPill.textContent = 'Base Sepolia · 84532';
+ chainPill.className = 'pill';
+ switchBtn.style.display = 'none';
+ warn.style.display = 'none';
+ } else if (connectedChainId != null) {
+ chainPill.textContent = `wrong chain · ${connectedChainId}`;
+ chainPill.className = 'pill bad';
+ switchBtn.style.display = '';
+ warn.textContent = `Your wallet is on chain ${connectedChainId}. This demo refuses to write on any chain other than Base Sepolia (84532). Click "Switch" above.`;
+ warn.style.display = '';
+ } else {
+ chainPill.textContent = 'no chain';
+ chainPill.className = 'pill muted';
+ switchBtn.style.display = 'none';
+ warn.style.display = 'none';
+ }
+
+ updateCreateBtn();
+ renderWithdrawButton();
+ }
+
+ async function rebuildClients() {
+ if (!window.ethereum || !connectedAddress) {
+ walletClient = null;
+ splitsClient = null;
+ return;
+ }
+ walletClient = createWalletClient({
+ chain: baseSepolia,
+ transport: custom(window.ethereum),
+ account: connectedAddress,
+ });
+ splitsClient = new SplitV2Client({
+ chainId: BASE_SEPOLIA_CHAIN_ID,
+ publicClient,
+ walletClient,
+ });
+ }
+
+ async function connect() {
+ if (!window.ethereum) {
+ logLine('no injected wallet found — install MetaMask, Rabby, or similar.', 'err');
+ return;
+ }
+ try {
+ logLine('requesting accounts…', 'info');
+ const accts = await window.ethereum.request({ method: 'eth_requestAccounts' });
+ connectedAddress = accts[0] ? getAddress(accts[0]) : null;
+ const chainHex = await window.ethereum.request({ method: 'eth_chainId' });
+ connectedChainId = parseInt(chainHex, 16);
+ await rebuildClients();
+ logLine(`connected ${connectedAddress} on chain ${connectedChainId}`, 'ok');
+ if (connectedChainId !== BASE_SEPOLIA_CHAIN_ID) {
+ logLine(`wrong chain (${connectedChainId}) — switch to Base Sepolia (84532) to continue.`, 'err');
+ }
+ updateWalletUI();
+ hydrateFromCache();
+ } catch (err) {
+ logLine(`connect failed: ${err.shortMessage || err.message}`, 'err');
+ }
+ }
+
+ async function switchChain() {
+ if (!window.ethereum) return;
+ try {
+ await window.ethereum.request({
+ method: 'wallet_switchEthereumChain',
+ params: [{ chainId: BASE_SEPOLIA_HEX }],
+ });
+ } catch (err) {
+ if (err.code === 4902 || /Unrecognized chain/i.test(err.message || '')) {
+ try {
+ await window.ethereum.request({
+ method: 'wallet_addEthereumChain',
+ params: [{
+ chainId: BASE_SEPOLIA_HEX,
+ chainName: 'Base Sepolia',
+ nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
+ rpcUrls: [BASE_SEPOLIA_RPC],
+ blockExplorerUrls: [BASESCAN_BASE],
+ }],
+ });
+ } catch (addErr) {
+ logLine(`add chain failed: ${addErr.message}`, 'err');
+ return;
+ }
+ } else {
+ logLine(`switch chain failed: ${err.message}`, 'err');
+ return;
+ }
+ }
+ const chainHex = await window.ethereum.request({ method: 'eth_chainId' });
+ connectedChainId = parseInt(chainHex, 16);
+ await rebuildClients();
+ logLine(`now on chain ${connectedChainId}`, connectedChainId === BASE_SEPOLIA_CHAIN_ID ? 'ok' : 'err');
+ updateWalletUI();
+ }
+
+ if (window.ethereum) {
+ window.ethereum.on?.('chainChanged', async (hex) => {
+ connectedChainId = parseInt(hex, 16);
+ await rebuildClients();
+ updateWalletUI();
+ logLine(`chainChanged → ${connectedChainId}`, 'info');
+ });
+ window.ethereum.on?.('accountsChanged', async (accts) => {
+ connectedAddress = accts[0] ? getAddress(accts[0]) : null;
+ await rebuildClients();
+ updateWalletUI();
+ renderWithdrawButton();
+ logLine(`accountsChanged → ${connectedAddress || 'none'}`, 'info');
+ });
+ }
+
+ $('connect-btn').addEventListener('click', connect);
+ $('switch-btn').addEventListener('click', switchChain);
+ $('wallet-pill').addEventListener('click', () => {
+ if (!connectedAddress) return;
+ navigator.clipboard.writeText(connectedAddress);
+ logLine(`copied ${connectedAddress}`, 'info');
+ });
+
+ // --- create split ---
+ $('create-btn').addEventListener('click', async () => {
+ if (connectedChainId !== BASE_SEPOLIA_CHAIN_ID) {
+ logLine('refusing to write — wallet is not on Base Sepolia.', 'err');
+ return;
+ }
+ if (!splitsClient) {
+ logLine('no splits client — connect wallet first.', 'err');
+ return;
+ }
+ try {
+ const checksummed = recipients.map((r) => ({
+ address: getAddress(r.address),
+ percentAllocation: Number(r.percentAllocation),
+ }));
+ logLine(`creating pull split with ${checksummed.length} recipient(s)…`, 'info');
+ $('create-btn').disabled = true;
+ $('create-btn').textContent = 'Waiting for wallet…';
+
+ const result = await splitsClient.createSplit({
+ recipients: checksummed,
+ distributorFeePercent: 0,
+ totalAllocationPercent: 100,
+ splitType: 'pull',
+ ownerAddress: zeroAddress, // immutable — no owner can update recipients
+ creatorAddress: connectedAddress,
+ });
+
+ splitAddress = getAddress(result.splitAddress);
+ logLine(`✓ split deployed at ${splitAddress}`, 'ok');
+ saveCache({
+ splitAddress,
+ recipients: checksummed,
+ chainId: BASE_SEPOLIA_CHAIN_ID,
+ creator: connectedAddress,
+ createdAt: Date.now(),
+ });
+ renderSplitInfo();
+ showFundCard();
+ showInspectCard();
+ await refreshBalance();
+ } catch (err) {
+ logLine(`create split failed: ${err.shortMessage || err.message}`, 'err');
+ } finally {
+ $('create-btn').textContent = 'Deploy immutable pull split';
+ updateCreateBtn();
+ }
+ });
+
+ $('forget-btn').addEventListener('click', () => {
+ clearCache();
+ splitAddress = null;
+ $('split-info').innerHTML = '';
+ $('forget-btn').style.display = 'none';
+ $('fund-card').style.display = 'none';
+ $('inspect-card').style.display = 'none';
+ logLine('forgot cached split — you can deploy a new one.', 'info');
+ });
+
+ function renderSplitInfo() {
+ if (!splitAddress) {
+ $('split-info').innerHTML = '';
+ $('forget-btn').style.display = 'none';
+ return;
+ }
+ $('forget-btn').style.display = '';
+ const baseScanUrl = `${BASESCAN_BASE}/address/${splitAddress}`;
+ const splitsUrl = `${SPLITS_APP_BASE}/accounts/${splitAddress}/?chainId=${BASE_SEPOLIA_CHAIN_ID}`;
+ $('split-info').innerHTML = `
+ <div class="notice ok">
+ Split contract is live and <b>immutable</b> on Base Sepolia.
+ </div>
+ <dl class="kv">
+ <dt>Address</dt>
+ <dd>
+ <a class="copy-addr" href="${baseScanUrl}" target="_blank" rel="noopener">${splitAddress}</a>
+ &middot; <a href="${splitsUrl}" target="_blank" rel="noopener">view on app.splits.org</a>
+ </dd>
+ <dt>Type</dt>
+ <dd>pull · distributorFee 0% · owner ${zeroAddress}</dd>
+ <dt>Recipients</dt>
+ <dd>${recipients.length} address(es) — sum 100%</dd>
+ </dl>
+ `;
+ $('fund-target').value = splitAddress;
+ }
+
+ // --- fund ---
+ function showFundCard() { $('fund-card').style.display = ''; }
+
+ $('fund-btn').addEventListener('click', async () => {
+ if (connectedChainId !== BASE_SEPOLIA_CHAIN_ID) {
+ logLine('refusing to write — wallet is not on Base Sepolia.', 'err');
+ return;
+ }
+ if (!walletClient || !splitAddress) {
+ logLine('connect wallet and create a split first.', 'err');
+ return;
+ }
+ const raw = $('fund-amount').value;
+ let valueWei;
+ try { valueWei = parseEther(String(raw)); } catch {
+ logLine(`invalid ETH amount: ${raw}`, 'err');
+ return;
+ }
+ if (valueWei <= 0n) {
+ logLine('amount must be > 0', 'err');
+ return;
+ }
+ try {
+ $('fund-btn').disabled = true;
+ $('fund-btn').textContent = 'Waiting for wallet…';
+ logLine(`sending ${raw} ETH → ${splitAddress}…`, 'info');
+ const hash = await walletClient.sendTransaction({
+ to: splitAddress,
+ value: valueWei,
+ });
+ logLine(`tx submitted: ${hash}`, 'info');
+ $('fund-result').innerHTML = `
+ <div class="notice">
+ Tx submitted &middot;
+ <a href="${BASESCAN_BASE}/tx/${hash}" target="_blank" rel="noopener">${hash.slice(0, 14)}…</a>
+ &middot; waiting 1 confirmation…
+ </div>
+ `;
+ const receipt = await publicClient.waitForTransactionReceipt({ hash });
+ logLine(`✓ funded (block ${receipt.blockNumber}, status ${receipt.status})`, 'ok');
+ $('fund-result').innerHTML = `
+ <div class="notice ok">
+ ✓ ${escapeHtml(raw)} ETH sent to split &middot;
+ <a href="${BASESCAN_BASE}/tx/${hash}" target="_blank" rel="noopener">${hash.slice(0, 14)}…</a>
+ </div>
+ `;
+ showInspectCard();
+ await refreshBalance();
+ } catch (err) {
+ logLine(`fund failed: ${err.shortMessage || err.message}`, 'err');
+ $('fund-result').innerHTML = `<div class="notice err">${escapeHtml(err.shortMessage || err.message)}</div>`;
+ } finally {
+ $('fund-btn').disabled = false;
+ $('fund-btn').textContent = 'Send test payment';
+ }
+ });
+
+ // --- inspect & distribute ---
+ function showInspectCard() { $('inspect-card').style.display = ''; }
+
+ $('refresh-btn').addEventListener('click', () => refreshBalance());
+
+ async function refreshBalance() {
+ if (!splitAddress) return;
+ try {
+ const bal = await publicClient.getBalance({ address: splitAddress });
+ renderInspect(bal);
+ } catch (err) {
+ logLine(`balance read failed: ${err.shortMessage || err.message}`, 'err');
+ }
+ }
+
+ function renderInspect(balanceWei) {
+ const ethStr = formatEther(balanceWei);
+ const cells = recipients.map((r) => {
+ const pct = Number(r.percentAllocation) || 0;
+ // projected payout = balance × pct / 100, integer division on bigint
+ const projWei = (balanceWei * BigInt(Math.round(pct * 1e6))) / BigInt(1e8);
+ const isUser = connectedAddress && r.address.toLowerCase() === connectedAddress.toLowerCase();
+ return `
+ <tr>
+ <td title="${escapeHtml(r.address)}">${shortAddr(r.address)}${isUser ? ' <span class="pill" style="font-size:10px;padding:1px 6px">you</span>' : ''}</td>
+ <td>${pct.toFixed(2)} %</td>
+ <td>${formatEther(projWei)} ETH</td>
+ </tr>
+ `;
+ }).join('');
+ $('inspect-body').innerHTML = `
+ <dl class="kv">
+ <dt>Split address</dt>
+ <dd><a class="copy-addr" href="${BASESCAN_BASE}/address/${splitAddress}" target="_blank" rel="noopener">${splitAddress}</a></dd>
+ <dt>Current balance</dt>
+ <dd>${ethStr} ETH (${balanceWei.toString()} wei)</dd>
+ </dl>
+ <table style="margin-top:14px">
+ <thead><tr><th>Recipient</th><th>Share</th><th>Projected payout</th></tr></thead>
+ <tbody>${cells}</tbody>
+ </table>
+ <p style="margin-top:10px;color:#8a8d98;font-size:12px">
+ Pull splits route funds through the Splits Warehouse. After you
+ click <b>Distribute</b>, each recipient must call
+ <code>warehouse.withdraw</code> to claim. If your connected
+ wallet matches a recipient, a <b>Withdraw your share</b> button
+ appears below.
+ </p>
+ `;
+ renderWithdrawButton();
+ }
+
+ function renderWithdrawButton() {
+ const btn = $('withdraw-btn');
+ if (!btn || !splitAddress) return;
+ const isRecipient = connectedAddress && recipients.some(
+ (r) => isAddress(r.address) && r.address.toLowerCase() === connectedAddress.toLowerCase(),
+ );
+ btn.style.display = isRecipient ? '' : 'none';
+ }
+
+ $('distribute-btn').addEventListener('click', async () => {
+ if (connectedChainId !== BASE_SEPOLIA_CHAIN_ID) {
+ logLine('refusing to write — wallet is not on Base Sepolia.', 'err');
+ return;
+ }
+ if (!splitsClient || !splitAddress) {
+ logLine('connect wallet and create a split first.', 'err');
+ return;
+ }
+ try {
+ $('distribute-btn').disabled = true;
+ $('distribute-btn').textContent = 'Waiting for wallet…';
+ logLine('calling splitV2.distribute(NATIVE_TOKEN_ADDRESS)…', 'info');
+ const checksummed = recipients.map((r) => ({
+ address: getAddress(r.address),
+ percentAllocation: Number(r.percentAllocation),
+ }));
+ // We pass `splitFields` so the SDK does not need to query a
+ // subgraph (Base Sepolia subgraph requires an API key). The
+ // on-chain `ownership` is the bigint allocation; for total
+ // = 100% and PERCENTAGE_SCALE = 1e6, each recipient's
+ // ownership = pct * 1e4.
+ const PERCENTAGE_SCALE = 1_000_000n;
+ const splitFields = {
+ distributorFeePercent: 0,
+ recipients: checksummed.map((r) => ({
+ recipient: { address: r.address },
+ ownership: BigInt(Math.round(r.percentAllocation * 1e4)),
+ percentAllocation: r.percentAllocation,
+ })),
+ };
+ // sanity-check totals match PERCENTAGE_SCALE
+ const total = splitFields.recipients.reduce((a, x) => a + x.ownership, 0n);
+ if (total !== PERCENTAGE_SCALE) {
+ throw new Error(`internal: allocations ${total} ≠ 1e6 scale`);
+ }
+ const res = await splitsClient.distribute({
+ splitAddress,
+ tokenAddress: NATIVE,
+ distributorAddress: connectedAddress,
+ splitFields,
+ });
+ logLine(`✓ distribute event emitted in tx ${res?.event?.transactionHash || ''}`.trim(), 'ok');
+ await refreshBalance();
+ } catch (err) {
+ logLine(`distribute failed: ${err.shortMessage || err.message}`, 'err');
+ } finally {
+ $('distribute-btn').disabled = false;
+ $('distribute-btn').textContent = 'Distribute to recipients';
+ }
+ });
+
+ $('withdraw-btn').addEventListener('click', async () => {
+ if (connectedChainId !== BASE_SEPOLIA_CHAIN_ID) {
+ logLine('refusing to write — wallet is not on Base Sepolia.', 'err');
+ return;
+ }
+ if (!walletClient || !connectedAddress) {
+ logLine('connect wallet first.', 'err');
+ return;
+ }
+ try {
+ $('withdraw-btn').disabled = true;
+ $('withdraw-btn').textContent = 'Waiting for wallet…';
+ logLine('calling warehouse.withdraw(self, NATIVE)…', 'info');
+ // Lazy-load WarehouseClient — keeps the createSplit happy
+ // path lean for users who never withdraw on this device.
+ const { WarehouseClient } = await import('@0xsplits/splits-sdk');
+ const wh = new WarehouseClient({
+ chainId: BASE_SEPOLIA_CHAIN_ID,
+ publicClient,
+ walletClient,
+ });
+ const res = await wh.withdraw({
+ ownerAddress: connectedAddress,
+ tokenAddress: NATIVE,
+ });
+ logLine(`✓ withdraw event ${res?.event?.transactionHash || ''}`.trim(), 'ok');
+ } catch (err) {
+ logLine(`withdraw failed: ${err.shortMessage || err.message}`, 'err');
+ } finally {
+ $('withdraw-btn').disabled = false;
+ $('withdraw-btn').textContent = 'Withdraw your share';
+ }
+ });
+
+ // --- cache hydration ---
+ function hydrateFromCache() {
+ const c = loadCache();
+ if (!c || c.chainId !== BASE_SEPOLIA_CHAIN_ID || !isAddress(c.splitAddress)) return;
+ splitAddress = getAddress(c.splitAddress);
+ if (Array.isArray(c.recipients) && c.recipients.length) {
+ recipients = c.recipients.map((r) => ({
+ address: r.address,
+ percentAllocation: Number(r.percentAllocation),
+ }));
+ renderRecipients();
+ }
+ logLine(`restored cached split ${splitAddress}`, 'info');
+ renderSplitInfo();
+ showFundCard();
+ showInspectCard();
+ refreshBalance();
+ }
+
+ // Try to silently pre-detect an already-permitted account so the
+ // "Connect" button shows the connected state on page refresh.
+ (async () => {
+ if (!window.ethereum) return;
+ try {
+ const accts = await window.ethereum.request({ method: 'eth_accounts' });
+ if (accts && accts[0]) {
+ connectedAddress = getAddress(accts[0]);
+ const chainHex = await window.ethereum.request({ method: 'eth_chainId' });
+ connectedChainId = parseInt(chainHex, 16);
+ await rebuildClients();
+ updateWalletUI();
+ hydrateFromCache();
+ logLine(`auto-restored session: ${connectedAddress} on chain ${connectedChainId}`, 'info');
+ } else {
+ // No connected account — still try to hydrate so the
+ // user can see their previous split address.
+ hydrateFromCache();
+ }
+ } catch {
+ hydrateFromCache();
+ }
+ })();
+ </script>
+ </body>
+</html>
diff --git a/tests/avatar-bake.test.js b/tests/avatar-bake.test.js
index 03831bcc1..f24b52eb6 100644
--- a/tests/avatar-bake.test.js
+++ b/tests/avatar-bake.test.js
@@ -17,6 +17,7 @@
import { describe, it, expect, beforeAll } from 'vitest';
import { Document, NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { MeshoptDecoder } from 'meshoptimizer';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
@@ -112,7 +113,12 @@ beforeAll(async () => {
// ── Helpers ────────────────────────────────────────────────────────────────
async function inspect(glbBytes) {
- const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ // bakeAppearance now ships meshopt-compressed buffers, so the test reader
+ // must register the meshopt decoder dependency to round-trip them.
+ await MeshoptDecoder.ready;
+ const io = new NodeIO()
+ .registerExtensions(ALL_EXTENSIONS)
+ .registerDependencies({ 'meshopt.decoder': MeshoptDecoder });
return io.readBinary(new Uint8Array(glbBytes));
}