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: avatar accessories + coin launchpad + agent-edit + avatar-sdk

nirholas457c92e8d313
diff --git a/.gitignore b/.gitignore
index aa7513395..37f1a83e0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -64,6 +64,8 @@ scripts/pump-usdc-race.mjs
*.b58.txt
*-pump-wallet.json
.fresh-pump-wallet.json
+.coin-keypair-*.json
+.coin-metadata-*.json
wallets/
.wallets/
x402-test-wallets/
diff --git a/README.md b/README.md
index 0103075de..7e0e88a17 100644
--- a/README.md
+++ b/README.md
@@ -119,7 +119,7 @@ The following environment variables are required. Copy `.env.example` to `.env.l
| `JWT_SECRET` | Secret key for signing JWTs. |
| `ANTHROPIC_API_KEY` | API key for the Anthropic (Claude) LLM. |
| `OPENROUTER_API_KEY` | API key for the OpenRouter free model proxy. |
-| `VITE_RPM_SUBDOMAIN` | Ready Player Me subdomain for the avatar creator. |
+| `VITE_CHARACTER_STUDIO_URL` | Origin where the Character Studio avatar builder iframe is hosted. Defaults to `http://localhost:5173` in dev. |
| `VITE_PRIVY_APP_ID` | Privy app ID for client-side wallet authentication. |
| `PRIVY_APP_ID` | Privy app ID for server-side token verification. |
| `AVATURN_API_KEY` | API key for the Avaturn photo-to-avatar pipeline. |
@@ -312,7 +312,7 @@ If you want to support the project — compute credits, grants, partnerships, or
- OAuth 2.1 server (RFC 6749 + PKCE, RFC 7591 dynamic registration, RFC 7009 revocation, RFC 7662 introspection, RFC 8414 discovery)
- Developer API keys with scope and expiry
- MCP (Model Context Protocol) over HTTP with JSON-RPC 2.0 for tool-calling from external AI systems
-- Ready Player Me, Avaturn (photo-to-avatar), and Privy (embedded wallet) integrations
+- Avaturn (photo-to-avatar), Character Studio (in-browser builder), and Privy (embedded wallet) integrations
- DCA strategy execution and on-chain subscription scheduling via cron jobs
- OpenAPI 3.1 spec generated at `/openapi.json`
@@ -1473,7 +1473,7 @@ WEB3_STORAGE_TOKEN=... # Fallback
### Optional (Frontend, prefixed `VITE_`)
```env
-VITE_RPM_SUBDOMAIN=demo # Ready Player Me subdomain
+VITE_CHARACTER_STUDIO_URL=https://studio.three.ws # Avatar builder iframe origin
VITE_PRIVY_APP_ID=...
VITE_AVATURN_EDITOR_URL=https://editor.avaturn.me/
VITE_AVATURN_DEVELOPER_ID=...
diff --git a/agent-edit.html b/agent-edit.html
index ea7e12c46..f17fe3ec6 100644
--- a/agent-edit.html
+++ b/agent-edit.html
@@ -517,6 +517,110 @@
padding: 0.15rem 0.382rem;
border-radius: 4px;
}
+ .avatar-create-tile {
+ border-style: dashed;
+ border-color: rgba(147, 197, 253, 0.4);
+ background: rgba(59, 130, 246, 0.04);
+ color: rgba(147, 197, 253, 0.85);
+ }
+ .avatar-create-tile:hover {
+ border-color: rgba(147, 197, 253, 0.85);
+ background: rgba(59, 130, 246, 0.10);
+ }
+ .avatar-create-icon {
+ font-size: 1.75rem;
+ font-weight: 300;
+ color: rgba(147, 197, 253, 0.85);
+ }
+ .avatar-create-menu {
+ position: absolute;
+ z-index: 1000;
+ min-width: 220px;
+ background: #0d0d18;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 8px;
+ padding: 0.382rem;
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45);
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+ }
+ .avatar-create-menu button[role="menuitem"] {
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+ text-align: left;
+ padding: 0.5rem 0.75rem;
+ background: transparent;
+ border: 0;
+ color: #eaeaf0;
+ cursor: pointer;
+ border-radius: 6px;
+ font-family: inherit;
+ }
+ .avatar-create-menu button[role="menuitem"]:hover {
+ background: rgba(255, 255, 255, 0.06);
+ }
+ .avatar-create-menu .acm-title { font-size: 0.875rem; }
+ .avatar-create-menu .acm-sub { font-size: 0.7rem; color: rgba(255, 255, 255, 0.5); }
+
+ .anims-picker-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));
+ gap: 0.5rem;
+ }
+ .anim-tile {
+ position: relative;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 8px;
+ padding: 0.5rem 0.382rem;
+ cursor: pointer;
+ font-family: inherit;
+ color: rgba(255, 255, 255, 0.85);
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+ align-items: center;
+ text-align: center;
+ transition: border-color 0.15s, background 0.15s, transform 0.1s;
+ }
+ .anim-tile:hover { border-color: rgba(59, 130, 246, 0.5); }
+ .anim-tile:active { transform: scale(0.97); }
+ .anim-tile.selected {
+ border-color: #3b82f6;
+ background: rgba(59, 130, 246, 0.12);
+ }
+ .anim-tile-icon {
+ font-size: 1.4rem;
+ line-height: 1;
+ margin-bottom: 0.15rem;
+ }
+ .anim-tile-name {
+ font-size: 0.7rem;
+ color: rgba(255, 255, 255, 0.7);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ max-width: 100%;
+ }
+ .anim-tile-check {
+ position: absolute;
+ top: 0.25rem;
+ right: 0.25rem;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: #3b82f6;
+ color: #fff;
+ font-size: 0.55rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0;
+ transition: opacity 0.15s;
+ }
+ .anim-tile.selected .anim-tile-check { opacity: 1; }
.edit-tab:focus-visible,
.btn-primary:focus-visible,
@@ -950,6 +1054,18 @@
<div id="avatar-picker-list" class="avatar-picker-list">
<div class="no-named-mats">Loading avatars…</div>
</div>
+
+ <div class="outfit-header" style="margin-top: 2rem;">
+ <h2 class="outfit-title">Animations</h2>
+ <button type="button" class="btn-reset-all" id="anims-save" disabled>Save selection</button>
+ </div>
+ <p class="note" style="font-size: 0.764rem; color: rgba(255,255,255,0.4); margin: 0 0 1rem;">
+ Pick which Mixamo clips this agent can play. They&rsquo;re also available to skills via <code>playAnimation</code>.
+ </p>
+ <div id="anims-picker-grid" class="anims-picker-grid">
+ <div class="no-named-mats">Loading animations…</div>
+ </div>
+ <span class="form-status" id="anims-status" role="status" aria-live="polite"></span>
</div>
</section>
<!-- Publish tab -->
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.js
index 922da5e42..bfd17b15b 100644
--- a/api/_lib/avatars.js
+++ b/api/_lib/avatars.js
@@ -1,6 +1,7 @@
// Avatar service — CRUD + quota enforcement + URL resolution.
// Keep handler code small by routing through this.
+import { createHash } from 'node:crypto';
import { sql } from './db.js';
import { publicUrl, presignGet, deleteObject } from './r2.js';
import { defaultStorageMode } from './storage-mode.js';
@@ -27,6 +28,8 @@ export async function listAvatars({
params.push(limit + 1);
const rows = await sql(
`select a.id, a.owner_id, a.slug, a.name, a.description, a.storage_key, a.thumbnail_key,
+ a.usdz_key, a.halfbody_key,
+ a.appearance, a.appearance_hash, a.baked_storage_key, a.baked_at,
a.size_bytes, a.content_type, a.source, a.visibility, a.tags, a.version,
a.created_at, a.updated_at, a.parent_avatar_id,
ai.id as agent_id, ai.wallet_address as agent_wallet_address
@@ -86,35 +89,80 @@ export async function createAvatar({ userId, input, storageKey }) {
insert into avatars (
owner_id, slug, name, description, storage_key, size_bytes, content_type,
source, source_meta, visibility, tags, checksum_sha256, parent_avatar_id,
- storage_mode
+ storage_mode, appearance
) values (
${userId}, ${finalSlug}, ${input.name}, ${input.description ?? null},
${storageKey}, ${input.size_bytes}, ${input.content_type},
${input.source}, ${JSON.stringify(input.source_meta)}::jsonb,
${input.visibility}, ${input.tags}, ${input.checksum_sha256 ?? null},
${input.parent_avatar_id ?? null},
- ${JSON.stringify(storageMode)}::jsonb
+ ${JSON.stringify(storageMode)}::jsonb,
+ ${input.appearance ? JSON.stringify(input.appearance) : null}::jsonb
) returning *
`;
return decorate(row);
}
export async function updateAvatar({ id, userId, patch }) {
+ const hasAppearance = Object.prototype.hasOwnProperty.call(patch, 'appearance');
+ const hasBaked = Object.prototype.hasOwnProperty.call(patch, 'baked_storage_key');
+
if (
patch.name === undefined &&
patch.description === undefined &&
patch.visibility === undefined &&
- patch.tags === undefined
+ patch.tags === undefined &&
+ patch.thumbnail_key === undefined &&
+ patch.usdz_key === undefined &&
+ patch.halfbody_key === undefined &&
+ !hasAppearance &&
+ !hasBaked
) {
return getAvatar({ id, requesterId: userId });
}
+ // Storage keys are scoped under u/<userId>/ — refuse to write keys that
+ // point outside the caller's namespace, which would let one user claim an
+ // object uploaded into another user's prefix.
+ for (const k of ['thumbnail_key', 'usdz_key', 'halfbody_key', 'baked_storage_key']) {
+ const v = patch[k];
+ if (v !== undefined && v !== null && !v.startsWith(`u/${userId}/`)) {
+ throw Object.assign(new Error(`${k} must live under u/${userId}/`), {
+ status: 400,
+ code: 'invalid_storage_key',
+ });
+ }
+ }
+ // Two distinct write paths so the JSON-only PATCH stays cheap and so a bake
+ // completion can land its three fields atomically without re-reading the row.
+ if (hasBaked) {
+ const [row] = await sql`
+ update avatars set
+ baked_storage_key = ${patch.baked_storage_key ?? null},
+ appearance_hash = ${patch.appearance_hash ?? null},
+ baked_at = ${patch.baked_storage_key ? sql`now()` : null},
+ updated_at = now()
+ where id = ${id} and owner_id = ${userId} and deleted_at is null
+ returning *
+ `;
+ return row ? decorate(row) : null;
+ }
+
// Coalesce-style update keeps the statement static and safe against dynamic composition.
+ // `appearance` uses the explicit `hasAppearance` flag because null is a valid value
+ // (means "clear the dress-up state"); coalesce would let null fall through unchanged.
const [row] = await sql`
update avatars set
- name = coalesce(${patch.name ?? null}, name),
- description = coalesce(${patch.description ?? null}, description),
- visibility = coalesce(${patch.visibility ?? null}, visibility),
- tags = coalesce(${patch.tags ?? null}::text[], tags)
+ name = coalesce(${patch.name ?? null}, name),
+ description = coalesce(${patch.description ?? null}, description),
+ visibility = coalesce(${patch.visibility ?? null}, visibility),
+ tags = coalesce(${patch.tags ?? null}::text[], tags),
+ thumbnail_key = coalesce(${patch.thumbnail_key ?? null}, thumbnail_key),
+ usdz_key = coalesce(${patch.usdz_key ?? null}, usdz_key),
+ halfbody_key = coalesce(${patch.halfbody_key ?? null}, halfbody_key),
+ appearance = case when ${hasAppearance}::bool
+ then ${patch.appearance ? JSON.stringify(patch.appearance) : null}::jsonb
+ else appearance end,
+ updated_at = now()
where id = ${id} and owner_id = ${userId} and deleted_at is null
returning *
`;
@@ -164,7 +212,10 @@ export async function searchPublicAvatars({ q, tag, limit = 24, cursor, withTota
}
params.push(limit + 1);
const rows = await sql(
- `select id, owner_id, slug, name, description, storage_key, thumbnail_key, size_bytes,
+ `select id, owner_id, slug, name, description, storage_key, thumbnail_key,
+ usdz_key, halfbody_key,
+ appearance, appearance_hash, baked_storage_key, baked_at,
+ size_bytes,
content_type, source, visibility, tags, view_count, created_at
from avatars where ${conds.join(' and ')}
order by created_at desc limit $${params.length}`,
@@ -190,16 +241,30 @@ export async function searchPublicAvatars({ q, tag, limit = 24, cursor, withTota
}
export async function resolveAvatarUrl(row, { expiresIn = 600 } = {}) {
+ const key = _servedStorageKey(row);
if (row.visibility === 'public' || row.visibility === 'unlisted') {
- return { url: publicUrl(row.storage_key), cdn: true };
+ return { url: publicUrl(key), cdn: true };
}
return {
- url: await presignGet({ key: row.storage_key, expiresIn }),
+ url: await presignGet({ key, expiresIn }),
cdn: false,
expires_in: expiresIn,
};
}
+// Public so the PATCH handler can decide whether to bake without re-reading.
+export function isBakedFresh(row) {
+ if (!row.baked_storage_key || !row.appearance_hash || !row.appearance) return false;
+ return row.appearance_hash === _hashAppearance(row.appearance);
+}
+
+export { _hashAppearance as appearanceHash };
+
+function _servedStorageKey(row) {
+ if (isBakedFresh(row)) return row.baked_storage_key;
+ return row.storage_key;
+}
+
// ── quotas ───────────────────────────────────────────────────────────────────
export async function enforceQuotas(userId, incomingBytes) {
const rows = await sql`
@@ -234,6 +299,9 @@ export async function enforceQuotas(userId, incomingBytes) {
// ── helpers ──────────────────────────────────────────────────────────────────
function decorate(row) {
+ const bakedFresh = isBakedFresh(row);
+ const servedStorageKey = _servedStorageKey(row);
+
return {
id: row.id,
owner_id: row.owner_id,
@@ -252,16 +320,46 @@ function decorate(row) {
created_at: row.created_at,
updated_at: row.updated_at,
model_url:
+ row.visibility === 'public' || row.visibility === 'unlisted'
+ ? publicUrl(servedStorageKey)
+ : null,
+ base_model_url:
row.visibility === 'public' || row.visibility === 'unlisted'
? publicUrl(row.storage_key)
: null,
parent_avatar_id: row.parent_avatar_id || null,
thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,
+ usdz_url: row.usdz_key ? publicUrl(row.usdz_key) : null,
+ halfbody_url: row.halfbody_key ? publicUrl(row.halfbody_key) : null,
+ appearance: row.appearance || null,
+ appearance_hash: row.appearance_hash || null,
+ baked: bakedFresh,
+ baked_at: row.baked_at || null,
agent_id: row.agent_id || null,
agent_wallet_address: row.agent_wallet_address || null,
};
}
+// Local copy of the canonical-JSON hash from bake.js so getAvatar()/listAvatars()
+// stay cheap (no @gltf-transform import). Must stay identical to bake.js's
+// appearanceHash() output — change both together.
+function _hashAppearance(appearance) {
+ return createHash('sha256').update(_canonicalize(appearance)).digest('hex');
+}
+function _canonicalize(obj) {
+ if (obj === undefined || obj === null) return 'null';
+ if (typeof obj === 'number') return Number.isFinite(obj) ? String(obj) : 'null';
+ if (typeof obj === 'boolean' || typeof obj === 'string') return JSON.stringify(obj);
+ if (Array.isArray(obj)) return '[' + obj.map(_canonicalize).join(',') + ']';
+ if (typeof obj === 'object') {
+ const keys = Object.keys(obj).sort();
+ return (
+ '{' + keys.map((k) => JSON.stringify(k) + ':' + _canonicalize(obj[k])).join(',') + '}'
+ );
+ }
+ return 'null';
+}
+
// Hide owner_id and storage_key from callers who don't own the row. The raw
// user UUID is the primary segment of R2 storage keys, so leaking either helps
// an attacker guess object paths in other users' namespaces.
diff --git a/api/_lib/bake.js b/api/_lib/bake.js
new file mode 100644
index 000000000..d8b9b284a
--- /dev/null
+++ b/api/_lib/bake.js
@@ -0,0 +1,337 @@
+// Server-side avatar appearance baker.
+//
+// Takes a base GLB + an `appearance` record and produces a derived GLB where:
+// - outfit morph bindings + raw morph overrides are baked into node-level weights
+// - bone-attached accessory GLBs (hats, glasses, earrings) are merged in and
+// re-parented under the named skeleton bone (Head, etc).
+//
+// The output is a single glTF 2.0 binary — every viewer (three.js, model-viewer,
+// Babylon.js, Unreal/Unity importers) sees the fully dressed avatar with no
+// special runtime code. Mirrors Ready Player Me's "baked URL" output model.
+//
+// Bone name matching is tolerant of mixamorig:, CC_Base_, and rig_ prefixes so
+// avatars from Mixamo / Character Creator / custom rigs all work.
+
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { mergeDocuments, prune, dedup, unpartition } from '@gltf-transform/functions';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { createHash } from 'node:crypto';
+import { isValidPresetId } from './accessories.js';
+import { env } from './env.js';
+import { getObjectBuffer, putObject } from './r2.js';
+
+// ── Public API ─────────────────────────────────────────────────────────────
+
+/**
+ * Stable sha256 over the canonical JSON form of `appearance`. Used as the cache
+ * key for baked GLBs — when the hash matches `avatars.appearance_hash`, the
+ * existing `baked_storage_key` is still valid.
+ */
+export function appearanceHash(appearance) {
+ if (!appearance) return null;
+ return createHash('sha256').update(canonicalize(appearance)).digest('hex');
+}
+
+/**
+ * Returns true if the appearance has anything bakeable (outfit, accessories, morphs).
+ * An empty / null appearance bakes to the base GLB unchanged — skip the work.
+ */
+export function isBakeable(appearance) {
+ if (!appearance) return false;
+ if (appearance.outfit) return true;
+ if (Array.isArray(appearance.accessories) && appearance.accessories.length > 0) return true;
+ if (appearance.morphs && Object.keys(appearance.morphs).length > 0) return true;
+ return false;
+}
+
+/**
+ * Bake `appearance` into a copy of the base GLB. Returns Uint8Array of the GLB.
+ *
+ * @param {Uint8Array|Buffer} baseGlbBytes
+ * @param {object} appearance — { outfit?, accessories?, morphs? }
+ * @returns {Promise<Uint8Array>}
+ */
+export async function bakeAppearance(baseGlbBytes, appearance) {
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ const doc = await io.readBinary(toUint8(baseGlbBytes));
+
+ const presets = await loadPresets();
+ const byId = new Map(presets.map((p) => [p.id, p]));
+
+ const presetIds = [];
+ if (appearance?.outfit && isValidPresetId(appearance.outfit)) presetIds.push(appearance.outfit);
+ for (const id of appearance?.accessories || []) {
+ if (isValidPresetId(id)) presetIds.push(id);
+ }
+
+ // 1) Aggregate morph weights: outfit.morphBinding + appearance.morphs.
+ // appearance.morphs wins on key conflict (user override beats preset).
+ const morphMap = {};
+ for (const id of presetIds) {
+ const p = byId.get(id);
+ if (p?.morphBinding) Object.assign(morphMap, p.morphBinding);
+ }
+ if (appearance?.morphs) Object.assign(morphMap, appearance.morphs);
+ if (Object.keys(morphMap).length > 0) applyMorphs(doc, morphMap);
+
+ // 2) Bone-mounted accessory GLBs.
+ for (let i = 0; i < presetIds.length; i++) {
+ const id = presetIds[i];
+ const preset = byId.get(id);
+ if (!preset?.glbUrl) continue;
+
+ let accessoryBytes;
+ try {
+ accessoryBytes = await loadAccessoryGlb(preset.glbUrl);
+ } catch (err) {
+ console.warn(`[bake] failed to load accessory ${preset.id}: ${err.message}`);
+ continue;
+ }
+
+ const accDoc = await io.readBinary(toUint8(accessoryBytes));
+ const bone = findBone(doc, preset.attachBone);
+ if (!bone) {
+ console.warn(`[bake] bone "${preset.attachBone}" not found for ${preset.id}`);
+ continue;
+ }
+
+ // mergeDocuments copies properties into the target graph — the originals
+ // in accDoc become disconnected. We can't keep refs across the merge, so
+ // rename the accessory's scene roots to a guaranteed-unique tag, merge,
+ // then look them up by name in the merged document. Re-parent under the
+ // target bone and finally restore each node's original name.
+ const accScene =
+ accDoc.getRoot().getDefaultScene() || accDoc.getRoot().listScenes()[0] || null;
+ const accRootSrcs = accScene
+ ? [...accScene.listChildren()]
+ : accDoc
+ .getRoot()
+ .listNodes()
+ .filter((n) => !n.getParentNode());
+
+ const tag = `__bake_${id}_${i}_${Date.now().toString(36)}`;
+ const renamed = accRootSrcs.map((node, idx) => {
+ const original = node.getName();
+ const unique = `${tag}_${idx}`;
+ node.setName(unique);
+ return { unique, original };
+ });
+
+ mergeDocuments(doc, accDoc);
+
+ for (const { unique, original } of renamed) {
+ const node = doc
+ .getRoot()
+ .listNodes()
+ .find((n) => n.getName() === unique);
+ if (!node) {
+ console.warn(`[bake] merged node "${unique}" missing after mergeDocuments`);
+ continue;
+ }
+ // Detach from any scene it landed in after merge.
+ for (const scene of doc.getRoot().listScenes()) {
+ scene.removeChild(node);
+ }
+ bone.addChild(node);
+ node.setName(original);
+ }
+ }
+
+ // 3) Tag + clean.
+ const asset = doc.getRoot().getAsset();
+ asset.generator =
+ (asset.generator || '') + ' / three.ws appearance-baker @gltf-transform';
+ const extras = doc.getRoot().getAsset().extras || {};
+ doc.getRoot().getAsset().extras = {
+ ...extras,
+ bakedAt: new Date().toISOString(),
+ appearance: appearance ?? null,
+ };
+
+ // unpartition() collapses multiple buffers (one from base + one per merged
+ // accessory) into a single buffer — required by the GLB container, which
+ // allows at most one buffer. prune/dedup happen after so they see the final
+ // canonical accessor → buffer layout.
+ await doc.transform(unpartition(), prune(), dedup());
+
+ return io.writeBinary(doc);
+}
+
+/**
+ * Derive the R2 storage key for the baked variant of an avatar.
+ * Path mirrors the base storage layout so all derived files for an avatar stay
+ * grouped by user and slug, and the hash is the cache key so old bakes don't
+ * overwrite mid-flight.
+ */
+export function bakedStorageKeyFor({ baseStorageKey, hash }) {
+ // baseStorageKey is "u/{userId}/{slug}/{ts}.glb"
+ const parts = baseStorageKey.split('/');
+ const base = parts.slice(0, -1).join('/');
+ return `${base}/baked-${hash.slice(0, 16)}.glb`;
+}
+
+/**
+ * End-to-end bake: read the base GLB from R2, apply `appearance`, upload the
+ * resulting GLB to R2 under a hash-keyed path, and return the new key + hash.
+ *
+ * Returns `null` if `appearance` has nothing bakeable (no outfit, accessories,
+ * or morph overrides) — caller should clear the baked fields in that case.
+ *
+ * @param {object} args
+ * @param {string} args.baseStorageKey Existing GLB key in R2 (avatar.storage_key)
+ * @param {object} args.appearance { outfit?, accessories?, morphs? }
+ * @returns {Promise<{baked_storage_key: string, appearance_hash: string, size_bytes: number} | null>}
+ */
+export async function bakeAndUploadAppearance({ baseStorageKey, appearance }) {
+ if (!isBakeable(appearance)) return null;
+
+ const baseBytes = await getObjectBuffer(baseStorageKey);
+ const bakedBytes = await bakeAppearance(baseBytes, appearance);
+ const hash = appearanceHash(appearance);
+ const bakedKey = bakedStorageKeyFor({ baseStorageKey, hash });
+
+ await putObject({
+ key: bakedKey,
+ body: Buffer.from(bakedBytes),
+ contentType: 'model/gltf-binary',
+ metadata: {
+ 'baked-from': baseStorageKey,
+ 'appearance-hash': hash,
+ },
+ });
+
+ return {
+ baked_storage_key: bakedKey,
+ appearance_hash: hash,
+ size_bytes: bakedBytes.byteLength,
+ };
+}
+
+// ── Internals ──────────────────────────────────────────────────────────────
+
+function toUint8(buf) {
+ if (buf instanceof Uint8Array && !Buffer.isBuffer(buf)) return buf;
+ if (Buffer.isBuffer(buf)) return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
+ return new Uint8Array(buf);
+}
+
+function canonBoneName(name) {
+ return String(name || '')
+ .replace(/^mixamorig[_:]?/i, '')
+ .replace(/^CC_Base_/i, '')
+ .replace(/^rig_/i, '')
+ .toLowerCase();
+}
+
+function findBone(doc, targetName) {
+ if (!targetName) return null;
+ const target = String(targetName).toLowerCase();
+ for (const node of doc.getRoot().listNodes()) {
+ const n = node.getName();
+ if (n === targetName) return node;
+ if (canonBoneName(n) === target) return node;
+ }
+ return null;
+}
+
+/**
+ * Apply a name→weight binding to every node whose mesh exposes a matching morph
+ * target. Target names are read from `mesh.extras.targetNames` (KHR convention)
+ * with a fallback to per-primitive extras. Node-level weights override mesh
+ * defaults; setting them here means every renderer sees the baked pose.
+ */
+function applyMorphs(doc, binding) {
+ for (const node of doc.getRoot().listNodes()) {
+ const mesh = node.getMesh();
+ if (!mesh) continue;
+
+ const names = collectTargetNames(mesh);
+ if (!names.length) continue;
+
+ // Start from existing node weights, falling back to mesh defaults, padded
+ // to the target count so we don't lose existing morph pose.
+ const meshWeights = mesh.getWeights() || [];
+ const nodeWeights = node.getWeights() || [];
+ const weights = new Array(names.length);
+ for (let i = 0; i < names.length; i++) {
+ weights[i] = nodeWeights[i] ?? meshWeights[i] ?? 0;
+ }
+
+ let changed = false;
+ for (const [name, weight] of Object.entries(binding)) {
+ const idx = names.indexOf(name);
+ if (idx < 0) continue;
+ weights[idx] = clamp01(weight);
+ changed = true;
+ }
+ if (changed) node.setWeights(weights);
+ }
+}
+
+function collectTargetNames(mesh) {
+ const ext = mesh.getExtras() || {};
+ if (Array.isArray(ext.targetNames) && ext.targetNames.length > 0) return ext.targetNames;
+ for (const prim of mesh.listPrimitives()) {
+ const pExt = prim.getExtras() || {};
+ if (Array.isArray(pExt.targetNames) && pExt.targetNames.length > 0) return pExt.targetNames;
+ }
+ return [];
+}
+
+function clamp01(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return 0;
+ if (v < 0) return 0;
+ if (v > 1) return 1;
+ return v;
+}
+
+let _presetsCache = null;
+async function loadPresets() {
+ if (_presetsCache) return _presetsCache;
+ const file = await readFile(
+ path.resolve(process.cwd(), 'public/accessories/presets.json'),
+ 'utf-8',
+ );
+ _presetsCache = JSON.parse(file);
+ return _presetsCache;
+}
+
+const _accCache = new Map();
+async function loadAccessoryGlb(glbUrl) {
+ if (_accCache.has(glbUrl)) return _accCache.get(glbUrl);
+
+ const fsPath = path.resolve(process.cwd(), 'public' + glbUrl);
+ let buf;
+ try {
+ buf = await readFile(fsPath);
+ } catch (err) {
+ // On Vercel functions, public/ assets may not be bundled with the function.
+ // Fall back to fetching from the deployed site over HTTPS.
+ const base = env.APP_ORIGIN || 'https://three.ws';
+ const r = await fetch(base + glbUrl);
+ if (!r.ok) {
+ throw new Error(`accessory fetch failed: ${base + glbUrl} → ${r.status}`);
+ }
+ buf = Buffer.from(await r.arrayBuffer());
+ }
+ _accCache.set(glbUrl, buf);
+ return buf;
+}
+
+// Canonical JSON for hashing: keys sorted, objects/arrays recursed, primitives
+// serialized stably. NaN/undefined collapse to null so two semantically equal
+// inputs always hash the same regardless of caller key ordering.
+function canonicalize(obj) {
+ if (obj === undefined || obj === null) return 'null';
+ if (typeof obj === 'number') return Number.isFinite(obj) ? String(obj) : 'null';
+ if (typeof obj === 'boolean' || typeof obj === 'string') return JSON.stringify(obj);
+ if (Array.isArray(obj)) return '[' + obj.map(canonicalize).join(',') + ']';
+ if (typeof obj === 'object') {
+ const keys = Object.keys(obj).sort();
+ return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalize(obj[k])).join(',') + '}';
+ }
+ return 'null';
+}
diff --git a/api/_lib/coin/creator-fees.js b/api/_lib/coin/creator-fees.js
new file mode 100644
index 000000000..6d5ad953e
--- /dev/null
+++ b/api/_lib/coin/creator-fees.js
@@ -0,0 +1,144 @@
+// Pump.fun creator-fee claim flow.
+//
+// On every buy/sell of a pump.fun token, the program accrues a small SOL fee
+// into a creator vault (a PDA derived from the launch's `creator` address).
+// The creator can periodically sweep that vault to its associated SOL token
+// account, which we then unwrap (close → SOL) and route to the coin treasury.
+//
+// The SDK call used is `OnlinePumpSdk.collectCoinCreatorFeeInstructions`,
+// which returns the full list of instructions needed (collectCreatorFee on the
+// bonding-curve program + collectCoinCreatorFee on the AMM program for the
+// post-graduation case). We then append a close-account instruction to unwrap
+// the WSOL the program transferred into the creator's WSOL ATA.
+//
+// Idempotency: this transaction is safe to retry — `collectCreatorFee` is a
+// no-op when the vault is empty, and the unwrap close-ATA ix is best-effort
+// (it errors if the ATA doesn't exist yet, but doesn't break the rest).
+//
+// Returns: { tx_signature, claimed_lamports, was_empty } so the caller can
+// record the inflow against coin_launches.total_claimed_lamports.
+
+import {
+ ComputeBudgetProgram,
+ PublicKey,
+ Transaction,
+} from '@solana/web3.js';
+import { NATIVE_MINT, getAssociatedTokenAddressSync, createCloseAccountInstruction } from '@solana/spl-token';
+
+import { getConnection, getPumpSdk, solanaPubkey } from '../pump.js';
+
+const PRIORITY_MICRO_LAMPORTS = 100_000;
+
+/**
+ * Build + sign + submit a creator-fee claim for one coin launch.
+ *
+ * @param {object} opts
+ * @param {object} opts.coin coin_launches row
+ * @param {import('@solana/web3.js').Keypair} opts.coinCreator
+ * keypair whose publicKey === coin.creator_wallet
+ * @param {import('@solana/web3.js').Keypair} opts.treasury
+ * keypair that pays fees + receives unwrapped SOL
+ * (typically same as coinCreator for v1 unless
+ * the deployer chose to separate roles)
+ * @returns {Promise<{ tx_signature: string|null, claimed_lamports: bigint, was_empty: boolean }>}
+ */
+export async function claimCreatorFees({ coin, coinCreator, treasury }) {
+ const network = coin.network || 'mainnet';
+ const connection = getConnection({ network });
+ const { sdk } = await getPumpSdk({ network });
+
+ const creatorPk = coinCreator.publicKey;
+ const treasuryPk = treasury.publicKey;
+ if (creatorPk.toBase58() !== coin.creator_wallet) {
+ throw new Error(
+ `creator key mismatch: keypair pubkey=${creatorPk.toBase58()} but coin.creator_wallet=${coin.creator_wallet}`,
+ );
+ }
+
+ // Snapshot the creator's lamport balance BEFORE the claim. The collect-fee
+ // instructions move SOL through the creator's WSOL ATA — to count what
+ // landed, we either parse the program event or simply diff the creator's
+ // native balance after the close-account unwrap. The diff approach is
+ // robust against SDK version drift.
+ const balanceBefore = BigInt(await connection.getBalance(creatorPk, 'confirmed'));
+
+ const ixs = await sdk.collectCoinCreatorFeeInstructions(creatorPk, treasuryPk);
+ if (!Array.isArray(ixs) || ixs.length === 0) {
+ return { tx_signature: null, claimed_lamports: 0n, was_empty: true };
+ }
+
+ // Append close-account on the creator's WSOL ATA to unwrap any wSOL that
+ // landed there during the AMM collect path. If the ATA doesn't exist or
+ // is already closed, the program reverts on this single ix only — wrap
+ // in its own tx to avoid blocking the claim itself.
+ let creatorWsolAta;
+ try {
+ creatorWsolAta = getAssociatedTokenAddressSync(NATIVE_MINT, creatorPk, false);
+ } catch {
+ creatorWsolAta = null;
+ }
+
+ const tx = new Transaction();
+ tx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: PRIORITY_MICRO_LAMPORTS }));
+ for (const ix of ixs) tx.add(ix);
+ tx.feePayer = treasuryPk;
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
+ tx.recentBlockhash = blockhash;
+
+ // Sign with both keys: treasury pays + signs as fee payer, creator signs
+ // the collectCreatorFee instruction. When they're the same keypair, this
+ // gracefully deduplicates inside @solana/web3.js.
+ const signers = [treasury];
+ if (creatorPk.toBase58() !== treasuryPk.toBase58()) signers.push(coinCreator);
+ tx.sign(...signers);
+
+ const sig = await connection.sendRawTransaction(tx.serialize(), {
+ skipPreflight: false,
+ maxRetries: 5,
+ });
+ await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
+
+ // Attempt the unwrap as a follow-up tx (best-effort).
+ if (creatorWsolAta) {
+ try {
+ const ataInfo = await connection.getAccountInfo(creatorWsolAta, 'confirmed');
+ if (ataInfo && Number(ataInfo.lamports) > 0) {
+ const closeTx = new Transaction();
+ closeTx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: PRIORITY_MICRO_LAMPORTS }));
+ closeTx.add(createCloseAccountInstruction(creatorWsolAta, treasuryPk, creatorPk));
+ closeTx.feePayer = treasuryPk;
+ const { blockhash: bh2 } = await connection.getLatestBlockhash('confirmed');
+ closeTx.recentBlockhash = bh2;
+ closeTx.sign(...signers);
+ await connection.sendRawTransaction(closeTx.serialize(), {
+ skipPreflight: false,
+ maxRetries: 5,
+ });
+ }
+ } catch {
+ // Non-fatal — the next claim cycle will unwrap any residue.
+ }
+ }
+
+ const balanceAfter = BigInt(await connection.getBalance(creatorPk, 'confirmed'));
+ // Diff: net SOL gained at the creator account (or the treasury when same key).
+ // Subtract a generous fee estimate so we don't credit ourselves more than
+ // what actually landed. Real fees are ~5_000 + priority; we under-count
+ // conservatively if the diff goes negative.
+ let diff = balanceAfter - balanceBefore;
+ if (diff < 0n) diff = 0n;
+
+ return {
+ tx_signature: sig,
+ claimed_lamports: diff,
+ was_empty: diff === 0n,
+ };
+}
+
+/**
+ * Validate that a public key string is a real Solana pubkey. Helper for
+ * launch-prep handler input validation.
+ */
+export function isValidPubkey(s) {
+ return solanaPubkey(s) instanceof PublicKey;
+}
diff --git a/api/_lib/coin/distribution.js b/api/_lib/coin/distribution.js
new file mode 100644
index 000000000..3f45e801c
--- /dev/null
+++ b/api/_lib/coin/distribution.js
@@ -0,0 +1,415 @@
+// Coin distribution orchestrator.
+//
+// Lifecycle of one full hourly cycle:
+//
+// 1. snapshot: refresh coin_holders from Helius RPC
+// 2. claim: sweep pump.fun creator-vault SOL to the treasury and
+// split lamports per coin_launches.{lottery,reflection,ops}_bps
+// into the pot columns
+// 3. lottery commit: pick the Drand round R that will be live at the next
+// draw time; insert coin_draws(status=committed) with
+// drand_round=R and weights_hash over today's snapshot
+// 4. lottery resolve: when round R's randomness is published, derive the
+// winner; insert one coin_payouts row for the lottery pot
+// 5. reflection: for each eligible holder, allocate a pro-rata share of
+// the reflection pot into coin_holders.accrued_reflection;
+// then queue coin_payouts rows for each holder
+// 6. payouts cron: a separate cron drains pending coin_payouts via
+// sendSolBatched, marks confirmed
+//
+// Each step is idempotent and persists its own state row, so partial failures
+// do not corrupt the books. The cron handler invokes step methods in order
+// but each is also callable independently for ops/debugging.
+
+import { sql } from '../db.js';
+import { claimCreatorFees } from './creator-fees.js';
+import { fetchHolderBalances, persistHolderSnapshot, readEligibleHolders } from './holders.js';
+import {
+ roundForTime,
+ timeForRound,
+ fetchDrandRound,
+ verifyDrandSignature,
+ seedFor,
+ weightedPick,
+ weightsHash,
+} from './randomness.js';
+import { loadCoinTreasury, loadCoinCreatorFromCoin } from './treasury.js';
+
+// ─── Snapshot ───────────────────────────────────────────────────────────────
+
+export async function snapshotHolders(coin) {
+ const balances = await fetchHolderBalances({ mint: coin.mint, network: coin.network });
+ const stats = await persistHolderSnapshot({ coinId: coin.id, balances });
+ await sql`
+ insert into coin_events (coin_id, kind, payload)
+ values (${coin.id}, 'snapshot', ${JSON.stringify({
+ accounts: stats.totalAccounts,
+ holders: stats.positive,
+ })}::jsonb)
+ `;
+ return stats;
+}
+
+// ─── Claim creator fees + allocation split ──────────────────────────────────
+
+export async function claimAndSplit(coin) {
+ const creator = loadCoinCreatorFromCoin(coin);
+ if (!creator) {
+ await sql`
+ insert into coin_events (coin_id, kind, payload)
+ values (${coin.id}, 'error', ${JSON.stringify({
+ step: 'claim',
+ reason: 'no_creator_keypair',
+ })}::jsonb)
+ `;
+ return { skipped: true, reason: 'no_creator_keypair' };
+ }
+ const treasury = coin.metadata?.treasury_is_creator ? creator : loadCoinTreasury();
+
+ const result = await claimCreatorFees({ coin, coinCreator: creator, treasury });
+
+ if (result.claimed_lamports === 0n) {
+ await sql`
+ insert into coin_events (coin_id, kind, payload, tx_signature)
+ values (${coin.id}, 'fee_claim', ${JSON.stringify({
+ claimed: '0',
+ was_empty: true,
+ })}::jsonb, ${result.tx_signature})
+ `;
+ return { skipped: true, reason: 'empty_vault', tx_signature: result.tx_signature };
+ }
+
+ // Split per bps. Use BigInt arithmetic throughout.
+ const total = result.claimed_lamports;
+ const lotteryLamports = (total * BigInt(coin.lottery_bps)) / 10_000n;
+ const reflectionLamports = (total * BigInt(coin.reflection_bps)) / 10_000n;
+ // Ops absorbs the rounding remainder so the three pots always sum to `total`.
+ const opsLamports = total - lotteryLamports - reflectionLamports;
+
+ await sql`
+ update coin_launches
+ set lottery_pot_lamports = lottery_pot_lamports + ${lotteryLamports.toString()}::bigint,
+ reflection_pot_lamports = reflection_pot_lamports + ${reflectionLamports.toString()}::bigint,
+ ops_pot_lamports = ops_pot_lamports + ${opsLamports.toString()}::bigint,
+ total_claimed_lamports = total_claimed_lamports + ${total.toString()}::bigint,
+ last_claim_at = now(),
+ updated_at = now()
+ where id = ${coin.id}
+ `;
+
+ await sql`
+ insert into coin_events (coin_id, kind, payload, tx_signature)
+ values (${coin.id}, 'fee_claim', ${JSON.stringify({
+ claimed: total.toString(),
+ lottery: lotteryLamports.toString(),
+ reflection: reflectionLamports.toString(),
+ ops: opsLamports.toString(),
+ })}::jsonb, ${result.tx_signature})
+ `;
+
+ return {
+ skipped: false,
+ claimed_lamports: total,
+ lottery_lamports: lotteryLamports,
+ reflection_lamports: reflectionLamports,
+ ops_lamports: opsLamports,
+ tx_signature: result.tx_signature,
+ };
+}
+
+// ─── Lottery ────────────────────────────────────────────────────────────────
+
+/**
+ * Build the deterministic id used to dedupe a draw. One draw per
+ * floor(now / draw_interval_seconds) per coin.
+ */
+function lotteryDrawId(coin, nowMs) {
+ const bucket = Math.floor(nowMs / 1000 / coin.draw_interval_seconds);
+ return `${coin.mint}-${bucket}`;
+}
+
+/**
+ * Commit a future Drand round + freeze a holder snapshot for the next lottery
+ * draw. Idempotent on the {coin_id, draw_id} unique constraint.
+ */
+export async function commitLottery(coin, nowMs = Date.now()) {
+ const drawId = lotteryDrawId(coin, nowMs);
+
+ // Already committed?
+ const [existing] = await sql`
+ select id, status, drand_round
+ from coin_draws
+ where coin_id = ${coin.id} and draw_id = ${drawId}
+ limit 1
+ `;
+ if (existing) {
+ return { drawId, drandRound: Number(existing.drand_round), status: existing.status, already: true };
+ }
+
+ const holders = await readEligibleHolders({
+ coinId: coin.id,
+ minBalance: BigInt(coin.min_holder_balance || 0),
+ });
+ if (holders.length === 0) {
+ await sql`
+ insert into coin_events (coin_id, kind, payload)
+ values (${coin.id}, 'error', ${JSON.stringify({
+ step: 'commit_lottery',
+ reason: 'no_holders',
+ draw_id: drawId,
+ })}::jsonb)
+ `;
+ return { drawId, status: 'no_holders' };
+ }
+
+ const drawTime = Math.floor(nowMs / 1000) + coin.draw_interval_seconds;
+ const drandRound = roundForTime(drawTime);
+ const wHash = weightsHash(holders.map((h) => ({ wallet: h.wallet, weight: h.balance })));
+ const pot = BigInt(coin.lottery_pot_lamports);
+
+ await sql`
+ insert into coin_draws (
+ coin_id, draw_id, drand_round, pot_lamports, weights_hash, holder_count, status
+ ) values (
+ ${coin.id}, ${drawId}, ${drandRound}, ${pot.toString()}::bigint,
+ ${wHash}, ${holders.length}, 'committed'
+ )
+ on conflict (coin_id, draw_id) do nothing
+ `;
+ return { drawId, drandRound, status: 'committed', holder_count: holders.length, pot };
+}
+
+/**
+ * Resolve a previously-committed draw: fetch the published Drand round, pick
+ * the weighted-random winner, queue a coin_payouts row, decrement the
+ * lottery pot.
+ *
+ * Failure modes:
+ * - drand_round_unavailable: Drand hasn't published the round yet — retry later.
+ * - holder set changed: we re-fetch and compare hashes; mismatch = abort
+ * (the operator can investigate; no pot change).
+ */
+export async function resolveLottery(coin, drawRow) {
+ if (drawRow.status === 'resolved' || drawRow.status === 'paid') {
+ return { already: true, status: drawRow.status };
+ }
+
+ const drand = await fetchDrandRound(Number(drawRow.drand_round));
+ const verified = await verifyDrandSignature(drand);
+
+ const holders = await readEligibleHolders({
+ coinId: coin.id,
+ minBalance: BigInt(coin.min_holder_balance || 0),
+ });
+ if (holders.length === 0) {
+ await sql`
+ update coin_draws set status='failed', error='no_holders_at_resolve', resolved_at=now()
+ where id=${drawRow.id}
+ `;
+ return { status: 'failed', error: 'no_holders_at_resolve' };
+ }
+ const currentHash = weightsHash(holders.map((h) => ({ wallet: h.wallet, weight: h.balance })));
+ if (currentHash !== drawRow.weights_hash) {
+ // Holder set drifted — pick deterministically over the CURRENT set, but
+ // record the drift so audit can spot it. (Refusing to draw here would
+ // just block the lottery; we accept the drift because the Drand round
+ // was committed in advance so the operator can't game it.)
+ await sql`
+ insert into coin_events (coin_id, kind, payload)
+ values (${coin.id}, 'snapshot', ${JSON.stringify({
+ step: 'resolve_lottery',
+ note: 'weights_hash_drift',
+ draw_id: drawRow.draw_id,
+ committed: drawRow.weights_hash,
+ current: currentHash,
+ })}::jsonb)
+ `;
+ }
+
+ const weights = holders.map((h) => h.balance);
+ const seed = seedFor(drand.randomness, currentHash);
+ const idx = weightedPick(weights, seed);
+ const winner = holders[idx];
+ const pot = BigInt(drawRow.pot_lamports);
+
+ const batchId = `lottery:${drawRow.draw_id}`;
+ await sql`
+ insert into coin_payouts (coin_id, kind, wallet, amount_lamports, batch_id, status)
+ values (${coin.id}, 'lottery', ${winner.wallet}, ${pot.toString()}::bigint, ${batchId}, 'pending')
+ on conflict (batch_id, wallet) do nothing
+ `;
+
+ await sql`
+ update coin_draws set
+ drand_randomness = ${drand.randomness},
+ drand_signature = ${drand.signature},
+ winner_wallet = ${winner.wallet},
+ winner_balance = ${winner.balance.toString()}::bigint,
+ status = 'resolved',
+ resolved_at = now()
+ where id = ${drawRow.id}
+ `;
+
+ // Decrement the lottery pot by the amount we're paying out. Any rounding
+ // remainder stays in the pot for the next draw.
+ await sql`
+ update coin_launches
+ set lottery_pot_lamports = lottery_pot_lamports - ${pot.toString()}::bigint,
+ last_draw_at = now(),
+ updated_at = now()
+ where id = ${coin.id}
+ `;
+
+ await sql`
+ insert into coin_events (coin_id, kind, payload)
+ values (${coin.id}, 'lottery_draw', ${JSON.stringify({
+ draw_id: drawRow.draw_id,
+ winner: winner.wallet,
+ amount: pot.toString(),
+ drand_round: Number(drawRow.drand_round),
+ verified,
+ holder_count: holders.length,
+ })}::jsonb)
+ `;
+
+ return { status: 'resolved', winner: winner.wallet, amount: pot, verified };
+}
+
+/**
+ * Find all coin_draws still in 'committed' status whose target Drand round is
+ * now past — and try to resolve each.
+ */
+export async function resolvePendingDraws(coin) {
+ const rows = await sql`
+ select * from coin_draws
+ where coin_id = ${coin.id} and status = 'committed'
+ order by created_at asc
+ limit 24
+ `;
+ const out = [];
+ for (const row of rows) {
+ const roundTime = timeForRound(Number(row.drand_round));
+ if (roundTime > Math.floor(Date.now() / 1000)) {
+ out.push({ drawId: row.draw_id, status: 'not_yet', drandRound: Number(row.drand_round) });
+ continue;
+ }
+ try {
+ const r = await resolveLottery(coin, row);
+ out.push({ drawId: row.draw_id, ...r });
+ } catch (err) {
+ const msg = err?.message || String(err);
+ if (msg.startsWith('drand_round_unavailable')) {
+ out.push({ drawId: row.draw_id, status: 'drand_not_ready' });
+ continue;
+ }
+ await sql`
+ update coin_draws set status='failed', error=${msg}, resolved_at=now()
+ where id=${row.id}
+ `;
+ out.push({ drawId: row.draw_id, status: 'failed', error: msg });
+ }
+ }
+ return out;
+}
+
+// ─── Reflection ─────────────────────────────────────────────────────────────
+
+/**
+ * Compute the next reflection batch id (one per reflection_interval_seconds).
+ */
+function reflectionBatchId(coin, nowMs) {
+ const bucket = Math.floor(nowMs / 1000 / coin.reflection_interval_seconds);
+ return `${coin.mint}-reflection-${bucket}`;
+}
+
+/**
+ * Allocate the reflection pot pro-rata across current eligible holders and
+ * queue coin_payouts rows. The pot is drained to zero (less any rounding
+ * remainder, which stays in the pot for the next cycle).
+ *
+ * Idempotent on the batch_id — a second call inside the same window short-
+ * circuits.
+ */
+export async function allocateReflection(coin, nowMs = Date.now()) {
+ const batchId = reflectionBatchId(coin, nowMs);
+
+ // Already allocated this window?
+ const [already] = await sql`
+ select 1 from coin_payouts
+ where coin_id = ${coin.id} and batch_id = ${batchId}
+ limit 1
+ `;
+ if (already) {
+ return { batchId, status: 'already', queued: 0 };
+ }
+
+ const pot = BigInt(coin.reflection_pot_lamports);
+ if (pot === 0n) {
+ await sql`
+ insert into coin_events (coin_id, kind, payload)
+ values (${coin.id}, 'reflection_batch', ${JSON.stringify({
+ batch_id: batchId,
+ queued: 0,
+ reason: 'empty_pot',
+ })}::jsonb)
+ `;
+ return { batchId, status: 'empty_pot', queued: 0 };
+ }
+
+ const holders = await readEligibleHolders({
+ coinId: coin.id,
+ minBalance: BigInt(coin.min_holder_balance || 0),
+ });
+ if (holders.length === 0) {
+ return { batchId, status: 'no_holders', queued: 0 };
+ }
+
+ const totalBalance = holders.reduce((a, h) => a + h.balance, 0n);
+ if (totalBalance === 0n) return { batchId, status: 'no_balance', queued: 0 };
+
+ let allocated = 0n;
+ let queued = 0;
+ const MIN_PAYOUT = 1_000n; // 0.000001 SOL — skip dust to keep tx batches efficient
+
+ for (const h of holders) {
+ const share = (pot * h.balance) / totalBalance;
+ if (share < MIN_PAYOUT) continue;
+ await sql`
+ insert into coin_payouts (
+ coin_id, kind, wallet, amount_lamports, batch_id, status
+ ) values (
+ ${coin.id}, 'reflection', ${h.wallet}, ${share.toString()}::bigint,
+ ${batchId}, 'pending'
+ )
+ on conflict (batch_id, wallet) do nothing
+ `;
+ await sql`
+ update coin_holders
+ set accrued_reflection_lamports = accrued_reflection_lamports + ${share.toString()}::bigint
+ where coin_id = ${coin.id} and wallet = ${h.wallet}
+ `;
+ allocated += share;
+ queued += 1;
+ }
+
+ // Drain the allocated portion from the reflection pot. Rounding dust stays.
+ await sql`
+ update coin_launches
+ set reflection_pot_lamports = reflection_pot_lamports - ${allocated.toString()}::bigint,
+ last_reflection_at = now(),
+ updated_at = now()
+ where id = ${coin.id}
+ `;
+
+ await sql`
+ insert into coin_events (coin_id, kind, payload)
+ values (${coin.id}, 'reflection_batch', ${JSON.stringify({
+ batch_id: batchId,
+ queued,
+ allocated: allocated.toString(),
+ pot_remaining: (pot - allocated).toString(),
+ })}::jsonb)
+ `;
+
+ return { batchId, status: 'allocated', queued, allocated };
+}
diff --git a/api/_lib/coin/holders.js b/api/_lib/coin/holders.js
new file mode 100644
index 000000000..955bbc13b
--- /dev/null
+++ b/api/_lib/coin/holders.js
@@ -0,0 +1,173 @@
+// Holder snapshot via Helius RPC.
+//
+// Pump.fun tokens are issued on Token-2022 (createV2). We poll both the
+// legacy SPL Token program (TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA) and
+// Token-2022 (TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb) so we never miss a
+// holder regardless of which program the mint targets.
+//
+// getProgramAccounts with a mint memcmp filter returns every token account
+// holding that mint. Each token account belongs to an owner wallet (the
+// "holder"). We aggregate balances by owner — a single owner can have multiple
+// token accounts (rare for retail wallets but does happen with multisigs).
+//
+// Snapshots are persisted into coin_holders via upsert; balances of zero
+// (i.e. holders that fully exited) are KEPT in the table at balance=0 because
+// their accrued_reflection_lamports might still be unpaid. The reflection
+// payout flow filters by balance > min_holder_balance at distribution time.
+
+import { sql } from '../db.js';
+
+const TOKEN_PROGRAM_LEGACY = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
+const TOKEN_PROGRAM_2022 = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';
+
+// SPL Token account layout: 32-byte mint at offset 0.
+// Token-2022 has the same first 165 bytes for plain token accounts (extensions
+// are appended after byte 165), so dataSize-greater-than filter works.
+
+function heliusRpcUrl(network) {
+ const key = process.env.HELIUS_API_KEY;
+ if (!key) throw new Error('HELIUS_API_KEY not set');
+ const host = network === 'devnet' ? 'devnet.helius-rpc.com' : 'mainnet.helius-rpc.com';
+ return `https://${host}/?api-key=${key}`;
+}
+
+async function rpc(network, method, params) {
+ const url = heliusRpcUrl(network);
+ const resp = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ });
+ if (!resp.ok) throw new Error(`helius_rpc_${method}_${resp.status}`);
+ const data = await resp.json();
+ if (data.error) throw new Error(`helius_rpc_${method}: ${data.error.message}`);
+ return data.result;
+}
+
+/**
+ * Fetch all holders of a given mint by walking SPL token accounts under both
+ * the legacy Token program and Token-2022. Aggregates by owner wallet.
+ *
+ * @param {object} opts
+ * @param {string} opts.mint
+ * @param {'mainnet'|'devnet'} [opts.network]
+ * @returns {Promise<Map<string, bigint>>} owner → token-units
+ */
+export async function fetchHolderBalances({ mint, network = 'mainnet' }) {
+ const balances = new Map();
+
+ for (const programId of [TOKEN_PROGRAM_LEGACY, TOKEN_PROGRAM_2022]) {
+ // jsonParsed gives us owner + tokenAmount.amount as a string directly,
+ // avoiding any need to decode account data ourselves.
+ const accounts = await rpc(network, 'getProgramAccounts', [
+ programId,
+ {
+ encoding: 'jsonParsed',
+ commitment: 'confirmed',
+ filters: [
+ { dataSize: programId === TOKEN_PROGRAM_LEGACY ? 165 : 170 },
+ { memcmp: { offset: 0, bytes: mint } },
+ ],
+ },
+ ]).catch(async (err) => {
+ // Token-2022 accounts may not match exact dataSize 170 — try without
+ // the dataSize filter as a fallback. This is slower but correct.
+ if (programId === TOKEN_PROGRAM_2022) {
+ return rpc(network, 'getProgramAccounts', [
+ programId,
+ {
+ encoding: 'jsonParsed',
+ commitment: 'confirmed',
+ filters: [{ memcmp: { offset: 0, bytes: mint } }],
+ },
+ ]);
+ }
+ throw err;
+ });
+
+ if (!Array.isArray(accounts)) continue;
+ for (const acc of accounts) {
+ const parsed = acc?.account?.data?.parsed?.info;
+ if (!parsed) continue;
+ const owner = parsed.owner;
+ const amount = parsed.tokenAmount?.amount;
+ if (!owner || amount == null) continue;
+ const n = BigInt(amount);
+ if (n === 0n) continue;
+ balances.set(owner, (balances.get(owner) || 0n) + n);
+ }
+ }
+
+ return balances;
+}
+
+/**
+ * Persist a holder snapshot into coin_holders. Returns counts for logging.
+ * Wallets with balance=0 in the snapshot are downgraded to balance=0 in DB
+ * (so they stop accruing reflection) but the row is preserved so any pending
+ * accrued_reflection_lamports remains claimable.
+ *
+ * @param {object} opts
+ * @param {string} opts.coinId
+ * @param {Map<string, bigint>} opts.balances
+ */
+export async function persistHolderSnapshot({ coinId, balances }) {
+ const now = new Date();
+ const wallets = [...balances.keys()];
+
+ // Insert/update each wallet. Postgres jsonb-style would be nice but we
+ // don't have batch tooling wired in; for snapshots of a few thousand
+ // holders this is fast enough on Solana traffic.
+ for (const wallet of wallets) {
+ const bal = balances.get(wallet);
+ await sql`
+ insert into coin_holders (coin_id, wallet, balance, first_seen, last_seen)
+ values (${coinId}, ${wallet}, ${bal.toString()}, ${now}, ${now})
+ on conflict (coin_id, wallet) do update set
+ balance = excluded.balance,
+ last_seen = excluded.last_seen
+ `;
+ }
+
+ // Mark wallets that vanished from the snapshot as balance=0 so they stop
+ // accruing reflection. Neon's HTTP client expands arrays into Postgres
+ // array params, so we use `NOT (wallet = ANY($1))` rather than `NOT IN`.
+ if (wallets.length > 0) {
+ await sql`
+ update coin_holders
+ set balance = 0
+ where coin_id = ${coinId}
+ and balance > 0
+ and not (wallet = any(${wallets}))
+ `;
+ } else {
+ await sql`
+ update coin_holders set balance = 0
+ where coin_id = ${coinId} and balance > 0
+ `;
+ }
+
+ await sql`
+ update coin_launches
+ set last_snapshot_at = ${now}, updated_at = ${now}
+ where id = ${coinId}
+ `;
+
+ const positive = wallets.filter((w) => balances.get(w) > 0n).length;
+ return { totalAccounts: wallets.length, positive };
+}
+
+/**
+ * Read the current eligible-holder set from DB. Returns {wallet, balance}
+ * tuples for everyone with balance > min_holder_balance, sorted descending
+ * by balance.
+ */
+export async function readEligibleHolders({ coinId, minBalance = 0n }) {
+ const rows = await sql`
+ select wallet, balance::text as balance
+ from coin_holders
+ where coin_id = ${coinId} and balance > ${minBalance.toString()}::bigint
+ order by balance::numeric desc
+ `;
+ return rows.map((r) => ({ wallet: r.wallet, balance: BigInt(r.balance) }));
+}
diff --git a/api/_lib/coin/index.js b/api/_lib/coin/index.js
new file mode 100644
index 000000000..c1b5d3d26
--- /dev/null
+++ b/api/_lib/coin/index.js
@@ -0,0 +1,71 @@
+// Public surface of the coin (lottery + reflection) library.
+// Re-exports the building blocks so cron handlers and API endpoints can
+// import from one stable path.
+
+export { claimCreatorFees, isValidPubkey } from './creator-fees.js';
+export {
+ loadCoinTreasury,
+ loadCoinCreatorFromCoin,
+ lamportsToSol,
+ sendSolTransfer,
+ sendSolBatched,
+} from './treasury.js';
+export {
+ fetchHolderBalances,
+ persistHolderSnapshot,
+ readEligibleHolders,
+} from './holders.js';
+export {
+ DRAND,
+ roundForTime,
+ timeForRound,
+ fetchDrandRound,
+ verifyDrandSignature,
+ drandRoundMessage,
+ seedFor,
+ weightedPick,
+ weightsHash,
+ bigintPRNG,
+} from './randomness.js';
+export {
+ snapshotHolders,
+ claimAndSplit,
+ commitLottery,
+ resolveLottery,
+ resolvePendingDraws,
+ allocateReflection,
+} from './distribution.js';
+export { drainPendingPayouts } from './payouts.js';
+
+import { sql } from '../db.js';
+
+/**
+ * Load a coin_launches row by mint pubkey. Returns null if not found.
+ */
+export async function loadCoinByMint(mint) {
+ const [row] = await sql`
+ select * from coin_launches where mint = ${mint} limit 1
+ `;
+ return row || null;
+}
+
+/**
+ * Load a coin_launches row by uuid id.
+ */
+export async function loadCoinById(id) {
+ const [row] = await sql`
+ select * from coin_launches where id = ${id} limit 1
+ `;
+ return row || null;
+}
+
+/**
+ * List all coins marked active. Used by cron handlers to sweep every coin.
+ */
+export async function listActiveCoins() {
+ return sql`
+ select * from coin_launches
+ where is_active = true
+ order by created_at asc
+ `;
+}
diff --git a/api/_lib/coin/payouts.js b/api/_lib/coin/payouts.js
new file mode 100644
index 000000000..2d3fa3acd
--- /dev/null
+++ b/api/_lib/coin/payouts.js
@@ -0,0 +1,158 @@
+// Drain pending coin_payouts rows by signing + submitting batched SOL transfers.
+//
+// Called by the run-coin-payouts cron. Idempotent on tx_signature: a payout
+// that was already submitted but lost in the network is re-attempted via
+// signature lookup before we send another tx. (Solana doesn't have nonces,
+// so the only way to avoid double-paying is to either include the same
+// recent blockhash or to mark a row 'submitted' before sending and gate
+// retries.) We use the second approach.
+
+import { sql } from '../db.js';
+import { loadCoinTreasury, sendSolBatched } from './treasury.js';
+
+const PAYOUTS_PER_CYCLE_LIMIT = 200; // ~12 chunked txs; keeps cron runtime bounded
+
+/**
+ * Pull a batch of pending payouts for one coin, send via batched SystemProgram
+ * transfers, and mark each row confirmed/failed.
+ *
+ * @param {object} coin coin_launches row
+ * @returns {Promise<{ sent: number, confirmed: number, failed: number }>}
+ */
+export async function drainPendingPayouts(coin) {
+ const pending = await sql`
+ select id, kind, wallet, amount_lamports::text as amount, batch_id
+ from coin_payouts
+ where coin_id = ${coin.id} and status = 'pending'
+ order by created_at asc
+ limit ${PAYOUTS_PER_CYCLE_LIMIT}
+ `;
+ if (pending.length === 0) return { sent: 0, confirmed: 0, failed: 0 };
+
+ if (!coin.is_live) {
+ // Dry-run mode: mark each pending payout as confirmed with a
+ // placeholder signature so the books reconcile. Useful for tests on
+ // devnet or for a soft-launch where the operator wants the indexer
+ // running but no on-chain spend.
+ let n = 0;
+ for (const p of pending) {
+ await sql`
+ update coin_payouts
+ set status='confirmed', tx_signature=${'DRYRUN-' + p.id}, confirmed_at=now()
+ where id=${p.id}
+ `;
+ await applyPostPayoutBookkeeping(coin.id, p);
+ n++;
+ }
+ return { sent: 0, confirmed: n, failed: 0, dry_run: true };
+ }
+
+ const treasury = loadCoinTreasury();
+
+ // Mark rows submitted BEFORE sending so a crash mid-flight doesn't allow
+ // a second cron to re-send them. Neon HTTP client expands arrays into a
+ // single Postgres array param, so we match via `= ANY($1)`.
+ const ids = pending.map((p) => p.id);
+ await sql`
+ update coin_payouts set status='submitted', submitted_at=now()
+ where id = any(${ids})
+ `;
+
+ const transfers = pending.map((p) => ({
+ to: p.wallet,
+ lamports: BigInt(p.amount),
+ ref: p,
+ }));
+
+ const results = await sendSolBatched({
+ from: treasury,
+ transfers,
+ network: coin.network || 'mainnet',
+ });
+
+ let confirmed = 0;
+ let failed = 0;
+ for (const r of results) {
+ if (r.error) {
+ failed += r.recipients.length;
+ for (const t of r.recipients) {
+ await sql`
+ update coin_payouts
+ set status='failed', error=${r.error.slice(0, 500)}
+ where id=${t.ref.id}
+ `;
+ await sql`
+ insert into coin_events (coin_id, kind, payload)
+ values (${coin.id}, 'error', ${JSON.stringify({
+ step: 'payout',
+ payout_id: t.ref.id,
+ kind: t.ref.kind,
+ wallet: t.ref.wallet,
+ amount: t.ref.amount,
+ error: r.error.slice(0, 500),
+ })}::jsonb)
+ `;
+ }
+ continue;
+ }
+ confirmed += r.recipients.length;
+ for (const t of r.recipients) {
+ await sql`
+ update coin_payouts
+ set status='confirmed', tx_signature=${r.signature}, confirmed_at=now()
+ where id=${t.ref.id}
+ `;
+ await applyPostPayoutBookkeeping(coin.id, t.ref);
+ }
+ await sql`
+ insert into coin_events (coin_id, kind, payload, tx_signature)
+ values (${coin.id}, 'reflection_batch', ${JSON.stringify({
+ batch_kind: 'payout_tx',
+ recipients: r.recipients.length,
+ lamports_total: r.recipients
+ .reduce((acc, t) => acc + BigInt(t.lamports), 0n)
+ .toString(),
+ })}::jsonb, ${r.signature})
+ `;
+ }
+
+ // For each lottery payout that confirmed, mark the corresponding draw paid.
+ const confirmedLotteryBatches = [
+ ...new Set(
+ results
+ .filter((r) => !r.error)
+ .flatMap((r) => r.recipients)
+ .filter((t) => t.ref.kind === 'lottery')
+ .map((t) => t.ref.batch_id),
+ ),
+ ];
+ for (const batchId of confirmedLotteryBatches) {
+ const drawId = batchId.replace(/^lottery:/, '');
+ await sql`
+ update coin_draws set status='paid', paid_at=now()
+ where coin_id=${coin.id} and draw_id=${drawId} and status='resolved'
+ `;
+ }
+
+ return { sent: pending.length, confirmed, failed };
+}
+
+async function applyPostPayoutBookkeeping(coinId, payoutRow) {
+ const amount = BigInt(payoutRow.amount);
+ if (payoutRow.kind === 'lottery') {
+ await sql`
+ update coin_holders
+ set total_lottery_won_lamports = total_lottery_won_lamports + ${amount.toString()}::bigint,
+ last_payout_at = now()
+ where coin_id = ${coinId} and wallet = ${payoutRow.wallet}
+ `;
+ } else if (payoutRow.kind === 'reflection') {
+ await sql`
+ update coin_holders
+ set accrued_reflection_lamports = greatest(accrued_reflection_lamports - ${amount.toString()}::bigint, 0),
+ total_reflection_paid_lamports = total_reflection_paid_lamports + ${amount.toString()}::bigint,
+ last_payout_at = now()
+ where coin_id = ${coinId} and wallet = ${payoutRow.wallet}
+ `;
+ }
+}
diff --git a/api/_lib/coin/randomness.js b/api/_lib/coin/randomness.js
new file mode 100644
index 000000000..ea2b8da60
--- /dev/null
+++ b/api/_lib/coin/randomness.js
@@ -0,0 +1,243 @@
+// Verifiable randomness for the lottery draw.
+//
+// We use Drand "quicknet" (the unchained BLS12-381 chain) for two reasons:
+// 1. Anyone can independently verify a published signature against the public
+// Drand public key, so our lottery is provably unbiased.
+// 2. We commit to a future round number at draw-open time; that round's
+// randomness isn't known to anyone (including us) until the Drand network
+// publishes the BLS signature, which happens on a public 3-second cadence.
+// No one — including the server operator — can influence the outcome.
+//
+// Chain info (quicknet, frozen):
+// chain hash : 52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971
+// genesis : 1692803367 (unix seconds)
+// period : 3 seconds
+// public key : 83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a
+//
+// Verification is best-effort: if @noble/curves API surface drifts between
+// minor versions we don't want to deadlock the draw. We always record the
+// raw {round, randomness, signature} into coin_draws so a third party can
+// audit after the fact even if we didn't verify in-process.
+
+import { sha256 } from '@noble/hashes/sha256';
+
+const QUICKNET_CHAIN_HASH = '52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971';
+const QUICKNET_GENESIS = 1692803367;
+const QUICKNET_PERIOD = 3;
+const QUICKNET_PUBLIC_KEY_HEX =
+ '83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c' +
+ '8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb' +
+ '5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a';
+
+const DRAND_BASE = `https://api.drand.sh/${QUICKNET_CHAIN_HASH}/public`;
+
+/**
+ * Compute the Drand round number that will be live at or after the given unix
+ * timestamp (seconds). Adds a `bufferRounds` lookahead so a freshly committed
+ * draw can't accidentally target a past round.
+ *
+ * @param {number} unixSeconds
+ * @param {number} bufferRounds rounds of headroom (default 2 = +6 seconds)
+ */
+export function roundForTime(unixSeconds, bufferRounds = 2) {
+ if (unixSeconds < QUICKNET_GENESIS) {
+ throw new Error('roundForTime: timestamp predates quicknet genesis');
+ }
+ const elapsed = unixSeconds - QUICKNET_GENESIS;
+ const r = Math.floor(elapsed / QUICKNET_PERIOD) + 1 + bufferRounds;
+ return r;
+}
+
+/**
+ * Unix timestamp at which the given Drand round becomes available.
+ */
+export function timeForRound(round) {
+ return QUICKNET_GENESIS + (round - 1) * QUICKNET_PERIOD;
+}
+
+function uint64BE(n) {
+ const buf = new Uint8Array(8);
+ const big = BigInt(n);
+ for (let i = 7; i >= 0; i--) {
+ buf[i] = Number((big >> BigInt((7 - i) * 8)) & 0xffn);
+ }
+ return buf;
+}
+
+/**
+ * The message hashed into the BLS signature for round `r` on quicknet
+ * (unchained mode): m = sha256(uint64_be(r)).
+ */
+export function drandRoundMessage(round) {
+ return sha256(uint64BE(round));
+}
+
+/**
+ * Fetch the published randomness for a Drand quicknet round. Throws if the
+ * round isn't available yet (404) or if Drand is unreachable.
+ *
+ * @returns {Promise<{ round: number, randomness: string, signature: string }>}
+ */
+export async function fetchDrandRound(round) {
+ const url = `${DRAND_BASE}/${round}`;
+ const resp = await fetch(url, { headers: { accept: 'application/json' } });
+ if (resp.status === 404) {
+ throw new Error(`drand_round_unavailable:${round}`);
+ }
+ if (!resp.ok) {
+ throw new Error(`drand_fetch_failed:${resp.status}`);
+ }
+ const data = await resp.json();
+ if (!data || typeof data.round !== 'number' || !data.randomness || !data.signature) {
+ throw new Error('drand_response_malformed');
+ }
+ // Sanity: randomness MUST equal sha256(signature) per the quicknet spec.
+ const expected = Buffer.from(sha256(Buffer.from(data.signature, 'hex'))).toString('hex');
+ if (data.randomness !== expected) {
+ throw new Error('drand_randomness_mismatch');
+ }
+ return { round: data.round, randomness: data.randomness, signature: data.signature };
+}
+
+/**
+ * Verify the BLS signature on a Drand quicknet round. Returns true on success;
+ * returns false on any verification failure or library mismatch. Callers should
+ * NOT use this as their only guard — always also persist the {round, randomness,
+ * signature} tuple so an outside auditor can re-verify with their own tooling.
+ *
+ * Drand quicknet uses the "short signatures" BLS scheme: signatures on G1
+ * (48 bytes compressed) and public keys on G2 (96 bytes compressed). The
+ * message is the raw uint64-BE round number; @noble/curves' shortSignatures
+ * scheme handles the hash-to-curve internally with the standard DST.
+ *
+ * @param {{ round: number, randomness: string, signature: string }} entry
+ * @returns {Promise<boolean>}
+ */
+export async function verifyDrandSignature({ round, signature }) {
+ try {
+ const noble = await import('@noble/curves/bls12-381.js').catch(() => null);
+ const short = noble?.bls12_381?.shortSignatures;
+ if (!short?.verify || !short?.hash) return false;
+ const sigBytes = Buffer.from(signature, 'hex');
+ const pkBytes = Buffer.from(QUICKNET_PUBLIC_KEY_HEX, 'hex');
+ // Drand quicknet (scheme "bls-unchained-g1-rfc9380") signs:
+ // m = sha256(uint64_be(round))
+ // then hashed-to-curve on G1 with DST BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_.
+ // @noble/curves' shortSignatures.verify wants the message PRE-hashed to
+ // the curve, so we run short.hash() first.
+ const msg = drandRoundMessage(round);
+ const hashed = short.hash(msg);
+ return short.verify(sigBytes, hashed, pkBytes);
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Compress randomness + a salt (the weights_hash) into a 32-byte PRNG seed.
+ * The salt binds a particular drawing to a particular holder snapshot — even
+ * if two draws target the same Drand round, distinct holder sets produce
+ * distinct seeds.
+ */
+export function seedFor(randomnessHex, saltHex) {
+ const buf = Buffer.concat([
+ Buffer.from(randomnessHex, 'hex'),
+ Buffer.from(saltHex, 'hex'),
+ ]);
+ return sha256(buf);
+}
+
+/**
+ * Deterministic xorshift-style PRNG over BigInt, seeded by a 32-byte seed.
+ * Used to pick the lottery winner from the cumulative-weight array; same seed
+ * → same winner, so audits are reproducible.
+ */
+export function bigintPRNG(seed) {
+ if (seed.length < 16) throw new Error('seed too short');
+ let s0 = 0n;
+ let s1 = 0n;
+ for (let i = 0; i < 16; i++) s0 |= BigInt(seed[i]) << BigInt(i * 8);
+ for (let i = 0; i < 16; i++) s1 |= BigInt(seed[i + 16] ?? 0) << BigInt(i * 8);
+ const MASK = (1n << 64n) - 1n;
+ let a = s0 & MASK;
+ let b = s1 & MASK;
+ return {
+ next() {
+ // xorshift128+
+ let x = a;
+ const y = b;
+ a = y;
+ x ^= (x << 23n) & MASK;
+ b = (x ^ y ^ (x >> 17n) ^ (y >> 26n)) & MASK;
+ return (b + y) & MASK;
+ },
+ };
+}
+
+/**
+ * Deterministic weighted-random pick. Returns the index of the chosen entry.
+ * weights: array of BigInts; all must be >= 0, sum > 0.
+ *
+ * Algorithm: rejection sampling against the smallest power-of-two upper bound
+ * for `total`. Generate enough random 64-bit chunks to cover that bit length,
+ * mask to exact size, reject and resample if the value lands in the rejection
+ * zone. This keeps the distribution provably uniform over [0, total).
+ */
+export function weightedPick(weights, seed) {
+ let total = 0n;
+ for (const w of weights) {
+ if (w < 0n) throw new Error('negative weight');
+ total += w;
+ }
+ if (total === 0n) throw new Error('empty weight set');
+
+ // Bit length needed to represent values in [0, total).
+ const bits = total === 1n ? 1 : (total - 1n).toString(2).length;
+ const chunks = Math.ceil(bits / 64);
+ const mask = bits >= 1 ? (1n << BigInt(bits)) - 1n : 0n;
+ const prng = bigintPRNG(seed);
+
+ let pick = 0n;
+ let attempts = 0;
+ while (attempts < 256) {
+ pick = 0n;
+ for (let i = 0; i < chunks; i++) {
+ pick = (pick << 64n) | prng.next();
+ }
+ pick &= mask;
+ if (pick < total) break;
+ attempts++;
+ }
+ if (pick >= total) {
+ // Rejection ratio is bounded by 50% per attempt (since `total` is at
+ // least half of `2^bits`), so reaching 256 unsuccessful samples has
+ // probability < 2^-256 — effectively impossible. Surface as an error
+ // rather than silently bias toward the last weight.
+ throw new Error('weightedPick: rejection sampling exhausted');
+ }
+
+ let acc = 0n;
+ for (let i = 0; i < weights.length; i++) {
+ acc += weights[i];
+ if (pick < acc) return i;
+ }
+ throw new Error('weightedPick: walk fell off end (impossible if total > 0)');
+}
+
+/**
+ * sha256 over the canonical (wallet, weight) tuple stream — used as the
+ * weights_hash committed alongside the Drand round number.
+ */
+export function weightsHash(entries) {
+ const sorted = [...entries].sort((a, b) => (a.wallet < b.wallet ? -1 : 1));
+ const lines = sorted.map((e) => `${e.wallet}:${e.weight.toString()}`);
+ const buf = Buffer.from(lines.join('\n'), 'utf-8');
+ return Buffer.from(sha256(buf)).toString('hex');
+}
+
+export const DRAND = {
+ chainHash: QUICKNET_CHAIN_HASH,
+ genesis: QUICKNET_GENESIS,
+ period: QUICKNET_PERIOD,
+ publicKey: QUICKNET_PUBLIC_KEY_HEX,
+};
diff --git a/api/_lib/coin/treasury.js b/api/_lib/coin/treasury.js
new file mode 100644
index 000000000..1d8b6a9bb
--- /dev/null
+++ b/api/_lib/coin/treasury.js
@@ -0,0 +1,195 @@
+// Keypair loaders + SOL transfer helpers for coin distribution.
+//
+// Two keypairs are involved:
+//
+// coin treasury (fee payer + transfer signer)
+// env: COIN_TREASURY_SECRET_KEY_B64
+// purpose: pays tx fees for all distribution ops AND signs SystemProgram.transfer
+// instructions when paying lottery winners / reflection drips. The
+// treasury holds the SOL that was previously claimed from the
+// pump.fun creator vault — distribution is just "move from
+// treasury to holders".
+//
+// coin creator (pump.fun creator address for one specific launch)
+// env: COIN_CREATOR_SECRET_KEY_B64_<MINT>
+// or coin_launches.metadata.creator_secret_b64 (loaded by ID)
+// purpose: signs the `collectCreatorFee` instruction so pump.fun's program
+// releases creator-fee SOL to its associated token account, which
+// then gets unwrapped and routed to the treasury inside the same
+// transaction.
+
+import { Keypair, PublicKey, SystemProgram, Transaction, ComputeBudgetProgram } from '@solana/web3.js';
+import { getConnection } from '../pump.js';
+
+const SOL_LAMPORTS = 1_000_000_000n;
+const TX_MAX_TRANSFERS = 18; // SystemProgram.transfer is ~96 bytes; leaves room for compute-budget ix
+const PRIORITY_MICRO_LAMPORTS = 50_000; // priority fee per CU — moderate competitive level
+
+function decodeB64Keypair(b64, label) {
+ if (!b64) throw new Error(`${label}: env not set`);
+ const raw = Buffer.from(b64, 'base64');
+ if (raw.byteLength !== 64) {
+ throw new Error(`${label}: expected 64-byte secret key, got ${raw.byteLength}`);
+ }
+ return Keypair.fromSecretKey(raw);
+}
+
+/** Load the treasury keypair from env. Throws if unset. */
+export function loadCoinTreasury() {
+ return decodeB64Keypair(process.env.COIN_TREASURY_SECRET_KEY_B64, 'COIN_TREASURY_SECRET_KEY_B64');
+}
+
+/**
+ * Load the pump.fun creator keypair for a specific mint.
+ *
+ * Lookup order:
+ * 1. COIN_CREATOR_SECRET_KEY_B64_<MINT> (env, deploy-time secret)
+ * 2. coin.metadata.creator_secret_b64 (DB, set by the launch script)
+ *
+ * Returns null if neither source is configured (caller decides whether to
+ * fall back to dry-run or error).
+ */
+export function loadCoinCreatorFromCoin(coin) {
+ const mintKey = `COIN_CREATOR_SECRET_KEY_B64_${coin.mint}`;
+ const envValue = process.env[mintKey];
+ if (envValue) return decodeB64Keypair(envValue, mintKey);
+
+ const dbValue = coin?.metadata?.creator_secret_b64;
+ if (dbValue) return decodeB64Keypair(dbValue, 'coin.metadata.creator_secret_b64');
+
+ return null;
+}
+
+/** Lamports → SOL string for log lines. */
+export function lamportsToSol(lamports) {
+ const big = typeof lamports === 'bigint' ? lamports : BigInt(lamports);
+ const whole = big / SOL_LAMPORTS;
+ const frac = big % SOL_LAMPORTS;
+ return `${whole}.${frac.toString().padStart(9, '0')}`;
+}
+
+/**
+ * Confirm a recent signature against the network with a bounded timeout.
+ * Vercel function executions are short-lived; we don't want to hang on
+ * confirmation if the cluster is slow.
+ */
+async function confirmWithTimeout(connection, signature, { commitment = 'confirmed', timeoutMs = 30_000 } = {}) {
+ const start = Date.now();
+ // First try the explicit confirm API; if that errors transiently, fall back
+ // to polling getSignatureStatus.
+ try {
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash(commitment);
+ await connection.confirmTransaction(
+ { signature, blockhash, lastValidBlockHeight },
+ commitment,
+ );
+ return true;
+ } catch {
+ while (Date.now() - start < timeoutMs) {
+ const status = await connection.getSignatureStatus(signature, {
+ searchTransactionHistory: true,
+ });
+ const val = status?.value;
+ if (val?.err) throw new Error('tx_failed: ' + JSON.stringify(val.err));
+ if (val?.confirmationStatus === 'confirmed' || val?.confirmationStatus === 'finalized') {
+ return true;
+ }
+ await new Promise((r) => setTimeout(r, 1_500));
+ }
+ throw new Error('confirm_timeout');
+ }
+}
+
+/**
+ * Send a single SystemProgram.transfer of `lamports` SOL from `from` to `to`.
+ * Returns the tx signature on confirmation. Used for the lottery winner payout.
+ *
+ * @param {object} opts
+ * @param {Keypair} opts.from signing keypair (treasury) — pays fees + transfers
+ * @param {string|PublicKey} opts.to recipient wallet
+ * @param {bigint|number} opts.lamports
+ * @param {'mainnet'|'devnet'} [opts.network]
+ */
+export async function sendSolTransfer({ from, to, lamports, network = 'mainnet' }) {
+ const connection = getConnection({ network });
+ const toPk = typeof to === 'string' ? new PublicKey(to) : to;
+ const amount = typeof lamports === 'bigint' ? lamports : BigInt(lamports);
+ if (amount <= 0n) throw new Error('sendSolTransfer: amount must be > 0');
+
+ const tx = new Transaction();
+ tx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: PRIORITY_MICRO_LAMPORTS }));
+ tx.add(SystemProgram.transfer({ fromPubkey: from.publicKey, toPubkey: toPk, lamports: amount }));
+ tx.feePayer = from.publicKey;
+ const { blockhash } = await connection.getLatestBlockhash('confirmed');
+ tx.recentBlockhash = blockhash;
+ tx.sign(from);
+
+ const raw = tx.serialize();
+ const sig = await connection.sendRawTransaction(raw, { skipPreflight: false, maxRetries: 5 });
+ await confirmWithTimeout(connection, sig);
+ return sig;
+}
+
+/**
+ * Send up to TX_MAX_TRANSFERS SystemProgram.transfer ix in a single tx.
+ * Used as the inner primitive by sendSolBatched().
+ */
+async function sendChunk({ from, transfers, network }) {
+ const connection = getConnection({ network });
+ const tx = new Transaction();
+ tx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: PRIORITY_MICRO_LAMPORTS }));
+ for (const t of transfers) {
+ tx.add(
+ SystemProgram.transfer({
+ fromPubkey: from.publicKey,
+ toPubkey: typeof t.to === 'string' ? new PublicKey(t.to) : t.to,
+ lamports: typeof t.lamports === 'bigint' ? t.lamports : BigInt(t.lamports),
+ }),
+ );
+ }
+ tx.feePayer = from.publicKey;
+ const { blockhash } = await connection.getLatestBlockhash('confirmed');
+ tx.recentBlockhash = blockhash;
+ tx.sign(from);
+
+ const sig = await connection.sendRawTransaction(tx.serialize(), {
+ skipPreflight: false,
+ maxRetries: 5,
+ });
+ await confirmWithTimeout(connection, sig);
+ return sig;
+}
+
+/**
+ * Send a batch of SOL transfers, splitting into multiple transactions when
+ * the batch exceeds TX_MAX_TRANSFERS. Returns an array of result objects
+ * matching the input order; each result has {recipients: [...], signature, error}.
+ *
+ * Failures inside one chunk DO NOT abort the rest — every chunk is attempted
+ * and individually reported, so the caller can mark the successful payouts
+ * confirmed in DB and re-queue the failed ones.
+ *
+ * @param {object} opts
+ * @param {Keypair} opts.from
+ * @param {Array<{ to: string, lamports: bigint|number, ref?: any }>} opts.transfers
+ * @param {'mainnet'|'devnet'} [opts.network]
+ */
+export async function sendSolBatched({ from, transfers, network = 'mainnet' }) {
+ const results = [];
+ for (let i = 0; i < transfers.length; i += TX_MAX_TRANSFERS) {
+ const chunk = transfers.slice(i, i + TX_MAX_TRANSFERS);
+ try {
+ const sig = await sendChunk({ from, transfers: chunk, network });
+ results.push({ recipients: chunk, signature: sig, error: null });
+ } catch (err) {
+ results.push({
+ recipients: chunk,
+ signature: null,
+ error: err?.message || String(err),
+ });
+ }
+ }
+ return results;
+}
+
+export { TX_MAX_TRANSFERS, PRIORITY_MICRO_LAMPORTS };
diff --git a/api/_lib/env.js b/api/_lib/env.js
index c06a6a5a2..c37f660f5 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -243,6 +243,19 @@ export const env = {
return opt('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com');
},
+ // ── Lottery + Reflection coin (api/_lib/coin/*) ───────────────────────
+ // Treasury keypair (base64-encoded 64-byte secret). Fee payer for every
+ // lottery winner transfer + reflection batch transfer. Holds the SOL that
+ // was claimed from the pump.fun creator vault.
+ get COIN_TREASURY_SECRET_KEY_B64() {
+ return opt('COIN_TREASURY_SECRET_KEY_B64');
+ },
+ // Per-mint pump.fun creator keypair, indexed by mint pubkey:
+ // COIN_CREATOR_SECRET_KEY_B64_<MINT_PUBKEY>=<base64-64-byte-secret>
+ // Loaded lazily by api/_lib/coin/treasury.js#loadCoinCreatorFromCoin().
+ // Alternative: store the base64 in coin_launches.metadata.creator_secret_b64
+ // at register time (less secure than env; v2 should move to a KMS).
+
// NFT.Storage API token — required for MintScene tool (uploads GLB + thumbnail + metadata to IPFS).
// Obtain at https://nft.storage. When unset, /api/nft/mint-scene returns 503 not_configured.
get NFT_STORAGE_TOKEN() {
diff --git a/api/_lib/migrations/2026-05-15-avatars-appearance.sql b/api/_lib/migrations/2026-05-15-avatars-appearance.sql
new file mode 100644
index 000000000..f51bc0faa
--- /dev/null
+++ b/api/_lib/migrations/2026-05-15-avatars-appearance.sql
@@ -0,0 +1,29 @@
+-- Avatar appearance: outfit + bone-attached accessories + arbitrary morph weights.
+--
+-- `appearance` is the authoritative state set by the customizer UI / PATCH /api/avatars/:id.
+--
+-- `baked_storage_key` is a derived GLB on R2 where the appearance has been baked
+-- into the geometry (morphs applied, accessory meshes parented to the right bones,
+-- exported as a single GLB). Every viewer that loads the avatar — model-viewer on
+-- /avatars/:id, embed iframes, third-party 3D renderers — gets the dressed avatar
+-- without needing custom client code. This is the same architecture Ready Player Me
+-- uses (the avatar URL you get from their API is already baked).
+--
+-- `appearance_hash` is the sha256 of the canonical appearance JSON the baked GLB
+-- was produced from. When `appearance_hash` doesn't match the current appearance's
+-- hash, the baked GLB is stale and a re-bake is queued. This lets the API decide
+-- which storage key to serve without re-reading R2.
+
+ALTER TABLE avatars
+ ADD COLUMN IF NOT EXISTS appearance jsonb,
+ ADD COLUMN IF NOT EXISTS appearance_hash text,
+ ADD COLUMN IF NOT EXISTS baked_storage_key text,
+ ADD COLUMN IF NOT EXISTS baked_at timestamptz;
+
+-- Quick lookup for the bake worker / lazy-bake path: which avatars have an
+-- appearance set but no matching baked GLB?
+CREATE INDEX IF NOT EXISTS idx_avatars_pending_bake
+ ON avatars (id)
+ WHERE deleted_at IS NULL
+ AND appearance IS NOT NULL
+ AND (baked_storage_key IS NULL OR appearance_hash IS NULL);
diff --git a/api/_lib/migrations/2026-05-15-coin-launches.sql b/api/_lib/migrations/2026-05-15-coin-launches.sql
new file mode 100644
index 000000000..a667422ef
--- /dev/null
+++ b/api/_lib/migrations/2026-05-15-coin-launches.sql
@@ -0,0 +1,138 @@
+-- Migration: coin_launches + holders + events + payouts
+--
+-- Backs the lottery + SOL-reflection coin mechanic.
+-- A row in coin_launches represents one pump.fun token whose creator-fee
+-- inflow is split into a lottery pot (one winner per draw) and a reflection
+-- pot (pro-rata SOL drip to all eligible holders). All payouts are tracked
+-- in coin_payouts with idempotent tx_signature uniqueness.
+--
+-- Idempotent: safe to re-run.
+
+begin;
+
+create table if not exists coin_launches (
+ id uuid primary key default gen_random_uuid(),
+ mint text not null unique, -- pump.fun token mint pubkey
+ name text not null,
+ symbol text not null,
+ network text not null default 'mainnet',
+ creator_wallet text not null, -- wallet receiving pump.fun creator fees
+ -- Allocation in basis points (must sum to 10000)
+ lottery_bps integer not null default 7000,
+ reflection_bps integer not null default 2500,
+ ops_bps integer not null default 500,
+ ops_wallet text, -- where ops cut is sent
+ -- Cadence
+ draw_interval_seconds integer not null default 3600, -- hourly draws
+ reflection_interval_seconds integer not null default 3600, -- hourly reflection batch
+ -- Live pot state (lamports = SOL × 1e9)
+ lottery_pot_lamports bigint not null default 0,
+ reflection_pot_lamports bigint not null default 0,
+ ops_pot_lamports bigint not null default 0,
+ total_claimed_lamports bigint not null default 0,
+ -- Last-action timestamps
+ last_claim_at timestamptz,
+ last_draw_at timestamptz,
+ last_reflection_at timestamptz,
+ last_snapshot_at timestamptz,
+ -- Holder eligibility
+ min_holder_balance bigint not null default 0, -- in token smallest units
+ -- Operational flags
+ is_active boolean not null default true, -- include in cron sweeps
+ is_live boolean not null default false, -- false = dry-run; true = sign + submit
+ -- Audit / metadata
+ metadata jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ check (lottery_bps + reflection_bps + ops_bps = 10000)
+);
+
+create index if not exists coin_launches_active on coin_launches(is_active) where is_active;
+
+create table if not exists coin_holders (
+ id bigserial primary key,
+ coin_id uuid not null references coin_launches(id) on delete cascade,
+ wallet text not null,
+ balance bigint not null default 0, -- token smallest units, last snapshot
+ first_seen timestamptz not null default now(),
+ last_seen timestamptz not null default now(),
+ accrued_reflection_lamports bigint not null default 0, -- pending payout
+ total_reflection_paid_lamports bigint not null default 0,
+ total_lottery_won_lamports bigint not null default 0,
+ last_payout_at timestamptz,
+ unique(coin_id, wallet)
+);
+
+create index if not exists coin_holders_coin_balance
+ on coin_holders(coin_id, balance desc) where balance > 0;
+
+create index if not exists coin_holders_wallet on coin_holders(wallet);
+
+create table if not exists coin_events (
+ id bigserial primary key,
+ coin_id uuid not null references coin_launches(id) on delete cascade,
+ kind text not null, -- fee_claim | lottery_draw | reflection_batch | snapshot | error
+ payload jsonb not null default '{}'::jsonb,
+ tx_signature text,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists coin_events_coin_kind_time
+ on coin_events(coin_id, kind, created_at desc);
+
+create index if not exists coin_events_tx_sig
+ on coin_events(tx_signature) where tx_signature is not null;
+
+create table if not exists coin_payouts (
+ id bigserial primary key,
+ coin_id uuid not null references coin_launches(id) on delete cascade,
+ kind text not null, -- 'lottery' | 'reflection'
+ wallet text not null,
+ amount_lamports bigint not null,
+ -- Reference to the originating draw/batch (so all reflection payouts in a
+ -- single batch share an idempotency key; lottery draws share the draw_id).
+ batch_id text not null,
+ tx_signature text,
+ status text not null default 'pending', -- pending | submitted | confirmed | failed
+ error text,
+ created_at timestamptz not null default now(),
+ submitted_at timestamptz,
+ confirmed_at timestamptz,
+ unique(batch_id, wallet)
+);
+
+create index if not exists coin_payouts_coin_status
+ on coin_payouts(coin_id, status, created_at);
+
+create index if not exists coin_payouts_wallet on coin_payouts(wallet);
+
+create index if not exists coin_payouts_batch on coin_payouts(batch_id);
+
+-- Drand round commitments (verifiable randomness audit trail).
+-- One row per lottery draw: committed at draw start, resolved when the
+-- Drand round's randomness is published.
+create table if not exists coin_draws (
+ id bigserial primary key,
+ coin_id uuid not null references coin_launches(id) on delete cascade,
+ draw_id text not null, -- caller-defined idempotency key (e.g. "<mint>-<unix_hour>")
+ drand_round bigint not null, -- League of Entropy round number used as RNG source
+ drand_randomness text, -- hex randomness once revealed
+ drand_signature text, -- BLS signature for verifier audit
+ pot_lamports bigint not null, -- size of the lottery pot at draw time
+ weights_hash text not null, -- sha256 of the sorted (wallet, weight) tuples
+ holder_count integer not null default 0,
+ winner_wallet text,
+ winner_balance bigint,
+ tx_signature text,
+ status text not null default 'committed', -- committed | resolved | paid | failed
+ error text,
+ created_at timestamptz not null default now(),
+ resolved_at timestamptz,
+ paid_at timestamptz,
+ unique(coin_id, draw_id)
+);
+
+create index if not exists coin_draws_coin_time
+ on coin_draws(coin_id, created_at desc);
+
+commit;
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index 0747146e3..3514e94cd 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -1,6 +1,7 @@
// Reusable zod schemas for API inputs.
import { z } from 'zod';
+import { validateAppearance as _validateAppearance } from './accessories.js';
export const email = z.string().trim().toLowerCase().email().max(254);
export const password = z.string().min(10).max(200);
@@ -14,6 +15,28 @@ export const slug = z
export const avatarVisibility = z.enum(['private', 'unlisted', 'public']);
+// Appearance: outfit + bone-attached accessories + arbitrary morph overrides.
+// Shape is enforced here; preset-ID allowlist enforcement lives in
+// validateAppearance() (accessories.js) and runs as a refine so we get one
+// consolidated 400 with a clear error message.
+export const avatarAppearance = z
+ .object({
+ outfit: z.string().min(1).max(64).nullable().optional(),
+ accessories: z.array(z.string().min(1).max(64)).max(8).optional(),
+ morphs: z.record(z.number().min(0).max(1)).optional(),
+ })
+ .strict()
+ .superRefine((val, ctx) => {
+ const err = _validateAppearance(val);
+ if (err) ctx.addIssue({ code: z.ZodIssueCode.custom, message: err });
+ if (val && val.morphs && Object.keys(val.morphs).length > 32) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: 'appearance.morphs max 32 keys',
+ });
+ }
+ });
+
// Avatars are GLB/GLTF models. Lock the content-type allowlist here so both
// the presign URL and the stored object can only ever be model binaries —
// prevents an attacker uploading HTML/SVG to the public CDN for stored XSS.
@@ -50,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', 'import', 'direct-upload']).default('upload'),
+ source: z.enum(['upload', 'avaturn', 'readyplayer', 'import', 'direct-upload']).default('upload'),
parent_avatar_id: z.string().uuid().optional(),
source_meta: z.record(z.any()).default({}),
content_type: avatarContentType.default('model/gltf-binary'),
@@ -63,6 +86,7 @@ export const createAvatarBody = z.object({
.string()
.regex(/^[a-f0-9]{64}$/)
.optional(),
+ appearance: avatarAppearance.optional(),
});
export const presignUploadBody = z.object({
diff --git a/api/avatars/[id].js b/api/avatars/[id].js
index a5fa45ce6..2beb75cc1 100644
--- a/api/avatars/[id].js
+++ b/api/avatars/[id].js
@@ -11,6 +11,7 @@ import {
resolveAvatarUrl,
stripOwnerFor,
} from '../_lib/avatars.js';
+import { bakeAndUploadAppearance, isBakeable } from '../_lib/bake.js';
import { sql } from '../_lib/db.js';
import { logAudit } from '../_lib/audit.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
@@ -18,7 +19,7 @@ import { headObject } from '../_lib/r2.js';
import { limits } from '../_lib/rate-limit.js';
import { recordEvent } from '../_lib/usage.js';
import { z } from 'zod';
-import { avatarVisibility, parse } from '../_lib/validate.js';
+import { avatarVisibility, avatarAppearance, parse } from '../_lib/validate.js';
import { DEMO_AVATARS } from '../_lib/demo-avatars.js';
const patchSchema = z.object({
@@ -26,10 +27,24 @@ const patchSchema = z.object({
description: z.string().trim().max(2000).optional(),
visibility: avatarVisibility.optional(),
tags: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
+ thumbnail_key: z.string().min(1).max(512).optional(),
+ usdz_key: z.string().min(1).max(512).optional(),
+ halfbody_key: z.string().min(1).max(512).optional(),
+ // `null` clears the dress-up state. Omit the field entirely to leave it untouched.
+ appearance: avatarAppearance.nullable().optional(),
});
// Action endpoints that share this file (no id needed)
-const ACTION_ENDPOINTS = new Set(['presign', 'public', 'regenerate', 'regenerate-status']);
+const ACTION_ENDPOINTS = new Set([
+ 'presign',
+ 'presign-thumbnail',
+ 'presign-usdz',
+ 'presign-halfbody',
+ 'auto-tag',
+ 'public',
+ 'regenerate',
+ 'regenerate-status',
+]);
export default wrap(async (req, res) => {
const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').pop();
@@ -101,8 +116,51 @@ export default wrap(async (req, res) => {
return handleGlbPatch(res, auth, id, body.glbUrl);
}
const patch = parse(patchSchema, body);
- const avatar = await updateAvatar({ id, userId: auth.userId, patch });
+ const appearanceChanged = Object.prototype.hasOwnProperty.call(patch, 'appearance');
+
+ let avatar = await updateAvatar({ id, userId: auth.userId, patch });
if (!avatar) return error(res, 404, 'not_found', 'avatar not found or not yours');
+
+ // When the appearance just changed, run the bake synchronously so the
+ // caller sees the dressed GLB on the very next GET. A failure here is
+ // non-fatal — the appearance is already persisted; the lazy-bake path on
+ // the next read will retry. Bake of an empty appearance clears the cached
+ // baked GLB so the base is served again.
+ if (appearanceChanged) {
+ try {
+ if (isBakeable(patch.appearance)) {
+ const result = await bakeAndUploadAppearance({
+ baseStorageKey: avatar.storage_key,
+ appearance: patch.appearance,
+ });
+ if (result) {
+ avatar = await updateAvatar({
+ id,
+ userId: auth.userId,
+ patch: {
+ baked_storage_key: result.baked_storage_key,
+ appearance_hash: result.appearance_hash,
+ },
+ });
+ }
+ } else {
+ // Empty / cleared appearance — drop the stale baked pointer so the
+ // base GLB is served again.
+ avatar = await updateAvatar({
+ id,
+ userId: auth.userId,
+ patch: { baked_storage_key: null, appearance_hash: null },
+ });
+ }
+ } catch (err) {
+ console.warn('[avatars] bake failed', {
+ avatarId: id,
+ message: err?.message,
+ });
+ avatar.bake_error = err?.message || 'bake_failed';
+ }
+ }
+
return json(res, 200, { avatar });
}
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index a3e6d26a2..740252640 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -157,6 +157,81 @@ const handlePresignThumbnail = wrap(async (req, res) => {
});
});
+// ── presign-usdz ──────────────────────────────────────────────────────────────
+// Called by the browser after a GLB upload completes. The client converts the
+// GLB → USDZ in-memory via three's USDZExporter and PUTs it to R2 here, then
+// PATCHes the avatar row with the returned usdz_key. Enables iOS Quick Look
+// for every avatar without an external USDZ source.
+
+const usdzPresignSchema = z.object({
+ avatar_id: z.string().uuid(),
+ size_bytes: z.number().int().min(1).max(50 * 1024 * 1024), // 50 MB cap — USDZ is larger than GLB
+});
+
+const handlePresignUsdz = wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const userId = await resolvePresignUser(req, 'avatars:write');
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');
+
+ const body = parse(usdzPresignSchema, await readJson(req));
+
+ const rows = await sql`
+ select id, storage_key from avatars
+ where id = ${body.avatar_id} and owner_id = ${userId} and deleted_at is null
+ limit 1
+ `;
+ if (!rows[0]) return error(res, 404, 'not_found', 'avatar not found or not yours');
+
+ const usdzKey = rows[0].storage_key.replace(/\.glb$/i, '') + '.usdz';
+ const uploadUrl = await presignUpload({ key: usdzKey, contentType: 'model/vnd.usdz+zip' });
+
+ return json(res, 200, {
+ usdz_key: usdzKey,
+ upload_url: uploadUrl,
+ method: 'PUT',
+ headers: { 'content-type': 'model/vnd.usdz+zip' },
+ expires_in: 300,
+ });
+});
+
+// ── presign-halfbody ──────────────────────────────────────────────────────────
+// Half-body (waist-up) GLB variant used in VR / first-person seats. Generated
+// client-side by stripping the lower-body bone hierarchy + skinned mesh from
+// the source avatar. Uploaded here, then PATCHed onto the avatar row.
+
+const halfbodyPresignSchema = z.object({
+ avatar_id: z.string().uuid(),
+ size_bytes: z.number().int().min(1).max(25 * 1024 * 1024),
+});
+
+const handlePresignHalfbody = wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const userId = await resolvePresignUser(req, 'avatars:write');
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');
+
+ const body = parse(halfbodyPresignSchema, await readJson(req));
+
+ const rows = await sql`
+ select id, storage_key from avatars
+ where id = ${body.avatar_id} and owner_id = ${userId} and deleted_at is null
+ limit 1
+ `;
+ if (!rows[0]) return error(res, 404, 'not_found', 'avatar not found or not yours');
+
+ const halfKey = rows[0].storage_key.replace(/\.glb$/i, '') + '_halfbody.glb';
+ const uploadUrl = await presignUpload({ key: halfKey, contentType: 'model/gltf-binary' });
+
+ return json(res, 200, {
+ halfbody_key: halfKey,
+ upload_url: uploadUrl,
+ method: 'PUT',
+ headers: { 'content-type': 'model/gltf-binary' },
+ expires_in: 300,
+ });
+});
+
// ── auto-tag ──────────────────────────────────────────────────────────────────
// Called after thumbnail upload; sends the poster to Claude vision for
// auto-generated tags and a one-line description. Non-blocking — a failure
@@ -266,6 +341,8 @@ const handleAutoTag = wrap(async (req, res) => {
const DISPATCH = {
presign: handlePresign,
'presign-thumbnail': handlePresignThumbnail,
+ 'presign-usdz': handlePresignUsdz,
+ 'presign-halfbody': handlePresignHalfbody,
'auto-tag': handleAutoTag,
public: handlePublic,
regenerate: handleRegenerate,
diff --git a/api/avatars/index.js b/api/avatars/index.js
index 24bb87c9f..cf8f1a269 100644
--- a/api/avatars/index.js
+++ b/api/avatars/index.js
@@ -111,7 +111,15 @@ async function handleCreate(req, res) {
// Auto-link selfie-derived avatars to the user's primary agent if it has no avatar yet.
// Fire-and-forget — if this UPDATE fails, the 201 still returns.
- if ((body.source === 'selfie' || body.source === 'avaturn') && auth.source === 'session') {
+ const providerHint = body.source_meta && typeof body.source_meta === 'object'
+ ? String(body.source_meta.provider || '').toLowerCase()
+ : '';
+ const autoLink = body.source === 'avaturn'
+ || body.source === 'readyplayer'
+ || providerHint === 'readyplayer'
+ || providerHint === 'readyplayerme'
+ || providerHint === 'avaturn';
+ if (autoLink && auth.source === 'session') {
queueMicrotask(async () => {
try {
await sql`
diff --git a/api/coin/[action].js b/api/coin/[action].js
new file mode 100644
index 000000000..cca1e8dcc
--- /dev/null
+++ b/api/coin/[action].js
@@ -0,0 +1,359 @@
+// Public read-only API for the lottery + reflection coin.
+//
+// Routes (via vercel.json rewrites):
+// GET /api/coin/state?mint=XXX
+// GET /api/coin/holder?mint=XXX&wallet=YYY
+// GET /api/coin/history?mint=XXX&limit=20
+// GET /api/coin/events?mint=XXX&limit=50&kind=<event_kind>
+// GET /api/coin/winners?mint=XXX&limit=20
+// GET /api/coin/holders?mint=XXX&limit=50
+//
+// Caller may omit `mint` when exactly one active coin exists — the API picks
+// it automatically so the public dashboard can run on /coin without any
+// query parameter for the common single-launch case.
+//
+// All `*_lamports` values are returned as strings to preserve precision on
+// the JSON wire (Number can't safely represent values > 2^53).
+
+import { sql } from '../_lib/db.js';
+import { cors, error, json, method, wrap } from '../_lib/http.js';
+import { listActiveCoins, loadCoinByMint } from '../_lib/coin/index.js';
+
+function bigStr(v) {
+ if (v === null || v === undefined) return null;
+ return String(v);
+}
+
+async function resolveCoin(req) {
+ const mint = req.query?.mint?.toString();
+ if (mint) {
+ const coin = await loadCoinByMint(mint);
+ if (!coin) return { coin: null, err: 'coin_not_found' };
+ return { coin, err: null };
+ }
+ const coins = await listActiveCoins();
+ if (coins.length === 1) return { coin: coins[0], err: null };
+ if (coins.length === 0) return { coin: null, err: 'no_active_coins' };
+ return { coin: null, err: 'multiple_active_coins_specify_mint' };
+}
+
+async function handleState(req, res) {
+ const { coin, err } = await resolveCoin(req);
+ if (err) return error(res, 404, err, err.replace(/_/g, ' '));
+
+ const [holdersAgg] = await sql`
+ select
+ count(*) filter (where balance > ${coin.min_holder_balance}::bigint) as eligible,
+ count(*) filter (where balance > 0) as total_with_balance,
+ coalesce(sum(balance::numeric) filter (where balance > 0), 0)::text as supply_held,
+ coalesce(sum(total_reflection_paid_lamports::numeric), 0)::text as total_reflection_paid,
+ coalesce(sum(total_lottery_won_lamports::numeric), 0)::text as total_lottery_paid
+ from coin_holders
+ where coin_id = ${coin.id}
+ `;
+
+ const [pendingPayouts] = await sql`
+ select
+ count(*)::int as pending_count,
+ coalesce(sum(amount_lamports::numeric), 0)::text as pending_lamports
+ from coin_payouts
+ where coin_id = ${coin.id} and status in ('pending', 'submitted')
+ `;
+
+ const [latestDraw] = await sql`
+ select draw_id, drand_round, pot_lamports::text as pot, winner_wallet, status, created_at, resolved_at, paid_at
+ from coin_draws
+ where coin_id = ${coin.id}
+ order by created_at desc
+ limit 1
+ `;
+
+ const nowMs = Date.now();
+ const interval = coin.draw_interval_seconds * 1000;
+ const nextDrawAt = new Date(Math.ceil(nowMs / interval) * interval).toISOString();
+
+ return json(res, 200, {
+ mint: coin.mint,
+ name: coin.name,
+ symbol: coin.symbol,
+ network: coin.network,
+ is_live: coin.is_live,
+ pots: {
+ lottery_lamports: bigStr(coin.lottery_pot_lamports),
+ reflection_lamports: bigStr(coin.reflection_pot_lamports),
+ ops_lamports: bigStr(coin.ops_pot_lamports),
+ total_claimed_lamports: bigStr(coin.total_claimed_lamports),
+ },
+ allocation_bps: {
+ lottery: coin.lottery_bps,
+ reflection: coin.reflection_bps,
+ ops: coin.ops_bps,
+ },
+ cadence: {
+ draw_interval_seconds: coin.draw_interval_seconds,
+ reflection_interval_seconds: coin.reflection_interval_seconds,
+ next_draw_at: nextDrawAt,
+ last_claim_at: coin.last_claim_at,
+ last_draw_at: coin.last_draw_at,
+ last_reflection_at: coin.last_reflection_at,
+ last_snapshot_at: coin.last_snapshot_at,
+ },
+ holders: {
+ eligible: Number(holdersAgg?.eligible || 0),
+ total: Number(holdersAgg?.total_with_balance || 0),
+ supply_held: holdersAgg?.supply_held || '0',
+ min_balance: bigStr(coin.min_holder_balance),
+ },
+ paid_total: {
+ reflection_lamports: holdersAgg?.total_reflection_paid || '0',
+ lottery_lamports: holdersAgg?.total_lottery_paid || '0',
+ },
+ pending_payouts: {
+ count: Number(pendingPayouts?.pending_count || 0),
+ lamports: pendingPayouts?.pending_lamports || '0',
+ },
+ latest_draw: latestDraw
+ ? {
+ draw_id: latestDraw.draw_id,
+ drand_round: Number(latestDraw.drand_round),
+ pot_lamports: latestDraw.pot,
+ winner: latestDraw.winner_wallet,
+ status: latestDraw.status,
+ created_at: latestDraw.created_at,
+ resolved_at: latestDraw.resolved_at,
+ paid_at: latestDraw.paid_at,
+ }
+ : null,
+ });
+}
+
+async function handleHolder(req, res) {
+ const { coin, err } = await resolveCoin(req);
+ if (err) return error(res, 404, err, err.replace(/_/g, ' '));
+ const wallet = req.query?.wallet?.toString();
+ if (!wallet) return error(res, 400, 'validation_error', 'wallet is required');
+
+ const [row] = await sql`
+ select wallet, balance::text as balance,
+ accrued_reflection_lamports::text as accrued,
+ total_reflection_paid_lamports::text as total_reflection,
+ total_lottery_won_lamports::text as total_lottery,
+ first_seen, last_seen, last_payout_at
+ from coin_holders
+ where coin_id = ${coin.id} and wallet = ${wallet}
+ limit 1
+ `;
+ if (!row) {
+ return json(res, 200, {
+ mint: coin.mint,
+ wallet,
+ balance: '0',
+ accrued_reflection_lamports: '0',
+ total_reflection_paid_lamports: '0',
+ total_lottery_won_lamports: '0',
+ recent_payouts: [],
+ recent_wins: [],
+ });
+ }
+
+ const recentPayouts = await sql`
+ select kind, amount_lamports::text as amount, batch_id, tx_signature, status, created_at, confirmed_at
+ from coin_payouts
+ where coin_id = ${coin.id} and wallet = ${wallet}
+ order by created_at desc
+ limit 25
+ `;
+ const wins = recentPayouts.filter((p) => p.kind === 'lottery');
+
+ return json(res, 200, {
+ mint: coin.mint,
+ wallet: row.wallet,
+ balance: row.balance,
+ accrued_reflection_lamports: row.accrued,
+ total_reflection_paid_lamports: row.total_reflection,
+ total_lottery_won_lamports: row.total_lottery,
+ first_seen: row.first_seen,
+ last_seen: row.last_seen,
+ last_payout_at: row.last_payout_at,
+ recent_payouts: recentPayouts.map((p) => ({
+ kind: p.kind,
+ amount_lamports: p.amount,
+ batch_id: p.batch_id,
+ tx_signature: p.tx_signature,
+ status: p.status,
+ created_at: p.created_at,
+ confirmed_at: p.confirmed_at,
+ })),
+ recent_wins: wins.map((w) => ({
+ amount_lamports: w.amount,
+ tx_signature: w.tx_signature,
+ created_at: w.created_at,
+ })),
+ });
+}
+
+async function handleHistory(req, res) {
+ const { coin, err } = await resolveCoin(req);
+ if (err) return error(res, 404, err, err.replace(/_/g, ' '));
+ const limit = Math.min(parseInt(req.query?.limit || '20', 10), 100);
+
+ const fees = await sql`
+ select payload, tx_signature, created_at
+ from coin_events
+ where coin_id = ${coin.id} and kind = 'fee_claim'
+ order by created_at desc
+ limit ${limit}
+ `;
+ const draws = await sql`
+ select draw_id, drand_round, pot_lamports::text as pot, winner_wallet, status,
+ drand_randomness, tx_signature, created_at, resolved_at, paid_at
+ from coin_draws
+ where coin_id = ${coin.id}
+ order by created_at desc
+ limit ${limit}
+ `;
+ const reflections = await sql`
+ select payload, tx_signature, created_at
+ from coin_events
+ where coin_id = ${coin.id} and kind = 'reflection_batch'
+ order by created_at desc
+ limit ${limit}
+ `;
+
+ return json(res, 200, {
+ mint: coin.mint,
+ fee_claims: fees.map((r) => ({
+ claimed_lamports: r.payload?.claimed,
+ lottery_lamports: r.payload?.lottery,
+ reflection_lamports: r.payload?.reflection,
+ ops_lamports: r.payload?.ops,
+ tx_signature: r.tx_signature,
+ created_at: r.created_at,
+ })),
+ draws: draws.map((d) => ({
+ draw_id: d.draw_id,
+ drand_round: Number(d.drand_round),
+ pot_lamports: d.pot,
+ winner: d.winner_wallet,
+ status: d.status,
+ drand_randomness: d.drand_randomness,
+ tx_signature: d.tx_signature,
+ created_at: d.created_at,
+ resolved_at: d.resolved_at,
+ paid_at: d.paid_at,
+ })),
+ reflection_batches: reflections.map((r) => ({
+ batch_id: r.payload?.batch_id,
+ queued: r.payload?.queued,
+ allocated_lamports: r.payload?.allocated,
+ tx_signature: r.tx_signature,
+ created_at: r.created_at,
+ })),
+ });
+}
+
+async function handleEvents(req, res) {
+ const { coin, err } = await resolveCoin(req);
+ if (err) return error(res, 404, err, err.replace(/_/g, ' '));
+ const limit = Math.min(parseInt(req.query?.limit || '50', 10), 200);
+ const kind = req.query?.kind?.toString() || null;
+
+ const rows = kind
+ ? await sql`
+ select kind, payload, tx_signature, created_at
+ from coin_events
+ where coin_id = ${coin.id} and kind = ${kind}
+ order by created_at desc
+ limit ${limit}
+ `
+ : await sql`
+ select kind, payload, tx_signature, created_at
+ from coin_events
+ where coin_id = ${coin.id}
+ order by created_at desc
+ limit ${limit}
+ `;
+ return json(res, 200, {
+ mint: coin.mint,
+ events: rows.map((r) => ({
+ kind: r.kind,
+ payload: r.payload,
+ tx_signature: r.tx_signature,
+ created_at: r.created_at,
+ })),
+ });
+}
+
+async function handleWinners(req, res) {
+ const { coin, err } = await resolveCoin(req);
+ if (err) return error(res, 404, err, err.replace(/_/g, ' '));
+ const limit = Math.min(parseInt(req.query?.limit || '20', 10), 100);
+ const rows = await sql`
+ select draw_id, drand_round, pot_lamports::text as pot, winner_wallet,
+ drand_randomness, tx_signature, status, created_at, paid_at
+ from coin_draws
+ where coin_id = ${coin.id} and winner_wallet is not null
+ order by created_at desc
+ limit ${limit}
+ `;
+ return json(res, 200, {
+ mint: coin.mint,
+ winners: rows.map((r) => ({
+ draw_id: r.draw_id,
+ drand_round: Number(r.drand_round),
+ amount_lamports: r.pot,
+ wallet: r.winner_wallet,
+ drand_randomness: r.drand_randomness,
+ tx_signature: r.tx_signature,
+ status: r.status,
+ created_at: r.created_at,
+ paid_at: r.paid_at,
+ })),
+ });
+}
+
+async function handleHolders(req, res) {
+ const { coin, err } = await resolveCoin(req);
+ if (err) return error(res, 404, err, err.replace(/_/g, ' '));
+ const limit = Math.min(parseInt(req.query?.limit || '50', 10), 500);
+ const rows = await sql`
+ select wallet, balance::text as balance,
+ accrued_reflection_lamports::text as accrued,
+ total_reflection_paid_lamports::text as total_reflection,
+ total_lottery_won_lamports::text as total_lottery
+ from coin_holders
+ where coin_id = ${coin.id} and balance > 0
+ order by balance::numeric desc
+ limit ${limit}
+ `;
+ return json(res, 200, {
+ mint: coin.mint,
+ holders: rows.map((r, i) => ({
+ rank: i + 1,
+ wallet: r.wallet,
+ balance: r.balance,
+ accrued_reflection_lamports: r.accrued,
+ total_reflection_paid_lamports: r.total_reflection,
+ total_lottery_won_lamports: r.total_lottery,
+ })),
+ });
+}
+
+const HANDLERS = {
+ state: handleState,
+ holder: handleHolder,
+ history: handleHistory,
+ events: handleEvents,
+ winners: handleWinners,
+ holders: handleHolders,
+};
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const action = req.query?.action;
+ const handler = typeof action === 'string' ? HANDLERS[action] : null;
+ if (!handler) return error(res, 404, 'not_found', 'unknown action');
+ return handler(req, res);
+});
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 029153ea5..6c00748e3 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -70,6 +70,8 @@ const HANDLERS = {
'run-x-scheduled-posts': handleRunXScheduledPosts,
'run-x-triggers': handleRunXTriggers,
'fetch-x-metrics': handleFetchXMetrics,
+ 'run-coin-cycle': handleRunCoinCycle,
+ 'run-coin-payouts': handleRunCoinPayouts,
};
export default wrap(async (req, res) => {
@@ -2915,3 +2917,144 @@ async function handleFetchXMetrics(req, res) {
return json(res, 200, report);
}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// run-coin-cycle
+// ═══════════════════════════════════════════════════════════════════════════
+//
+// One unified pass over every active coin_launches row:
+// 1. refresh holder snapshot via Helius RPC
+// 2. claim creator-vault SOL from pump.fun and split into pots
+// 3. commit the next lottery draw (one per draw_interval_seconds)
+// 4. resolve any committed draws whose Drand round has been published
+// 5. allocate the reflection pot pro-rata to eligible holders
+//
+// Payouts (SOL transfers) are NOT done here — see run-coin-payouts which
+// drains the coin_payouts queue. Splitting these two crons means a slow
+// or stuck payout tx can't block the next cycle from being committed.
+//
+// Scheduled every 5 minutes by Vercel. Each step is idempotent — running
+// twice within the same draw/reflection bucket is a no-op.
+
+async function handleRunCoinCycle(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ const coinLib = await import('../_lib/coin/index.js');
+ const coins = await coinLib.listActiveCoins();
+
+ const phaseFilter = (req.query?.phase || '').toString();
+ const onlyPhase = phaseFilter
+ ? new Set(phaseFilter.split(',').map((s) => s.trim()).filter(Boolean))
+ : null;
+ const wantPhase = (name) => !onlyPhase || onlyPhase.has(name);
+
+ const report = { coins: [], errors: [] };
+
+ for (const coin of coins) {
+ const result = { mint: coin.mint, symbol: coin.symbol, steps: {} };
+ try {
+ if (wantPhase('snapshot')) {
+ result.steps.snapshot = await coinLib.snapshotHolders(coin);
+ }
+ } catch (err) {
+ result.steps.snapshot = { error: err.message || String(err) };
+ report.errors.push({ mint: coin.mint, step: 'snapshot', error: result.steps.snapshot.error });
+ }
+
+ // Refresh row after snapshot so we have current last_snapshot_at.
+ const refreshed1 = await coinLib.loadCoinById(coin.id);
+ const c1 = refreshed1 || coin;
+
+ try {
+ if (wantPhase('claim')) {
+ result.steps.claim = await coinLib.claimAndSplit(c1);
+ }
+ } catch (err) {
+ result.steps.claim = { error: err.message || String(err) };
+ report.errors.push({ mint: coin.mint, step: 'claim', error: result.steps.claim.error });
+ }
+
+ const refreshed2 = await coinLib.loadCoinById(coin.id);
+ const c2 = refreshed2 || c1;
+
+ try {
+ if (wantPhase('commit')) {
+ result.steps.commit_lottery = await coinLib.commitLottery(c2);
+ }
+ } catch (err) {
+ result.steps.commit_lottery = { error: err.message || String(err) };
+ report.errors.push({ mint: coin.mint, step: 'commit_lottery', error: result.steps.commit_lottery.error });
+ }
+
+ try {
+ if (wantPhase('resolve')) {
+ result.steps.resolve_lottery = await coinLib.resolvePendingDraws(c2);
+ }
+ } catch (err) {
+ result.steps.resolve_lottery = { error: err.message || String(err) };
+ report.errors.push({ mint: coin.mint, step: 'resolve_lottery', error: result.steps.resolve_lottery.error });
+ }
+
+ const refreshed3 = await coinLib.loadCoinById(coin.id);
+ const c3 = refreshed3 || c2;
+
+ try {
+ if (wantPhase('reflection')) {
+ result.steps.reflection = await coinLib.allocateReflection(c3);
+ }
+ } catch (err) {
+ result.steps.reflection = { error: err.message || String(err) };
+ report.errors.push({ mint: coin.mint, step: 'reflection', error: result.steps.reflection.error });
+ }
+
+ report.coins.push(result);
+ }
+
+ return json(res, 200, { ok: true, processed: report.coins.length, report });
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// run-coin-payouts
+// ═══════════════════════════════════════════════════════════════════════════
+//
+// Drains pending coin_payouts rows for every active coin. Each row already has
+// a committed amount + recipient (queued by run-coin-cycle); this cron just
+// signs + submits the batched SystemProgram.transfer txs.
+//
+// Runs on a separate schedule from run-coin-cycle so RPC issues on the
+// payout side never block fresh draws/reflection from being committed.
+
+async function handleRunCoinPayouts(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ const coinLib = await import('../_lib/coin/index.js');
+ const coins = await coinLib.listActiveCoins();
+
+ const report = { coins: [], errors: [] };
+ for (const coin of coins) {
+ try {
+ const result = await coinLib.drainPendingPayouts(coin);
+ report.coins.push({ mint: coin.mint, ...result });
+ } catch (err) {
+ report.errors.push({ mint: coin.mint, error: err.message || String(err) });
+ }
+ }
+
+ return json(res, 200, { ok: true, processed: report.coins.length, report });
+}
diff --git a/avatar-sdk/LICENSE b/avatar-sdk/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/avatar-sdk/LICENSE
@@ -0,0 +1,180 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship made available under
+ the License, as indicated by a copyright notice that is included in
+ or attached to the work (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other transformations
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
+ in the Work by the copyright owner or by an individual or Legal Entity
+ authorized to submit on behalf of the copyright owner. For the purposes
+ of this definition, "submitted" means any form of electronic, verbal,
+ or written communication sent to the Licensor or its representatives,
+ including but not limited to communication on electronic mailing lists,
+ source code control systems, and issue tracking systems that are managed
+ by, or on behalf of, the Licensor for the purpose of discussing and
+ improving the Work, but excluding communication that is conspicuously
+ marked or designated in writing by the copyright owner as "Not a
+ Contribution."
+
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
+ whom a Contribution has been received by the Licensor and included
+ within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by the combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a cross-claim
+ or counterclaim in a lawsuit) alleging that the Work or any
+ Contribution embodied within the Work constitutes direct or contributory
+ patent infringement, then any patent licenses granted to You under
+ this License for that Work shall terminate as of the date such
+ litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative
+ Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, You must include a readable copy of the
+ attribution notices contained within such NOTICE file, in
+ at least one of the following places: within a NOTICE text
+ file distributed as part of the Derivative Works; within
+ the Source form or documentation, if provided along with the
+ Derivative Works; or, within a display generated by the
+ Derivative Works, if and wherever such third-party notices
+ normally appear. The contents of the NOTICE file are for
+ informational purposes only and do not modify the License.
+ You may add Your own attribution notices within Derivative
+ Works that You distribute, alongside or in addition to the
+ NOTICE text from the Work, provided that such additional
+ attribution notices cannot be construed as modifying the License.
+
+ You may add Your own license statement for Your modifications and
+ may provide additional grant of rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the
+ Derivative Works, and to permit persons to whom the Derivative Works
+ are furnished to do so.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or reproducing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or exemplary damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or all other
+ commercial damages or losses), even if such Contributor has been
+ advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may offer only
+ conditions consistent with this License.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/avatar-sdk/README.md b/avatar-sdk/README.md
new file mode 100644
index 000000000..2597e5ac2
--- /dev/null
+++ b/avatar-sdk/README.md
@@ -0,0 +1,73 @@
+# @three-ws/avatar
+
+3D avatar viewer, creator iframe, and emotion + lipsync runtime — a drop-in replacement for the Ready Player Me SDK now that RPM was acquired and is no longer accepting new accounts.
+
+Includes:
+
+- **`<agent-3d>` web component** — declarative avatar viewer with built-in chat/voice loop, emotion morphs, audio-driven viseme lipsync, AR Quick Look (iOS) and WebXR (Android/Quest).
+- **`AvatarCreator`** — programmatic iframe modal that wraps the [Character Studio](https://studio.three.ws) builder and the [Avaturn](https://avaturn.me) photo-to-avatar pipeline. Resolves with a GLB Blob.
+- **`saveBlob()`** — uploads a freshly-created GLB to the hosted three.ws backend (R2 storage, auto-thumbnail, USDZ companion auto-generation).
+
+## Install
+
+```bash
+npm install @three-ws/avatar three
+```
+
+`three` is a peer dependency.
+
+## Use the web component
+
+```html
+<script type="module">
+ import '@three-ws/avatar';
+</script>
+
+<agent-3d avatar-id="00000000-1111-2222-3333-444444444444"></agent-3d>
+```
+
+Or with a direct GLB URL:
+
+```html
+<agent-3d src="https://example.com/my-avatar.glb"></agent-3d>
+```
+
+## Open the avatar creator
+
+```js
+import { AvatarCreator, saveBlob } from '@three-ws/avatar/creator';
+
+const creator = new AvatarCreator({
+ onExport: async (glbBlob) => {
+ const avatar = await saveBlob(glbBlob, {
+ bearerToken: 'YOUR_THREE_WS_TOKEN',
+ name: 'My Avatar',
+ visibility: 'public',
+ });
+ console.log('Saved:', avatar.url);
+ },
+});
+
+creator.open();
+```
+
+If you have a previously created avatar and want to re-open it for editing, first call your backend's `/api/avatars/:id/session` (which POSTs to Avaturn under the hood) and pass `avaturnSessionUrl` to the constructor.
+
+## What this gives you that Ready Player Me did
+
+| RPM feature | `@three-ws/avatar` equivalent |
+|---|---|
+| Photo → 3D avatar | `AvatarCreator` → Avaturn pipeline |
+| In-browser avatar editor | `AvatarCreator` → [Character Studio](https://studio.three.ws) |
+| Hosted CDN | three.ws R2 + presigned uploads (free public tier) |
+| ARKit `viseme_*` morphs | Loaded automatically into the runtime |
+| Mixamo-compatible humanoid rig | Yes — same skeleton naming conventions |
+| Animation library | 50+ Mixamo clips bundled (idle, wave, nod, dance, …) |
+| iOS Quick Look USDZ | Auto-generated server-side on first upload |
+| Half-body variant | Auto-generated for VR seats |
+| Web component embed | `<agent-3d>` |
+| React component | `<agent-3d>` (works in React 18+ via the JSX intrinsic) |
+
+## License
+
+Apache-2.0. See `LICENSE` in the repo root.
diff --git a/avatar-sdk/build.mjs b/avatar-sdk/build.mjs
new file mode 100644
index 000000000..341422a8b
--- /dev/null
+++ b/avatar-sdk/build.mjs
@@ -0,0 +1,41 @@
+#!/usr/bin/env node
+// Build @three-ws/avatar by copying the prebuilt CDN bundle out of the parent
+// repo's dist-lib/ into this package's dist/. The CDN bundle is built by
+// `npm run build:lib` at the root of the repo and is already self-contained
+// (Three.js inlined, side-effectful custom-element registration on import).
+//
+// We do NOT re-bundle here — Vite has already produced a single ES module
+// suitable for both browser <script type="module"> use and bundler consumption.
+// All this script does is materialise that file as dist/index.mjs plus an
+// empty stylesheet placeholder (kept for forward-compatibility with the
+// "@three-ws/avatar/style.css" subpath import).
+
+import { copyFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(here, '..');
+
+const src = resolve(repoRoot, 'dist-lib', 'agent-3d.js');
+if (!existsSync(src)) {
+ console.error(
+ '[avatar-sdk] dist-lib/agent-3d.js is missing — run `npm run build:lib` at the repo root first.',
+ );
+ process.exit(1);
+}
+
+const outDir = resolve(here, 'dist');
+mkdirSync(outDir, { recursive: true });
+
+copyFileSync(src, resolve(outDir, 'index.mjs'));
+
+// Stylesheet stub. The custom element injects its own styles, so this is empty
+// — but consumers that bundle ".css" side-effect imports get a no-op instead
+// of a missing-file error.
+writeFileSync(
+ resolve(outDir, 'style.css'),
+ '/* @three-ws/avatar — styles are injected by the custom element at runtime. */\n',
+);
+
+console.log('[avatar-sdk] built dist/index.mjs from dist-lib/agent-3d.js');
diff --git a/avatar-sdk/package.json b/avatar-sdk/package.json
new file mode 100644
index 000000000..f6602ffd3
--- /dev/null
+++ b/avatar-sdk/package.json
@@ -0,0 +1,71 @@
+{
+ "name": "@three-ws/avatar",
+ "version": "0.1.0",
+ "description": "3D avatar viewer, creator iframe, and emotion + lipsync runtime — drop-in replacement for Ready Player Me.",
+ "keywords": [
+ "3d",
+ "avatar",
+ "three.js",
+ "webgl",
+ "webxr",
+ "ar",
+ "vr",
+ "lipsync",
+ "viseme",
+ "web-component",
+ "readyplayerme",
+ "ready-player-me"
+ ],
+ "author": "three.ws",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/nirholas/three.ws.git",
+ "directory": "avatar-sdk"
+ },
+ "type": "module",
+ "main": "./dist/index.mjs",
+ "module": "./dist/index.mjs",
+ "types": "./types/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./types/index.d.ts",
+ "import": "./dist/index.mjs",
+ "default": "./dist/index.mjs"
+ },
+ "./creator": {
+ "types": "./types/creator.d.ts",
+ "import": "./src/creator.js",
+ "default": "./src/creator.js"
+ },
+ "./element": {
+ "types": "./types/element.d.ts",
+ "import": "./dist/index.mjs",
+ "default": "./dist/index.mjs"
+ },
+ "./style.css": "./dist/style.css"
+ },
+ "files": [
+ "dist",
+ "src",
+ "types",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "build": "node build.mjs",
+ "prepublishOnly": "npm run build"
+ },
+ "peerDependencies": {
+ "three": ">=0.150.0"
+ },
+ "peerDependenciesMeta": {
+ "three": {
+ "optional": false
+ }
+ },
+ "engines": {
+ "node": ">=18"
+ }
+}
diff --git a/avatar-sdk/src/creator.js b/avatar-sdk/src/creator.js
new file mode 100644
index 000000000..0ce46d65e
--- /dev/null
+++ b/avatar-sdk/src/creator.js
@@ -0,0 +1,237 @@
+// Programmatic Avatar Creator — opens an iframe modal where the user builds
+// or photographs an avatar via Character Studio or Avaturn, listens for the
+// `export` postMessage, and resolves with the GLB Blob.
+//
+// This is the thin client-only wrapper. Apps that already have their own
+// session/auth flow are expected to:
+// 1) call AvatarCreator.open()
+// 2) await onExport(blob)
+// 3) PUT the blob to whatever storage they like.
+//
+// For the hosted three.ws backend (R2 + presigned uploads + auto-tag), use
+// the `saveBlob()` helper instead, which posts to three.ws's /api/avatars
+// pipeline using a bearer token.
+
+const DEFAULT_STUDIO_URL = 'https://studio.three.ws';
+const DEFAULT_THREE_WS_ORIGIN = 'https://three.ws';
+
+export class AvatarCreator {
+ /**
+ * @param {object} opts
+ * @param {HTMLElement} [opts.container] — DOM node to mount the modal into. Defaults to document.body.
+ * @param {string} [opts.studioUrl] — origin of the Character Studio iframe. Defaults to studio.three.ws.
+ * @param {string} [opts.avaturnSessionUrl] — if provided, opens Avaturn in edit mode for that session.
+ * @param {(blob: Blob) => any} [opts.onExport] — called with the GLB Blob when the user exports.
+ * @param {() => any} [opts.onClose] — called when the user closes without exporting.
+ */
+ constructor(opts = {}) {
+ this.container = opts.container || (typeof document !== 'undefined' ? document.body : null);
+ this.studioUrl = (opts.studioUrl || DEFAULT_STUDIO_URL).replace(/\/$/, '');
+ this.avaturnSessionUrl = opts.avaturnSessionUrl || null;
+ this.onExport = opts.onExport || null;
+ this.onClose = opts.onClose || null;
+
+ this._modal = null;
+ this._iframe = null;
+ this._onMessage = null;
+ this._onKeyDown = null;
+ }
+
+ async open() {
+ if (this._modal) return;
+ this._buildModal();
+ this._onMessage = (e) => this._handleMessage(e);
+ window.addEventListener('message', this._onMessage);
+ this._iframe.src = this.avaturnSessionUrl || this.studioUrl;
+ }
+
+ close() {
+ if (this._onMessage) {
+ window.removeEventListener('message', this._onMessage);
+ this._onMessage = null;
+ }
+ if (this._onKeyDown) {
+ document.removeEventListener('keydown', this._onKeyDown);
+ this._onKeyDown = null;
+ }
+ if (this._modal) {
+ this._modal.remove();
+ this._modal = null;
+ this._iframe = null;
+ this.onClose?.();
+ }
+ }
+
+ dispose() {
+ this.close();
+ }
+
+ _buildModal() {
+ this._modal = document.createElement('div');
+ this._modal.style.cssText = [
+ 'position:fixed', 'inset:0', 'z-index:2147483646',
+ 'background:rgba(0,0,0,0.78)', 'display:flex',
+ 'align-items:center', 'justify-content:center',
+ ].join(';');
+
+ const card = document.createElement('div');
+ card.style.cssText = [
+ 'background:#111', 'border-radius:12px',
+ 'width:min(960px,96vw)', 'height:min(720px,92vh)',
+ 'position:relative', 'overflow:hidden',
+ ].join(';');
+
+ this._iframe = document.createElement('iframe');
+ this._iframe.title = 'Avatar Creator';
+ this._iframe.allow = 'camera *; microphone *; clipboard-write';
+ this._iframe.style.cssText = 'width:100%;height:100%;border:0;display:block';
+ card.appendChild(this._iframe);
+
+ const closeBtn = document.createElement('button');
+ closeBtn.type = 'button';
+ closeBtn.setAttribute('aria-label', 'Close');
+ closeBtn.textContent = '×';
+ closeBtn.style.cssText = [
+ 'position:absolute', 'top:8px', 'right:10px', 'z-index:1',
+ 'background:rgba(0,0,0,0.4)', 'color:#fff', 'border:0',
+ 'width:32px', 'height:32px', 'border-radius:50%',
+ 'font-size:20px', 'line-height:30px', 'cursor:pointer',
+ ].join(';');
+ closeBtn.addEventListener('click', () => this.close());
+ card.appendChild(closeBtn);
+
+ this._modal.appendChild(card);
+ this._modal.addEventListener('click', (e) => {
+ if (e.target === this._modal) this.close();
+ });
+
+ this._onKeyDown = (e) => {
+ if (e.key === 'Escape') this.close();
+ };
+ document.addEventListener('keydown', this._onKeyDown);
+
+ this.container.appendChild(this._modal);
+ }
+
+ _handleMessage(event) {
+ // Character Studio: { source:'characterstudio', type:'export', glb: ArrayBuffer }
+ // Avaturn: { source:'avaturn', eventName:'export', data:{ url, urlType } }
+ const msg = event.data;
+ if (!msg || typeof msg !== 'object') return;
+
+ // Trust check — message must come from the iframe we opened.
+ try {
+ const expected = new URL(this._iframe.src).origin;
+ if (event.origin !== expected) return;
+ } catch {
+ return;
+ }
+
+ if (msg.source === 'characterstudio' && msg.type === 'export' && msg.glb instanceof ArrayBuffer) {
+ this._fire(new Blob([msg.glb], { type: 'model/gltf-binary' }));
+ return;
+ }
+ if (msg.source === 'avaturn' && msg.eventName === 'export' && msg.data?.url) {
+ this._fetchAndFire(msg.data.url);
+ }
+ }
+
+ async _fetchAndFire(url) {
+ try {
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`avatar fetch failed: ${res.status}`);
+ const blob = await res.blob();
+ const typed = blob.type
+ ? blob
+ : new Blob([await blob.arrayBuffer()], { type: 'model/gltf-binary' });
+ this._fire(typed);
+ } catch (err) {
+ console.error('[@three-ws/avatar] avaturn export fetch failed:', err);
+ }
+ }
+
+ _fire(blob) {
+ try {
+ this.onExport?.(blob);
+ } catch (err) {
+ console.error('[@three-ws/avatar] onExport threw:', err);
+ }
+ this.close();
+ }
+}
+
+/**
+ * Upload a freshly created GLB to a three.ws-compatible backend.
+ *
+ * @param {Blob} blob — GLB blob returned by AvatarCreator.
+ * @param {object} opts
+ * @param {string} opts.bearerToken — OAuth/API token with `avatars:write` scope.
+ * @param {string} [opts.apiOrigin] — defaults to https://three.ws.
+ * @param {string} [opts.name] — avatar display name.
+ * @param {string} [opts.description] — optional description.
+ * @param {string[]} [opts.tags] — optional tag list.
+ * @param {'public'|'unlisted'|'private'} [opts.visibility] — defaults to 'public'.
+ * @returns {Promise<{ id: string, url: string, slug: string }>}
+ */
+export async function saveBlob(blob, opts) {
+ if (!opts?.bearerToken) throw new Error('saveBlob: bearerToken is required');
+ const origin = (opts.apiOrigin || DEFAULT_THREE_WS_ORIGIN).replace(/\/$/, '');
+ const headers = {
+ authorization: `Bearer ${opts.bearerToken}`,
+ 'content-type': 'application/json',
+ };
+
+ const size = blob.size;
+ const contentType = blob.type || 'model/gltf-binary';
+ const checksum = await _sha256Hex(blob);
+
+ const presignRes = await fetch(`${origin}/api/avatars/presign`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ size_bytes: size,
+ content_type: contentType,
+ checksum_sha256: checksum,
+ }),
+ });
+ if (!presignRes.ok) throw new Error(`presign failed: ${presignRes.status}`);
+ const presign = await presignRes.json();
+
+ const put = await fetch(presign.upload_url, {
+ method: 'PUT',
+ headers: { 'content-type': contentType },
+ body: blob,
+ });
+ if (!put.ok) throw new Error(`R2 upload failed: ${put.status}`);
+
+ const createRes = await fetch(`${origin}/api/avatars`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ storage_key: presign.storage_key,
+ size_bytes: size,
+ content_type: contentType,
+ checksum_sha256: checksum,
+ name: opts.name || `Avatar ${checksum.slice(0, 6)}`,
+ description: opts.description,
+ visibility: opts.visibility || 'public',
+ tags: opts.tags || [],
+ source: opts.source || 'sdk',
+ source_meta: { via: '@three-ws/avatar' },
+ }),
+ });
+ if (!createRes.ok) throw new Error(`avatar create failed: ${createRes.status}`);
+ const { avatar } = await createRes.json();
+
+ return {
+ id: avatar.id,
+ url: avatar.url || avatar.model_url,
+ slug: avatar.slug,
+ };
+}
+
+async function _sha256Hex(blob) {
+ const buf = await blob.arrayBuffer();
+ const hash = await crypto.subtle.digest('SHA-256', buf);
+ return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
+}
diff --git a/avatar-sdk/types/creator.d.ts b/avatar-sdk/types/creator.d.ts
new file mode 100644
index 000000000..f7c023a1e
--- /dev/null
+++ b/avatar-sdk/types/creator.d.ts
@@ -0,0 +1,34 @@
+export interface AvatarCreatorOptions {
+ /** DOM node to mount the modal in. Defaults to document.body. */
+ container?: HTMLElement;
+ /** Origin of the Character Studio iframe. Defaults to https://studio.three.ws. */
+ studioUrl?: string;
+ /** Avaturn session URL for edit mode (created via /api/avatars/:id/session). */
+ avaturnSessionUrl?: string;
+ /** Called with the GLB Blob when the user exports. */
+ onExport?: (blob: Blob) => void | Promise<void>;
+ /** Called when the user closes the modal without exporting. */
+ onClose?: () => void;
+}
+
+export class AvatarCreator {
+ constructor(opts?: AvatarCreatorOptions);
+ open(): Promise<void>;
+ close(): void;
+ dispose(): void;
+}
+
+export interface SaveBlobOptions {
+ bearerToken: string;
+ apiOrigin?: string;
+ name?: string;
+ description?: string;
+ tags?: string[];
+ visibility?: 'public' | 'unlisted' | 'private';
+ source?: string;
+}
+
+export function saveBlob(
+ blob: Blob,
+ opts: SaveBlobOptions,
+): Promise<{ id: string; url: string; slug: string }>;
diff --git a/avatar-sdk/types/element.d.ts b/avatar-sdk/types/element.d.ts
new file mode 100644
index 000000000..ea465c2a3
--- /dev/null
+++ b/avatar-sdk/types/element.d.ts
@@ -0,0 +1 @@
+export * from './index';
diff --git a/avatar-sdk/types/index.d.ts b/avatar-sdk/types/index.d.ts
new file mode 100644
index 000000000..10701e6db
--- /dev/null
+++ b/avatar-sdk/types/index.d.ts
@@ -0,0 +1,44 @@
+// Type declarations for @three-ws/avatar. The runtime is implemented in
+// JavaScript and ships as a self-contained ES module that side-effectfully
+// registers the <agent-3d> custom element on import.
+
+export {};
+
+declare global {
+ interface HTMLElementTagNameMap {
+ 'agent-3d': Agent3DElement;
+ 'agent-stage': AgentStageElement;
+ }
+}
+
+/**
+ * The `<agent-3d>` web component renders a 3D avatar with a built-in chat /
+ * voice loop, emotion morphs, and lipsync. Most apps will use it declaratively
+ * in HTML; instances can also be created via `document.createElement`.
+ */
+export class Agent3DElement extends HTMLElement {
+ /** Avatar UUID (server-resolved). Setting this loads the GLB + animations. */
+ avatarId?: string;
+ /** Direct GLB URL. Use this OR `avatarId`, not both. */
+ src?: string;
+ /** Optional iOS Quick Look USDZ URL for AR. */
+ iosSrc?: string;
+ /** Hide the dev/debug GUI. */
+ kiosk?: boolean;
+
+ /** Trigger a one-shot gesture animation by name (idle, wave, nod, …). */
+ playGesture(name: string, opts?: { loop?: boolean }): void;
+ /** Drive a single morph target by name. */
+ setMorph(name: string, weight: number): void;
+}
+
+export class AgentStageElement extends HTMLElement {}
+
+export class Viewer {}
+export class Runtime {}
+export class SceneController {}
+export class Memory {}
+export class Skill {}
+export class SkillRegistry {}
+
+export function defineElement(tag?: string): void;
diff --git a/create.html b/create.html
index 2663f6708..5acf7e250 100644
--- a/create.html
+++ b/create.html
@@ -766,7 +766,73 @@
</span>
</div>
- <!-- Card 2: Upload GLB -->
+ <!-- Card 2: Selfie via Avaturn (replaces the retired Ready Player Me flow) -->
+ <div
+ class="create-card"
+ id="card-selfie"
+ role="button"
+ tabindex="0"
+ aria-label="Create an avatar from a selfie"
+ >
+ <div class="card-preview">
+ <model-viewer
+ src="/avatars/default.glb"
+ alt="Selfie-to-avatar preview"
+ auto-rotate
+ auto-rotate-delay="0"
+ rotation-per-second="22deg"
+ interaction-prompt="none"
+ disable-zoom
+ disable-pan
+ disable-tap
+ shadow-intensity="0.4"
+ shadow-softness="0.8"
+ exposure="0.95"
+ environment-image="neutral"
+ camera-orbit="-15deg 80deg auto"
+ loading="lazy"
+ ></model-viewer>
+ </div>
+ <div class="card-icon-row">
+ <div class="card-icon" aria-hidden="true">
+ <svg
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.7"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ >
+ <rect x="3" y="5" width="18" height="14" rx="2" />
+ <circle cx="12" cy="11" r="3" />
+ <path d="M7 19c0-2 2.5-3 5-3s5 1 5 3" />
+ </svg>
+ </div>
+ <h2 class="card-title">Selfie to avatar</h2>
+ </div>
+ <p class="card-subtitle">
+ Open Avaturn — snap a selfie or pick a style, get a rigged avatar.
+ </p>
+ <span class="card-cta">
+ Open creator
+ <svg
+ width="13"
+ height="13"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2.2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <line x1="5" y1="12" x2="19" y2="12" />
+ <polyline points="12 5 19 12 12 19" />
+ </svg>
+ </span>
+ </div>
+
+ <!-- Card 3: Upload GLB -->
<div
class="create-card"
id="card-upload-glb"
diff --git a/docs/configuration.md b/docs/configuration.md
index bcf6462ef..14932a765 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -191,14 +191,14 @@ Both should be the same value. Get from [dashboard.privy.io](https://dashboard.p
### Avatar Pipeline
-#### `VITE_RPM_SUBDOMAIN`
-**Optional.** Ready Player Me subdomain for the avatar creator iframe. Defaults to `demo` (public demo builder).
+#### `VITE_CHARACTER_STUDIO_URL`
+**Optional.** Origin where the Character Studio in-browser avatar builder is hosted. Defaults to `http://localhost:5173` in dev and `https://studio.three.ws` in production.
```
-VITE_RPM_SUBDOMAIN=your-app
+VITE_CHARACTER_STUDIO_URL=https://studio.three.ws
```
-Register a subdomain at [studio.readyplayer.me](https://studio.readyplayer.me). Setting this to `your-app` yields `https://your-app.readyplayer.me`.
+Character Studio is an open-source 3D avatar editor (full body customisation — hair, clothing, accessories, skin tone, proportions). It runs as a separate Vite/React app under `character-studio/` in this monorepo and posts the exported GLB back to the parent via `postMessage`. Ready Player Me previously fulfilled this role; after its 2026 acquisition, Character Studio is the recommended replacement and is fully drop-in compatible — same humanoid skeleton naming, ARKit `viseme_*` blendshapes, and Mixamo animation support.
#### `AVATURN_API_KEY`
**Optional.** API key for the Avaturn photo-to-avatar pipeline. Used server-side by `/api/onboarding/avaturn-session` to exchange selfie photos for a session URL.
diff --git a/docs/deployment.md b/docs/deployment.md
index 5eb044560..21866e188 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -104,10 +104,13 @@ Without Redis, rate limits run in-memory per serverless instance. This is fine f
### Avatar creation
```env
-# Ready Player Me — subdomain for the avatar creator iframe
-# Register at https://studio.readyplayer.me; e.g. "your-app" → https://your-app.readyplayer.me
-# Falls back to "demo" if unset.
-VITE_RPM_SUBDOMAIN=demo
+# Character Studio — origin where the in-browser avatar builder iframe is hosted.
+# Defaults to http://localhost:5173 in dev. Production deployments should host the
+# character-studio/ workspace (it is a separate Vite/React app) and point this env
+# var at its origin. Character Studio replaces the Ready Player Me iframe that was
+# previously used here — same export contract, same humanoid rig, but open-source
+# and self-hostable.
+VITE_CHARACTER_STUDIO_URL=https://studio.three.ws
# Avaturn — photo-to-avatar pipeline
# Get key at https://avaturn.me/developer
@@ -534,7 +537,7 @@ After deploying, run through these checks to verify the instance is healthy:
|---|---|
| Viewer | Load the app and drag-drop a GLB file |
| Wallet sign-in | Connect MetaMask — SIWE challenge + verify |
-| Avatar creation | Navigate to `/create` — Ready Player Me iframe loads |
+| Avatar creation | Navigate to `/create` — Character Studio (or Avaturn) iframe loads |
| Agent page | Visit `/agent/:id` — 3D viewer with chat overlay |
| Embed | Check `/agent/:id/embed` loads without auth, can be iframed |
| Dashboard | Navigate to `/dashboard` — shows your agents |
diff --git a/docs/quick-start.md b/docs/quick-start.md
index 492cff46d..7993cd965 100644
--- a/docs/quick-start.md
+++ b/docs/quick-start.md
@@ -203,7 +203,7 @@ Copy `.env.example` to `.env` and fill in:
| `ANTHROPIC_API_KEY` | Required for AI chat | LLM backend. Without it, the agent falls back to pattern matching. |
| `VITE_PRIVY_APP_ID` | Optional | Wallet auth via [Privy](https://privy.io). Needed for on-chain identity. |
| `UPSTASH_REDIS_REST_URL` / `UPSTASH_REDIS_REST_TOKEN` | Optional | Distributed rate limiting. Falls back to in-memory without it. |
-| `VITE_RPM_SUBDOMAIN` | Optional | Your [Ready Player Me](https://studio.readyplayer.me) subdomain for the avatar creator. Defaults to `demo`. |
+| `VITE_CHARACTER_STUDIO_URL` | Optional | Origin where the [Character Studio](https://github.com/m3-org/CharacterStudio) avatar builder iframe is hosted. Defaults to `http://localhost:5173` in dev. |
| `AVATURN_API_KEY` | Optional | Photo-to-avatar pipeline via [Avaturn](https://avaturn.me). |
| `PINATA_JWT` | Optional | IPFS pinning for on-chain agent registration. |
diff --git a/migrations/20260515000000_avatars_usdz_halfbody.sql b/migrations/20260515000000_avatars_usdz_halfbody.sql
new file mode 100644
index 000000000..8abc985b1
--- /dev/null
+++ b/migrations/20260515000000_avatars_usdz_halfbody.sql
@@ -0,0 +1,18 @@
+-- Add USDZ companion and half-body variant columns to avatars table.
+--
+-- usdz_key: R2 storage key for the iOS Quick Look USDZ counterpart of the
+-- avatar GLB. Generated client-side at upload time via Three.js
+-- USDZExporter. Lets iOS Safari open the avatar in AR without a USDZ URL
+-- being supplied externally.
+--
+-- halfbody_key: R2 storage key for the optional half-body (waist-up) GLB
+-- variant used in VR / first-person contexts. Generated by stripping the
+-- lower-body bone hierarchy and mesh from the source avatar.
+
+ALTER TABLE avatars
+ ADD COLUMN IF NOT EXISTS usdz_key text,
+ ADD COLUMN IF NOT EXISTS halfbody_key text;
+
+CREATE INDEX IF NOT EXISTS idx_avatars_usdz_key
+ ON avatars (usdz_key)
+ WHERE usdz_key IS NOT NULL;
diff --git a/package.json b/package.json
index 0eb35af2d..3c304f78b 100644
--- a/package.json
+++ b/package.json
@@ -24,6 +24,7 @@
],
"workspaces": [
"agent-payments-sdk",
+ "avatar-sdk",
"character-studio",
"multiplayer"
],
diff --git a/public/accessories/earrings-hoops.glb b/public/accessories/earrings-hoops.glb
new file mode 100644
index 000000000..a0fc1e800
Binary files /dev/null and b/public/accessories/earrings-hoops.glb differ
diff --git a/public/accessories/earrings-studs.glb b/public/accessories/earrings-studs.glb
new file mode 100644
index 000000000..aa91c2938
Binary files /dev/null and b/public/accessories/earrings-studs.glb differ
diff --git a/public/accessories/glasses-round.glb b/public/accessories/glasses-round.glb
new file mode 100644
index 000000000..0c0fc12f0
Binary files /dev/null and b/public/accessories/glasses-round.glb differ
diff --git a/public/accessories/glasses-shades.glb b/public/accessories/glasses-shades.glb
new file mode 100644
index 000000000..722f873ed
Binary files /dev/null and b/public/accessories/glasses-shades.glb differ
diff --git a/public/accessories/hat-baseball.glb b/public/accessories/hat-baseball.glb
new file mode 100644
index 000000000..3ef5a265c
Binary files /dev/null and b/public/accessories/hat-baseball.glb differ
diff --git a/public/accessories/hat-beanie.glb b/public/accessories/hat-beanie.glb
new file mode 100644
index 000000000..34a5820d1
Binary files /dev/null and b/public/accessories/hat-beanie.glb differ
diff --git a/public/accessories/hat-cowboy.glb b/public/accessories/hat-cowboy.glb
new file mode 100644
index 000000000..166eb3f44
Binary files /dev/null and b/public/accessories/hat-cowboy.glb differ
diff --git a/public/coin-dashboard.js b/public/coin-dashboard.js
new file mode 100644
index 000000000..64f064934
--- /dev/null
+++ b/public/coin-dashboard.js
@@ -0,0 +1,343 @@
+// Coin dashboard — vanilla module, no framework.
+//
+// Lifecycle:
+// 1. Parse mint from /coin/<mint>/ URL or query, fall back to "first active
+// coin" from /api/coin/state.
+// 2. Fetch state every 10s; render pots, KPIs, countdown.
+// 3. Tabs (winners | holders | claims | reflections) lazy-fetch their
+// data on first open and refresh on the same 10s tick.
+// 4. Wallet input (persisted to localStorage) fetches /api/coin/holder and
+// renders per-wallet stats + recent payouts.
+
+const POLL_MS = 10_000;
+const LS_KEY = 'coin-dashboard-wallet';
+
+const $ = (sel) => document.querySelector(sel);
+
+const state = {
+ mint: null,
+ intervalId: null,
+ activeTab: 'winners',
+ tabData: { winners: null, holders: null, claims: null, reflections: null },
+ wallet: localStorage.getItem(LS_KEY) || '',
+};
+
+function pickMintFromUrl() {
+ const m = window.location.pathname.match(/^\/coin\/([1-9A-HJ-NP-Za-km-z]{32,44})\/?$/);
+ if (m) return m[1];
+ const q = new URLSearchParams(window.location.search);
+ return q.get('mint');
+}
+
+function lamportsToSol(lamportsStr) {
+ if (lamportsStr == null) return '0';
+ const big = BigInt(lamportsStr);
+ const whole = big / 1_000_000_000n;
+ const frac = big % 1_000_000_000n;
+ const fracStr = frac.toString().padStart(9, '0');
+ // Trim trailing zeros after 6 decimals but keep at least 3 decimals.
+ const trimmed = fracStr.slice(0, 6).replace(/0+$/, '') || '000';
+ return `${whole.toLocaleString()}.${trimmed}`;
+}
+
+function shortWallet(w) {
+ if (!w) return '—';
+ return `${w.slice(0, 4)}…${w.slice(-4)}`;
+}
+
+function fmtTime(iso) {
+ if (!iso) return '—';
+ const d = new Date(iso);
+ const diff = Math.floor((Date.now() - d.getTime()) / 1000);
+ if (diff < 60) return `${diff}s ago`;
+ if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
+ if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
+ return d.toLocaleDateString();
+}
+
+function fmtCountdown(targetIso) {
+ if (!targetIso) return '—';
+ const target = new Date(targetIso).getTime();
+ const left = Math.max(0, Math.floor((target - Date.now()) / 1000));
+ if (left === 0) return 'drawing now…';
+ const m = Math.floor(left / 60);
+ const s = left % 60;
+ if (m >= 60) {
+ const h = Math.floor(m / 60);
+ return `${h}h ${m % 60}m ${s.toString().padStart(2, '0')}s`;
+ }
+ return `${m}m ${s.toString().padStart(2, '0')}s`;
+}
+
+async function fetchJson(url) {
+ const r = await fetch(url, { credentials: 'omit' });
+ if (!r.ok) {
+ const text = await r.text().catch(() => '');
+ throw new Error(`${r.status}: ${text || r.statusText}`);
+ }
+ return r.json();
+}
+
+function apiUrl(action, params = {}) {
+ const q = new URLSearchParams(params);
+ if (state.mint) q.set('mint', state.mint);
+ return `/api/coin/${action}?${q.toString()}`;
+}
+
+async function refreshState() {
+ const data = await fetchJson(apiUrl('state'));
+ state.mint = data.mint;
+ $('#coin-name').textContent = data.name || 'Coin';
+ const sym = $('#coin-symbol');
+ sym.textContent = `$${data.symbol}`;
+ sym.hidden = false;
+ const live = $('#coin-live');
+ const liveText = $('#coin-live-text');
+ live.hidden = false;
+ live.dataset.live = data.is_live ? 'true' : 'false';
+ liveText.textContent = data.is_live ? 'LIVE' : 'DRY-RUN';
+
+ $('#address-row').hidden = false;
+ $('#coin-mint').textContent = data.mint;
+
+ $('#pot-lottery').textContent = lamportsToSol(data.pots.lottery_lamports);
+ $('#pot-reflection').textContent = lamportsToSol(data.pots.reflection_lamports);
+ $('#next-draw').dataset.target = data.cadence.next_draw_at || '';
+ $('#next-draw').textContent = fmtCountdown(data.cadence.next_draw_at);
+
+ $('#kpi-claimed').textContent = `${lamportsToSol(data.pots.total_claimed_lamports)} SOL`;
+ $('#kpi-holders').textContent = `${data.holders.eligible.toLocaleString()} / ${data.holders.total.toLocaleString()}`;
+ $('#kpi-reflection-paid').textContent = `${lamportsToSol(data.paid_total.reflection_lamports)} SOL`;
+ $('#kpi-lottery-paid').textContent = `${lamportsToSol(data.paid_total.lottery_lamports)} SOL`;
+ $('#kpi-allocation').textContent = `${(data.allocation_bps.lottery / 100).toFixed(0)}/${(data.allocation_bps.reflection / 100).toFixed(0)}/${(data.allocation_bps.ops / 100).toFixed(0)}`;
+
+ return data;
+}
+
+async function refreshActiveTab() {
+ const tab = state.activeTab;
+ const container = $('#tab-content');
+ try {
+ if (tab === 'winners') {
+ const data = await fetchJson(apiUrl('winners', { limit: 25 }));
+ state.tabData.winners = data;
+ renderWinners(container, data);
+ } else if (tab === 'holders') {
+ const data = await fetchJson(apiUrl('holders', { limit: 50 }));
+ state.tabData.holders = data;
+ renderHolders(container, data);
+ } else if (tab === 'claims') {
+ const data = await fetchJson(apiUrl('history', { limit: 25 }));
+ state.tabData.claims = data;
+ renderClaims(container, data);
+ } else if (tab === 'reflections') {
+ const data = state.tabData.claims || (await fetchJson(apiUrl('history', { limit: 25 })));
+ state.tabData.reflections = data;
+ renderReflections(container, data);
+ }
+ } catch (err) {
+ container.innerHTML = `<div class="error">Failed to load: ${err.message}</div>`;
+ }
+}
+
+function renderWinners(container, data) {
+ if (!data?.winners?.length) {
+ container.innerHTML = `<div class="empty">No draws yet — the first one will appear here once the pot has anything in it.</div>`;
+ return;
+ }
+ const me = state.wallet;
+ const rows = data.winners
+ .map((w) => {
+ const isMe = me && w.wallet === me ? 'you' : '';
+ const explorer = w.tx_signature
+ ? `<a href="https://solscan.io/tx/${w.tx_signature}" target="_blank" rel="noopener">tx</a>`
+ : w.status === 'resolved'
+ ? '<span style="color:var(--muted)">pending payout</span>'
+ : '<span style="color:var(--muted)">—</span>';
+ return `<tr class="${isMe}"><td>${fmtTime(w.created_at)}</td>
+ <td class="wallet" title="${w.wallet || ''}">${shortWallet(w.wallet)}</td>
+ <td>${lamportsToSol(w.amount_lamports)} SOL</td>
+ <td>${explorer}</td>
+ <td><span title="Drand round ${w.drand_round}; randomness ${w.drand_randomness?.slice(0, 16) || '—'}…">round ${w.drand_round}</span></td></tr>`;
+ })
+ .join('');
+ container.innerHTML = `<table><thead><tr>
+ <th>When</th><th>Winner</th><th>Amount</th><th>Tx</th><th>Drand</th>
+ </tr></thead><tbody>${rows}</tbody></table>`;
+}
+
+function renderHolders(container, data) {
+ if (!data?.holders?.length) {
+ container.innerHTML = `<div class="empty">No holders yet.</div>`;
+ return;
+ }
+ const me = state.wallet;
+ const rows = data.holders
+ .map((h) => {
+ const isMe = me && h.wallet === me ? 'you' : '';
+ return `<tr class="${isMe}"><td>#${h.rank}</td>
+ <td class="wallet" title="${h.wallet}">${shortWallet(h.wallet)}</td>
+ <td>${BigInt(h.balance).toLocaleString()}</td>
+ <td>${lamportsToSol(h.total_reflection_paid_lamports)} SOL</td>
+ <td>${lamportsToSol(h.total_lottery_won_lamports)} SOL</td></tr>`;
+ })
+ .join('');
+ container.innerHTML = `<table><thead><tr>
+ <th>Rank</th><th>Wallet</th><th>Balance</th><th>Reflection paid</th><th>Lottery won</th>
+ </tr></thead><tbody>${rows}</tbody></table>`;
+}
+
+function renderClaims(container, data) {
+ if (!data?.fee_claims?.length) {
+ container.innerHTML = `<div class="empty">No creator-fee claims yet. The next cycle will sweep any pending fees.</div>`;
+ return;
+ }
+ const rows = data.fee_claims
+ .map((c) => {
+ const tx = c.tx_signature
+ ? `<a href="https://solscan.io/tx/${c.tx_signature}" target="_blank" rel="noopener">tx</a>`
+ : '<span style="color:var(--muted)">empty</span>';
+ return `<tr><td>${fmtTime(c.created_at)}</td>
+ <td>${c.claimed_lamports ? lamportsToSol(c.claimed_lamports) + ' SOL' : '0 SOL'}</td>
+ <td>${c.lottery_lamports ? lamportsToSol(c.lottery_lamports) + ' SOL' : '—'}</td>
+ <td>${c.reflection_lamports ? lamportsToSol(c.reflection_lamports) + ' SOL' : '—'}</td>
+ <td>${tx}</td></tr>`;
+ })
+ .join('');
+ container.innerHTML = `<table><thead><tr>
+ <th>When</th><th>Claimed</th><th>→ Lottery</th><th>→ Reflection</th><th>Tx</th>
+ </tr></thead><tbody>${rows}</tbody></table>`;
+}
+
+function renderReflections(container, data) {
+ if (!data?.reflection_batches?.length) {
+ container.innerHTML = `<div class="empty">No reflection batches yet. Each cycle pays accrued SOL to every eligible holder pro-rata.</div>`;
+ return;
+ }
+ const rows = data.reflection_batches
+ .map((b) => {
+ return `<tr><td>${fmtTime(b.created_at)}</td>
+ <td>${b.batch_id?.split('-').slice(-1)[0] || '—'}</td>
+ <td>${b.queued || 0}</td>
+ <td>${lamportsToSol(b.allocated_lamports || '0')} SOL</td></tr>`;
+ })
+ .join('');
+ container.innerHTML = `<table><thead><tr>
+ <th>When</th><th>Batch</th><th>Holders paid</th><th>Total distributed</th>
+ </tr></thead><tbody>${rows}</tbody></table>`;
+}
+
+async function refreshWallet() {
+ const wallet = state.wallet;
+ if (!wallet) {
+ $('#wallet-stats').hidden = true;
+ $('#wallet-payouts').hidden = true;
+ return;
+ }
+ try {
+ const data = await fetchJson(apiUrl('holder', { wallet }));
+ $('#wallet-balance').innerHTML = `${BigInt(data.balance || '0').toLocaleString()}<span class="unit">tokens</span>`;
+ $('#wallet-reflection-paid').innerHTML = `${lamportsToSol(data.total_reflection_paid_lamports || '0')}<span class="unit">SOL</span>`;
+ $('#wallet-accrued').innerHTML = `${lamportsToSol(data.accrued_reflection_lamports || '0')}<span class="unit">SOL</span>`;
+ $('#wallet-lottery').innerHTML = `${lamportsToSol(data.total_lottery_won_lamports || '0')}<span class="unit">SOL</span>`;
+ $('#wallet-stats').hidden = false;
+
+ // Recent payouts inline list.
+ const list = $('#wallet-payouts');
+ if (data.recent_payouts?.length) {
+ const rows = data.recent_payouts
+ .slice(0, 8)
+ .map((p) => {
+ const sym = p.kind === 'lottery' ? '🎟' : '⟳';
+ const tx = p.tx_signature
+ ? `<a href="https://solscan.io/tx/${p.tx_signature}" target="_blank" rel="noopener" style="color:var(--accent);text-decoration:none">${p.status}</a>`
+ : p.status;
+ return `<tr><td style="width:24px">${sym}</td><td>${p.kind}</td><td>${lamportsToSol(p.amount_lamports)} SOL</td><td style="text-align:right;color:var(--muted)">${fmtTime(p.created_at)} · ${tx}</td></tr>`;
+ })
+ .join('');
+ list.innerHTML = `<table>${rows}</table>`;
+ list.hidden = false;
+ } else {
+ list.hidden = true;
+ }
+ } catch (err) {
+ console.error('[coin-dashboard] wallet fetch failed', err);
+ }
+}
+
+function bindTabs() {
+ for (const btn of document.querySelectorAll('.tabs button')) {
+ btn.addEventListener('click', () => {
+ for (const b of document.querySelectorAll('.tabs button')) {
+ b.setAttribute('aria-selected', String(b === btn));
+ }
+ state.activeTab = btn.dataset.tab;
+ refreshActiveTab();
+ });
+ }
+}
+
+function bindWallet() {
+ const input = $('#wallet-input');
+ input.value = state.wallet || '';
+ $('#wallet-check').addEventListener('click', () => {
+ const v = input.value.trim();
+ state.wallet = v;
+ if (v) localStorage.setItem(LS_KEY, v);
+ else localStorage.removeItem(LS_KEY);
+ refreshWallet();
+ refreshActiveTab(); // re-highlight "you" rows
+ });
+ $('#wallet-clear').addEventListener('click', () => {
+ state.wallet = '';
+ input.value = '';
+ localStorage.removeItem(LS_KEY);
+ refreshWallet();
+ refreshActiveTab();
+ });
+ input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') $('#wallet-check').click();
+ });
+}
+
+function bindCopy() {
+ $('#copy-mint').addEventListener('click', async () => {
+ try {
+ await navigator.clipboard.writeText(state.mint || '');
+ $('#copy-mint').textContent = 'copied';
+ setTimeout(() => ($('#copy-mint').textContent = 'copy'), 1500);
+ } catch {
+ /* ignore */
+ }
+ });
+}
+
+function tickCountdown() {
+ const el = $('#next-draw');
+ if (!el) return;
+ el.textContent = fmtCountdown(el.dataset.target || '');
+}
+
+async function tick() {
+ try {
+ await refreshState();
+ await refreshActiveTab();
+ await refreshWallet();
+ } catch (err) {
+ console.error('[coin-dashboard] tick failed', err);
+ if (!state.mint) {
+ $('#coin-name').textContent = 'No active coin';
+ $('#header').innerHTML += `<div style="color:var(--err);font-size:13px;margin-left:10px">${err.message}</div>`;
+ }
+ }
+}
+
+(async function main() {
+ state.mint = pickMintFromUrl();
+ bindTabs();
+ bindWallet();
+ bindCopy();
+ await tick();
+ setInterval(tick, POLL_MS);
+ setInterval(tickCountdown, 1000);
+})();
diff --git a/public/coin/index.html b/public/coin/index.html
new file mode 100644
index 000000000..5c9e1bd5d
--- /dev/null
+++ b/public/coin/index.html
@@ -0,0 +1,216 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Coin · three.ws</title>
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --accent: #6a5cff;
+ --accent-2: #ff6ad6;
+ --accent-3: #ffba2e;
+ --border: #1f1f29;
+ --bg: #0a0a0f;
+ --panel: #14141c;
+ --panel-hi: #181822;
+ --muted: #888;
+ --header-h: 48px;
+ --ok: #4ade80;
+ --err: #f87171;
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; background: var(--bg); color: #eee;
+ font: 14px/1.55 -apple-system, system-ui, Segoe UI, Roboto, sans-serif; }
+ body { padding-top: var(--header-h); min-height: 100vh; display: flex; flex-direction: column; }
+ main { flex: 1; max-width: 1180px; margin: 0 auto; padding: 24px 18px 64px; width: 100%; }
+
+ .hero { display: grid; grid-template-columns: 1fr; gap: 16px; margin-bottom: 24px; }
+ @media (min-width: 900px) { .hero { grid-template-columns: 2fr 1fr; align-items: stretch; } }
+
+ .title-row { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; }
+ .title-row h1 { font-size: 28px; margin: 0; font-weight: 700; letter-spacing: -0.01em; }
+ .title-row .symbol { font-size: 14px; color: var(--muted); font-weight: 500;
+ padding: 3px 9px; border: 1px solid var(--border); border-radius: 999px; background: var(--panel); }
+ .title-row .live-pill { font-size: 11px; padding: 3px 9px; border-radius: 999px;
+ border: 1px solid #1a3624; background: rgba(74,222,128,0.08); color: var(--ok);
+ display: inline-flex; align-items: center; gap: 6px; }
+ .title-row .live-pill[data-live="false"] { border-color: #4a1f23; background: rgba(248,113,113,0.06); color: var(--err); }
+ .live-pill .pulse { width: 7px; height: 7px; border-radius: 50%; background: currentColor;
+ box-shadow: 0 0 6px currentColor; animation: pulse 1.6s ease-in-out infinite; }
+ @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
+
+ .address-row { display: flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12px; font-family: ui-monospace, SFMono-Regular, monospace; margin-bottom: 18px; }
+ .address-row .copy { cursor: pointer; padding: 2px 6px; border: 1px solid var(--border); border-radius: 4px; background: var(--panel); color: var(--muted); }
+ .address-row .copy:hover { color: #eee; border-color: #2a2a36; }
+
+ .pots-card { background: linear-gradient(180deg, var(--panel-hi), var(--panel));
+ border: 1px solid var(--border); border-radius: 14px; padding: 20px 22px; }
+ .pots-row { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-bottom: 14px; }
+ .pot { padding: 14px 16px; border-radius: 10px; border: 1px solid var(--border); background: #0e0e16; }
+ .pot .label { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em; font-weight: 600; }
+ .pot .value { font-size: 26px; font-weight: 700; margin-top: 6px; font-variant-numeric: tabular-nums; }
+ .pot .value .sol { font-size: 14px; color: var(--muted); font-weight: 500; margin-left: 4px; }
+ .pot.lottery { background: linear-gradient(180deg, rgba(255,186,46,0.08), rgba(255,186,46,0.02)); border-color: rgba(255,186,46,0.25); }
+ .pot.lottery .value { color: var(--accent-3); }
+ .pot.reflection { background: linear-gradient(180deg, rgba(106,92,255,0.08), rgba(106,92,255,0.02)); border-color: rgba(106,92,255,0.25); }
+ .pot.reflection .value { color: var(--accent); }
+
+ .next-draw { display: flex; align-items: center; justify-content: space-between; padding: 10px 14px;
+ background: #0e0e16; border: 1px solid var(--border); border-radius: 10px; font-size: 13px; }
+ .next-draw .label { color: var(--muted); }
+ .next-draw .countdown { font-variant-numeric: tabular-nums; font-weight: 600; }
+
+ .kpi-card { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 20px 22px;
+ display: flex; flex-direction: column; gap: 14px; }
+ .kpi { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; }
+ .kpi .label { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.04em; }
+ .kpi .value { font-size: 15px; font-weight: 600; font-variant-numeric: tabular-nums; }
+
+ section.panel { background: var(--panel); border: 1px solid var(--border); border-radius: 12px;
+ padding: 18px 20px; margin-bottom: 18px; }
+ section.panel h2 { font-size: 13px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted);
+ margin: 0 0 12px; font-weight: 600; }
+
+ .wallet-controls { display: flex; gap: 8px; flex-wrap: wrap; }
+ .wallet-controls input[type="text"] { flex: 1; min-width: 220px; background: #0e0e16; color: #eee;
+ border: 1px solid var(--border); border-radius: 6px; padding: 8px 11px; font-size: 13px; font-family: ui-monospace, SFMono-Regular, monospace; }
+ .wallet-controls input:focus { outline: none; border-color: var(--accent); }
+ .wallet-controls button { background: var(--accent); border: 0; color: #fff;
+ border-radius: 6px; padding: 8px 16px; font-size: 13px; cursor: pointer; font-weight: 600; }
+ .wallet-controls button:hover { filter: brightness(1.1); }
+ .wallet-controls button.ghost { background: transparent; border: 1px solid var(--border); color: var(--muted); }
+ .wallet-controls button.ghost:hover { color: #eee; border-color: #2a2a36; }
+
+ .wallet-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ gap: 12px; margin-top: 14px; }
+ .wallet-stats .stat { padding: 12px; border: 1px solid var(--border); border-radius: 8px; background: #0e0e16; }
+ .wallet-stats .stat .label { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }
+ .wallet-stats .stat .value { font-size: 18px; font-weight: 600; margin-top: 6px; font-variant-numeric: tabular-nums; }
+ .wallet-stats .stat .value .unit { font-size: 11px; color: var(--muted); margin-left: 4px; font-weight: 500; }
+
+ table { width: 100%; border-collapse: collapse; font-size: 13px; }
+ table th { text-align: left; color: var(--muted); font-size: 11px; text-transform: uppercase;
+ letter-spacing: 0.05em; padding: 8px 12px; border-bottom: 1px solid var(--border); font-weight: 600; }
+ table td { padding: 10px 12px; border-bottom: 1px solid #15151e; font-variant-numeric: tabular-nums; }
+ table td.wallet { font-family: ui-monospace, SFMono-Regular, monospace; font-size: 12px; }
+ table tr:hover td { background: rgba(106,92,255,0.04); }
+ table tr.you td { background: rgba(106,92,255,0.08); }
+ table tr.you td:first-child::before { content: '★ '; color: var(--accent-3); }
+ table a { color: var(--accent); text-decoration: none; }
+ table a:hover { text-decoration: underline; }
+
+ .empty { padding: 28px 16px; text-align: center; color: var(--muted); font-size: 13px; }
+ .error { color: var(--err); padding: 28px 16px; text-align: center; font-size: 13px; }
+
+ .tabs { display: flex; gap: 2px; padding: 0; margin: 0 0 14px; border-bottom: 1px solid var(--border); }
+ .tabs button { background: transparent; border: 0; color: var(--muted); cursor: pointer;
+ padding: 10px 14px; font-size: 13px; font-weight: 500; border-bottom: 2px solid transparent; white-space: nowrap; }
+ .tabs button:hover { color: #eee; }
+ .tabs button[aria-selected="true"] { color: #eee; border-bottom-color: var(--accent); }
+
+ .transparency { font-size: 12px; color: var(--muted); padding: 12px; background: #0e0e16;
+ border: 1px dashed var(--border); border-radius: 8px; margin-top: 14px; line-height: 1.55; }
+ .transparency code { background: #1a1a24; padding: 1px 5px; border-radius: 4px; color: #cbd5e1; font-size: 11px; }
+ </style>
+ <script defer src="/nav.js"></script>
+</head>
+<body>
+ <header id="top-nav"></header>
+ <main>
+ <div id="header" class="title-row">
+ <h1 id="coin-name">Loading…</h1>
+ <span id="coin-symbol" class="symbol" hidden></span>
+ <span id="coin-live" class="live-pill" hidden><span class="pulse"></span><span id="coin-live-text">LIVE</span></span>
+ </div>
+ <div id="address-row" class="address-row" hidden>
+ <span id="coin-mint">—</span>
+ <button class="copy" id="copy-mint" title="Copy mint">copy</button>
+ </div>
+
+ <div class="hero">
+ <div class="pots-card">
+ <div class="pots-row">
+ <div class="pot lottery">
+ <div class="label">Lottery pot</div>
+ <div class="value"><span id="pot-lottery">0.000000000</span><span class="sol">SOL</span></div>
+ </div>
+ <div class="pot reflection">
+ <div class="label">Reflection pot</div>
+ <div class="value"><span id="pot-reflection">0.000000000</span><span class="sol">SOL</span></div>
+ </div>
+ </div>
+ <div class="next-draw">
+ <span class="label">Next draw</span>
+ <span class="countdown" id="next-draw">—</span>
+ </div>
+ </div>
+
+ <div class="kpi-card">
+ <div class="kpi">
+ <span class="label">Total claimed</span>
+ <span class="value" id="kpi-claimed">— SOL</span>
+ </div>
+ <div class="kpi">
+ <span class="label">Eligible holders</span>
+ <span class="value" id="kpi-holders">—</span>
+ </div>
+ <div class="kpi">
+ <span class="label">Total reflection paid</span>
+ <span class="value" id="kpi-reflection-paid">— SOL</span>
+ </div>
+ <div class="kpi">
+ <span class="label">Total lottery paid</span>
+ <span class="value" id="kpi-lottery-paid">— SOL</span>
+ </div>
+ <div class="kpi">
+ <span class="label">Allocation</span>
+ <span class="value" id="kpi-allocation">—</span>
+ </div>
+ </div>
+ </div>
+
+ <section class="panel">
+ <h2>Your wallet</h2>
+ <div class="wallet-controls">
+ <input id="wallet-input" type="text" placeholder="Paste your Solana wallet address (or use a Phantom-signed session)" autocomplete="off" spellcheck="false" />
+ <button id="wallet-check">Show my stats</button>
+ <button id="wallet-clear" class="ghost">Clear</button>
+ </div>
+ <div id="wallet-stats" class="wallet-stats" hidden>
+ <div class="stat"><div class="label">Balance</div><div class="value" id="wallet-balance">—<span class="unit">tokens</span></div></div>
+ <div class="stat"><div class="label">Reflection paid</div><div class="value" id="wallet-reflection-paid">—<span class="unit">SOL</span></div></div>
+ <div class="stat"><div class="label">Pending reflection</div><div class="value" id="wallet-accrued">—<span class="unit">SOL</span></div></div>
+ <div class="stat"><div class="label">Lottery winnings</div><div class="value" id="wallet-lottery">—<span class="unit">SOL</span></div></div>
+ </div>
+ <div id="wallet-payouts" hidden style="margin-top: 14px;"></div>
+ </section>
+
+ <section class="panel">
+ <div class="tabs" role="tablist">
+ <button data-tab="winners" aria-selected="true" role="tab">Recent winners</button>
+ <button data-tab="holders" role="tab">Top holders</button>
+ <button data-tab="claims" role="tab">Fee claims</button>
+ <button data-tab="reflections" role="tab">Reflection batches</button>
+ </div>
+ <div id="tab-content"><div class="empty">Loading…</div></div>
+ <div class="transparency">
+ <strong>Verifiable randomness.</strong> Every lottery draw commits to a Drand quicknet
+ round in advance — the BLS signature for that round is published by the
+ <a href="https://drand.love" target="_blank" rel="noopener" style="color: var(--accent);">League of Entropy</a>
+ on a public 3-second cadence. We compute the winner deterministically from
+ <code>sha256(randomness ∥ weights_hash)</code> and persist the full audit trail
+ (<code>drand_round</code>, <code>drand_randomness</code>, <code>drand_signature</code>) so anyone
+ can independently re-derive the winner.
+ </div>
+ </section>
+ </main>
+ <footer id="site-footer"></footer>
+ <script type="module" src="/coin-dashboard.js"></script>
+</body>
+</html>
diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.js
index e330c9437..cfd5c1905 100644
--- a/public/dashboard/dashboard.js
+++ b/public/dashboard/dashboard.js
@@ -1670,32 +1670,18 @@ function uploadToR2(url, file, onProgress) {
}
// ── Create avatar ───────────────────────────────────────────────────────────
-// Uses Avaturn SDK (same provider as /create page) instead of the defunct
-// demo.readyplayer.me iframe.
-let _avaturnSdk = null;
-async function getAvaturnSDK() {
- if (!_avaturnSdk) {
- const mod = await import('/dashboard/avaturn-sdk.js');
- _avaturnSdk = mod.AvaturnSDK;
- }
- return _avaturnSdk;
-}
+// The dashboard "Create" entry redirects to the full creation flow at /create,
+// which exposes Avaturn (default editor), Ready Player Me (selfie → avatar),
+// and direct GLB upload.
function renderCreate(root) {
root.innerHTML = `
<div>
<h1>Create avatar</h1>
- <p class="sub">Design a 3D avatar from a selfie.</p>
- </div>
- <div class="empty" style="margin-top:24px; padding:60px 32px">
- <div style="font-size:48px; line-height:1; margin-bottom:16px">🧍</div>
- <div style="font-size:18px; font-weight:600; margin-bottom:8px; color:#eee">Coming soon</div>
- <p style="margin:0 0 20px; color:#888; max-width:380px; margin-left:auto; margin-right:auto; font-size:14px">
- Avatar creation from a selfie is under development. In the meantime you can upload an existing .glb file.
- </p>
- <a href="/dashboard/upload" class="btn">Upload a .glb instead</a>
+ <p class="sub">Opening the avatar creator…</p>
</div>
`;
+ location.replace('/create');
}
async function fetchGlbBlob(url, urlType) {
diff --git a/public/docs/configuration.md b/public/docs/configuration.md
index bcf6462ef..14932a765 100644
--- a/public/docs/configuration.md
+++ b/public/docs/configuration.md
@@ -191,14 +191,14 @@ Both should be the same value. Get from [dashboard.privy.io](https://dashboard.p
### Avatar Pipeline
-#### `VITE_RPM_SUBDOMAIN`
-**Optional.** Ready Player Me subdomain for the avatar creator iframe. Defaults to `demo` (public demo builder).
+#### `VITE_CHARACTER_STUDIO_URL`
+**Optional.** Origin where the Character Studio in-browser avatar builder is hosted. Defaults to `http://localhost:5173` in dev and `https://studio.three.ws` in production.
```
-VITE_RPM_SUBDOMAIN=your-app
+VITE_CHARACTER_STUDIO_URL=https://studio.three.ws
```
-Register a subdomain at [studio.readyplayer.me](https://studio.readyplayer.me). Setting this to `your-app` yields `https://your-app.readyplayer.me`.
+Character Studio is an open-source 3D avatar editor (full body customisation — hair, clothing, accessories, skin tone, proportions). It runs as a separate Vite/React app under `character-studio/` in this monorepo and posts the exported GLB back to the parent via `postMessage`. Ready Player Me previously fulfilled this role; after its 2026 acquisition, Character Studio is the recommended replacement and is fully drop-in compatible — same humanoid skeleton naming, ARKit `viseme_*` blendshapes, and Mixamo animation support.
#### `AVATURN_API_KEY`
**Optional.** API key for the Avaturn photo-to-avatar pipeline. Used server-side by `/api/onboarding/avaturn-session` to exchange selfie photos for a session URL.
diff --git a/public/docs/deployment.md b/public/docs/deployment.md
index 5eb044560..21866e188 100644
--- a/public/docs/deployment.md
+++ b/public/docs/deployment.md
@@ -104,10 +104,13 @@ Without Redis, rate limits run in-memory per serverless instance. This is fine f
### Avatar creation
```env
-# Ready Player Me — subdomain for the avatar creator iframe
-# Register at https://studio.readyplayer.me; e.g. "your-app" → https://your-app.readyplayer.me
-# Falls back to "demo" if unset.
-VITE_RPM_SUBDOMAIN=demo
+# Character Studio — origin where the in-browser avatar builder iframe is hosted.
+# Defaults to http://localhost:5173 in dev. Production deployments should host the
+# character-studio/ workspace (it is a separate Vite/React app) and point this env
+# var at its origin. Character Studio replaces the Ready Player Me iframe that was
+# previously used here — same export contract, same humanoid rig, but open-source
+# and self-hostable.
+VITE_CHARACTER_STUDIO_URL=https://studio.three.ws
# Avaturn — photo-to-avatar pipeline
# Get key at https://avaturn.me/developer
@@ -534,7 +537,7 @@ After deploying, run through these checks to verify the instance is healthy:
|---|---|
| Viewer | Load the app and drag-drop a GLB file |
| Wallet sign-in | Connect MetaMask — SIWE challenge + verify |
-| Avatar creation | Navigate to `/create` — Ready Player Me iframe loads |
+| Avatar creation | Navigate to `/create` — Character Studio (or Avaturn) iframe loads |
| Agent page | Visit `/agent/:id` — 3D viewer with chat overlay |
| Embed | Check `/agent/:id/embed` loads without auth, can be iframed |
| Dashboard | Navigate to `/dashboard` — shows your agents |
diff --git a/public/docs/quick-start.md b/public/docs/quick-start.md
index 492cff46d..7993cd965 100644
--- a/public/docs/quick-start.md
+++ b/public/docs/quick-start.md
@@ -203,7 +203,7 @@ Copy `.env.example` to `.env` and fill in:
| `ANTHROPIC_API_KEY` | Required for AI chat | LLM backend. Without it, the agent falls back to pattern matching. |
| `VITE_PRIVY_APP_ID` | Optional | Wallet auth via [Privy](https://privy.io). Needed for on-chain identity. |
| `UPSTASH_REDIS_REST_URL` / `UPSTASH_REDIS_REST_TOKEN` | Optional | Distributed rate limiting. Falls back to in-memory without it. |
-| `VITE_RPM_SUBDOMAIN` | Optional | Your [Ready Player Me](https://studio.readyplayer.me) subdomain for the avatar creator. Defaults to `demo`. |
+| `VITE_CHARACTER_STUDIO_URL` | Optional | Origin where the [Character Studio](https://github.com/m3-org/CharacterStudio) avatar builder iframe is hosted. Defaults to `http://localhost:5173` in dev. |
| `AVATURN_API_KEY` | Optional | Photo-to-avatar pipeline via [Avaturn](https://avaturn.me). |
| `PINATA_JWT` | Optional | IPFS pinning for on-chain agent registration. |
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 3d1fadec7..52f2c3cbd 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -31,6 +31,12 @@ URL: https://three.ws/gallery
Every public 3D avatar in the system, browsable as a grid.
+### Walk
+
+URL: https://three.ws/walk
+
+Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.
+
### Marketplace
URL: https://three.ws/marketplace
diff --git a/public/llms.txt b/public/llms.txt
index d12202458..a75a778ad 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -14,6 +14,7 @@ Entry points into the product.
- [Home](https://three.ws/): Landing page. Pitch, live agent demos, and the front door to every flow.
- [Discover](https://three.ws/discover): On-chain agent directory (ERC-8004 + Solana). Browse, search, and inspect every registered agent.
- [Avatar Gallery](https://three.ws/gallery): Every public 3D avatar in the system, browsable as a grid.
+- [Walk](https://three.ws/walk): Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.
- [Marketplace](https://three.ws/marketplace): Buy access to agents, skills, and avatars from other creators.
- [Community](https://three.ws/community): Featured creators, builds, and conversations from the three.ws community.
- [Sitemap](https://three.ws/sitemap): Human-readable index of every page on three.ws.
diff --git a/public/sitemap.xml b/public/sitemap.xml
index 229cc90ec..16f420ff7 100644
--- a/public/sitemap.xml
+++ b/public/sitemap.xml
@@ -2,227 +2,233 @@
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://three.ws/</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>https://three.ws/discover</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>daily</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/gallery</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
+ <url>
+ <loc>https://three.ws/walk</loc>
+ <lastmod>2026-05-15</lastmod>
+ <changefreq>monthly</changefreq>
+ <priority>0.7</priority>
+ </url>
<url>
<loc>https://three.ws/marketplace</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/community</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/sitemap</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.4</priority>
</url>
<url>
<loc>https://three.ws/create</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/app</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>monthly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/validation</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/studio</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/artifact</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>monthly</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>https://three.ws/widgets</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/hydrate</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/pay</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/pumpfun</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/pump-live</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/pump-dashboard</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/strategy-lab</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/vanity-wallet</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/eth-vanity</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/chat</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/agent</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/agents</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/reputation</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/login</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>yearly</changefreq>
<priority>0.4</priority>
</url>
<url>
<loc>https://three.ws/register</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>yearly</changefreq>
<priority>0.4</priority>
</url>
<url>
<loc>https://three.ws/forgot-password</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>yearly</changefreq>
<priority>0.2</priority>
</url>
<url>
<loc>https://three.ws/docs</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/docs/quick-start</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/docs/agent-system</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
</url>
<url>
<loc>https://three.ws/docs/erc8004</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
</url>
<url>
<loc>https://three.ws/docs/embedding</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
</url>
<url>
<loc>https://three.ws/docs/web-component</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
</url>
<url>
<loc>https://three.ws/docs/mcp</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
</url>
<url>
<loc>https://three.ws/docs/skills</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
</url>
<url>
<loc>https://three.ws/docs/widgets</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
</url>
<url>
<loc>https://three.ws/docs/api-reference</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
</url>
<url>
<loc>https://three.ws/docs/sdk</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
</url>
<url>
<loc>https://three.ws/tutorials</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
</url>
<url>
<loc>https://three.ws/legal/privacy</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>yearly</changefreq>
<priority>0.2</priority>
</url>
<url>
<loc>https://three.ws/legal/tos</loc>
- <lastmod>2026-05-13</lastmod>
+ <lastmod>2026-05-15</lastmod>
<changefreq>yearly</changefreq>
<priority>0.2</priority>
</url>
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 5917a0289..8e5702dd0 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -89,6 +89,13 @@
<span class="sm-desc">Every public 3D avatar in the system, browsable as a grid.</span>
</a>
</li>
+ <li>
+ <a href="/walk">
+ <span class="sm-title">Walk</span>
+ <span class="sm-path">/walk</span>
+ <span class="sm-desc">Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.</span>
+ </a>
+ </li>
<li>
<a href="/marketplace">
<span class="sm-title">Marketplace</span>
diff --git a/publish/README.md b/publish/README.md
index e17ddadfb..f1a0c6a8f 100644
--- a/publish/README.md
+++ b/publish/README.md
@@ -220,7 +220,7 @@ If you want to support the project — compute credits, grants, partnerships, or
- OAuth 2.1 server (RFC 6749 + PKCE, RFC 7591 dynamic registration, RFC 7009 revocation, RFC 7662 introspection, RFC 8414 discovery)
- Developer API keys with scope and expiry
- MCP (Model Context Protocol) over HTTP with JSON-RPC 2.0 for tool-calling from external AI systems
-- Ready Player Me, Avaturn (photo-to-avatar), and Privy (embedded wallet) integrations
+- Avaturn (photo-to-avatar), Character Studio (in-browser builder), and Privy (embedded wallet) integrations
- DCA strategy execution and on-chain subscription scheduling via cron jobs
- OpenAPI 3.1 spec generated at `/openapi.json`
@@ -1363,7 +1363,7 @@ WEB3_STORAGE_TOKEN=... # Fallback
### Optional (Frontend, prefixed `VITE_`)
```env
-VITE_RPM_SUBDOMAIN=demo # Ready Player Me subdomain
+VITE_CHARACTER_STUDIO_URL=https://studio.three.ws # Avatar builder iframe origin
VITE_PRIVY_APP_ID=...
VITE_AVATURN_EDITOR_URL=https://editor.avaturn.me/
VITE_AVATURN_DEVELOPER_ID=...
diff --git a/scripts/coin-cli.mjs b/scripts/coin-cli.mjs
new file mode 100644
index 000000000..c16fb8294
--- /dev/null
+++ b/scripts/coin-cli.mjs
@@ -0,0 +1,494 @@
+#!/usr/bin/env node
+// coin-cli — lifecycle management for the lottery + reflection coin.
+//
+// Subcommands:
+// keygen [--out <path>] generate a fresh Solana keypair (treasury / creator)
+// prepare <name> <symbol> build pump.fun-compatible metadata JSON, pin to IPFS
+// via /api/pinning/pin (if a session cookie is provided
+// via THREEWS_SESSION_COOKIE) or fall back to writing
+// the JSON to disk for manual hosting
+// launch <metadata-url> build + sign + submit a pump.fun create-v2 tx
+// using --wallet <keypair.json> as the buyer/fee-payer
+// and --creator <keypair.json> as the pump.fun creator
+// (the address whose pubkey is written to BondingCurve.creator).
+// Refuses to send unless --execute is also passed.
+// register <mint> insert a coin_launches row for an already-launched mint.
+// Requires DATABASE_URL. Defaults to is_live=false so the
+// cron runs in dry-run mode until you explicitly activate.
+// activate <mint> [--enable|--disable]
+// flip coin_launches.is_live for an existing row.
+//
+// Common flags:
+// --network mainnet|devnet (default: mainnet)
+// --rpc <url> override SOLANA_RPC_URL for the launch step
+//
+// Each subcommand prints the resulting state at the end so the operator can
+// copy/paste env vars into Vercel without re-running. No subcommand mutates
+// remote state without the operator explicitly invoking that command.
+
+import fs from 'node:fs';
+import path from 'node:path';
+import process from 'node:process';
+import readline from 'node:readline/promises';
+import { stdin as input, stdout as output } from 'node:process';
+import { fileURLToPath } from 'node:url';
+
+import {
+ Connection,
+ Keypair,
+ LAMPORTS_PER_SOL,
+ PublicKey,
+ TransactionMessage,
+ VersionedTransaction,
+} from '@solana/web3.js';
+import { AnchorProvider, Wallet } from '@coral-xyz/anchor';
+import { PumpSdk, getBuyTokenAmountFromSolAmount } from '@pump-fun/pump-sdk';
+import BN from 'bn.js';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(__dirname, '..');
+
+// ── env loader ──────────────────────────────────────────────────────────────
+
+function loadDotenv() {
+ for (const fname of ['.env.local', '.env', '.env.production']) {
+ const p = path.join(REPO_ROOT, fname);
+ if (!fs.existsSync(p)) continue;
+ for (const line of fs.readFileSync(p, 'utf8').split('\n')) {
+ const m = line.match(/^([A-Z0-9_]+)=(.*)$/);
+ if (!m) continue;
+ if (process.env[m[1]] === undefined) {
+ process.env[m[1]] = m[2].replace(/^['"]|['"]$/g, '');
+ }
+ }
+ }
+}
+loadDotenv();
+
+function rpcUrl(network) {
+ if (process.env.SOLANA_RPC_URL && network !== 'devnet') return process.env.SOLANA_RPC_URL;
+ if (network === 'devnet') {
+ return process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';
+ }
+ if (process.env.HELIUS_API_KEY) {
+ return `https://mainnet.helius-rpc.com/?api-key=${process.env.HELIUS_API_KEY}`;
+ }
+ return 'https://api.mainnet-beta.solana.com';
+}
+
+// ── arg parsing ─────────────────────────────────────────────────────────────
+
+function parseArgs(argv) {
+ const [cmd, ...rest] = argv.slice(2);
+ const positional = [];
+ const opts = {};
+ for (let i = 0; i < rest.length; i++) {
+ const a = rest[i];
+ if (a.startsWith('--')) {
+ const name = a.slice(2);
+ const next = rest[i + 1];
+ if (next === undefined || next.startsWith('--')) {
+ opts[name] = true;
+ } else {
+ opts[name] = next;
+ i++;
+ }
+ } else {
+ positional.push(a);
+ }
+ }
+ return { cmd, positional, opts };
+}
+
+// ── keypair helpers ─────────────────────────────────────────────────────────
+
+function loadKeypair(p) {
+ if (!fs.existsSync(p)) throw new Error(`keypair not found: ${p}`);
+ const secret = JSON.parse(fs.readFileSync(p, 'utf8'));
+ if (!Array.isArray(secret) || secret.length !== 64) {
+ throw new Error(`expected 64-byte JSON array at ${p}`);
+ }
+ return Keypair.fromSecretKey(Uint8Array.from(secret));
+}
+
+function writeKeypair(p, kp) {
+ fs.writeFileSync(p, JSON.stringify(Array.from(kp.secretKey)), { mode: 0o600 });
+}
+
+// ── confirmation prompt ─────────────────────────────────────────────────────
+
+async function confirm(prompt) {
+ const rl = readline.createInterface({ input, output });
+ const answer = (await rl.question(`${prompt} (type 'yes' to proceed) > `)).trim().toLowerCase();
+ rl.close();
+ return answer === 'yes';
+}
+
+// ── keygen ──────────────────────────────────────────────────────────────────
+
+async function cmdKeygen(opts) {
+ const kp = Keypair.generate();
+ const outPath = opts.out || path.join(REPO_ROOT, `.coin-keypair-${kp.publicKey.toBase58().slice(0, 8)}.json`);
+ writeKeypair(outPath, kp);
+ const b64 = Buffer.from(kp.secretKey).toString('base64');
+ console.log(JSON.stringify({
+ address: kp.publicKey.toBase58(),
+ keypair_file: outPath,
+ secret_key_b64: b64,
+ hint: {
+ next_step: 'Set COIN_TREASURY_SECRET_KEY_B64 (or COIN_CREATOR_SECRET_KEY_B64_<MINT>) to secret_key_b64.',
+ gitignore: 'Add the keypair file path to .gitignore before committing anything.',
+ },
+ }, null, 2));
+}
+
+// ── prepare metadata ────────────────────────────────────────────────────────
+
+async function cmdPrepare(positional, opts) {
+ const [name, symbol] = positional;
+ if (!name || !symbol) {
+ throw new Error('Usage: prepare <name> <symbol> [--description "..."] [--image <url>] [--website https://three.ws]');
+ }
+ const description = opts.description || `Lottery + SOL reflection coin. Live dashboard: ${opts.website || 'https://three.ws'}/coin`;
+ const website = opts.website || 'https://three.ws';
+ const image = opts.image || null;
+
+ const metadata = {
+ name,
+ symbol,
+ description,
+ ...(image ? { image } : {}),
+ showName: true,
+ createdOn: 'https://pump.fun',
+ website,
+ };
+
+ const outPath = opts.out || path.join(REPO_ROOT, `.coin-metadata-${symbol.toLowerCase()}.json`);
+ fs.writeFileSync(outPath, JSON.stringify(metadata, null, 2));
+
+ // If THREEWS_SESSION_COOKIE is set, try uploading to R2 via the
+ // /api/pump/build-metadata endpoint. Otherwise, the operator must host
+ // the JSON themselves (Pinata, GitHub Pages, etc).
+ const cookie = process.env.THREEWS_SESSION_COOKIE;
+ const apiOrigin = process.env.THREEWS_API_ORIGIN || 'https://three.ws';
+
+ let metadataUrl = null;
+ if (cookie) {
+ try {
+ const body = { name, symbol, description };
+ if (image && image.startsWith('data:')) body.image_data_url = image;
+ const resp = await fetch(`${apiOrigin}/api/pump/build-metadata`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', cookie },
+ body: JSON.stringify(body),
+ });
+ if (resp.ok) {
+ const data = await resp.json();
+ metadataUrl = data.metadata_url;
+ } else {
+ console.error(`(build-metadata upload failed: ${resp.status}; falling back to local file)`);
+ }
+ } catch (err) {
+ console.error(`(build-metadata upload errored: ${err.message}; falling back to local file)`);
+ }
+ }
+
+ console.log(JSON.stringify({
+ metadata,
+ metadata_file: outPath,
+ metadata_url: metadataUrl,
+ next_step: metadataUrl
+ ? `Run: node scripts/coin-cli.mjs launch ${metadataUrl} --wallet <buyer.json> --creator <creator.json>`
+ : `Host ${outPath} at a public HTTPS URL, then: node scripts/coin-cli.mjs launch <URL> --wallet <buyer.json> --creator <creator.json>`,
+ }, null, 2));
+}
+
+// ── launch ──────────────────────────────────────────────────────────────────
+
+async function cmdLaunch(positional, opts) {
+ const [uri] = positional;
+ if (!uri) throw new Error('Usage: launch <metadata-url> --wallet <buyer.json> --creator <creator.json> [--buy <sol>] [--name "..."] [--symbol "..."] [--execute]');
+ if (!opts.wallet) throw new Error('--wallet <buyer.json> is required (fee payer + initial buyer)');
+ if (!opts.creator) throw new Error('--creator <creator.json> is required (pump.fun creator address; receives creator fees)');
+ if (!opts.name) throw new Error('--name "..." is required');
+ if (!opts.symbol) throw new Error('--symbol "..." is required');
+
+ const network = opts.network || 'mainnet';
+ const rpc = opts.rpc || rpcUrl(network);
+ const buySol = opts.buy ? parseFloat(opts.buy) : 0;
+ if (Number.isNaN(buySol) || buySol < 0) throw new Error('Invalid --buy value');
+
+ const buyer = loadKeypair(opts.wallet);
+ const creator = loadKeypair(opts.creator);
+
+ let mint;
+ if (opts['mint-keypair']) {
+ mint = loadKeypair(opts['mint-keypair']);
+ console.error(`Using existing mint keypair: ${mint.publicKey.toBase58()}`);
+ } else {
+ mint = Keypair.generate();
+ }
+
+ const connection = new Connection(rpc, 'confirmed');
+
+ console.error('');
+ console.error('— Launch parameters —');
+ console.error(' network: ', network);
+ console.error(' RPC: ', rpc.replace(/api-key=[^&]+/, 'api-key=***'));
+ console.error(' buyer/payer:', buyer.publicKey.toBase58());
+ console.error(' creator: ', creator.publicKey.toBase58());
+ console.error(' mint: ', mint.publicKey.toBase58());
+ console.error(' name: ', opts.name);
+ console.error(' symbol: ', opts.symbol);
+ console.error(' metadata: ', uri);
+ console.error(' buy-in: ', buySol, 'SOL');
+ console.error('');
+
+ const balance = await connection.getBalance(buyer.publicKey);
+ console.error(` buyer balance: ${(balance / LAMPORTS_PER_SOL).toFixed(6)} SOL`);
+ const minNeeded = 0.025 + buySol;
+ if (balance / LAMPORTS_PER_SOL < minNeeded) {
+ throw new Error(`buyer needs at least ~${minNeeded.toFixed(3)} SOL (has ${(balance / LAMPORTS_PER_SOL).toFixed(4)})`);
+ }
+
+ const wallet = new Wallet(buyer);
+ const provider = new AnchorProvider(connection, wallet, { commitment: 'confirmed' });
+ const sdk = new PumpSdk(provider);
+
+ const instructions = [];
+ const mayhemMode = false;
+ if (buySol > 0) {
+ const global = await sdk.fetchGlobal();
+ const solAmount = new BN(Math.floor(buySol * LAMPORTS_PER_SOL));
+ const tokenAmount = getBuyTokenAmountFromSolAmount({
+ global,
+ feeConfig: null,
+ mintSupply: null,
+ bondingCurve: null,
+ amount: solAmount,
+ });
+ const ixs = await sdk.createV2AndBuyInstructions({
+ global,
+ mint: mint.publicKey,
+ name: opts.name,
+ symbol: opts.symbol,
+ uri,
+ creator: creator.publicKey,
+ user: buyer.publicKey,
+ solAmount,
+ amount: tokenAmount,
+ mayhemMode,
+ });
+ instructions.push(...(Array.isArray(ixs) ? ixs : [ixs]));
+ } else {
+ const ix = await sdk.createV2Instruction({
+ mint: mint.publicKey,
+ name: opts.name,
+ symbol: opts.symbol,
+ uri,
+ creator: creator.publicKey,
+ user: buyer.publicKey,
+ mayhemMode,
+ });
+ instructions.push(ix);
+ }
+
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
+ const msg = new TransactionMessage({
+ payerKey: buyer.publicKey,
+ recentBlockhash: blockhash,
+ instructions,
+ }).compileToV0Message();
+ const tx = new VersionedTransaction(msg);
+
+ // Sign with all three keys: buyer (fee payer + user), mint (new token authority),
+ // creator (only if it differs from buyer — pump.fun's program treats creator as
+ // an instruction argument, not a signer, so this is just defensive against future
+ // program upgrades that may add a signer requirement).
+ const signers = [buyer, mint];
+ if (creator.publicKey.toBase58() !== buyer.publicKey.toBase58()) signers.push(creator);
+ tx.sign(signers);
+
+ console.error('— Simulating —');
+ const sim = await connection.simulateTransaction(tx, { sigVerify: false });
+ if (sim.value.err) {
+ console.error('Simulation FAILED:', JSON.stringify(sim.value.err));
+ for (const l of sim.value.logs || []) console.error(' ', l);
+ throw new Error('aborting (simulation failed)');
+ }
+ console.error(' OK; compute units consumed:', sim.value.unitsConsumed);
+
+ if (!opts.execute) {
+ // Print the serialized tx so the operator can submit it manually if desired.
+ const serialized = Buffer.from(tx.serialize()).toString('base64');
+ console.error('');
+ console.error('DRY RUN — re-run with --execute to submit on-chain.');
+ console.log(JSON.stringify({
+ dry_run: true,
+ mint: mint.publicKey.toBase58(),
+ creator: creator.publicKey.toBase58(),
+ buyer: buyer.publicKey.toBase58(),
+ tx_base64: serialized,
+ next_step: 'Re-run with --execute, OR submit the tx_base64 yourself.',
+ }, null, 2));
+ return;
+ }
+
+ const proceed = await confirm(`About to launch ${opts.symbol} (${mint.publicKey.toBase58()}) on ${network} — proceed?`);
+ if (!proceed) {
+ console.error('aborted');
+ process.exit(1);
+ }
+
+ console.error('— Submitting —');
+ const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 5 });
+ console.error(' signature:', sig);
+ console.error(' solscan: https://solscan.io/tx/' + sig);
+
+ const conf = await connection.confirmTransaction(
+ { signature: sig, blockhash, lastValidBlockHeight },
+ 'confirmed',
+ );
+ if (conf.value.err) throw new Error('confirmation error: ' + JSON.stringify(conf.value.err));
+
+ console.error('LAUNCHED.');
+ console.log(JSON.stringify({
+ mint: mint.publicKey.toBase58(),
+ creator_wallet: creator.publicKey.toBase58(),
+ buyer_wallet: buyer.publicKey.toBase58(),
+ tx_signature: sig,
+ solscan: `https://solscan.io/tx/${sig}`,
+ pump_fun: `https://pump.fun/coin/${mint.publicKey.toBase58()}`,
+ next_step: `Run: node scripts/coin-cli.mjs register ${mint.publicKey.toBase58()} --name "${opts.name}" --symbol "${opts.symbol}" --creator-wallet ${creator.publicKey.toBase58()} --creator-secret-b64 <base64>`,
+ }, null, 2));
+}
+
+// ── register / activate (DB-only, uses Neon serverless driver) ──────────────
+
+async function neonSql() {
+ const [{ neon, neonConfig }, ws] = await Promise.all([
+ import('@neondatabase/serverless'),
+ import('ws'),
+ ]);
+ neonConfig.webSocketConstructor = ws.default || ws;
+ const url = process.env.DATABASE_URL;
+ if (!url) throw new Error('DATABASE_URL not set — required for register/activate');
+ return neon(url);
+}
+
+async function cmdRegister(positional, opts) {
+ const [mint] = positional;
+ if (!mint) throw new Error('Usage: register <mint> --name "..." --symbol "..." --creator-wallet <pubkey> [--creator-secret-b64 <b64>] [--lottery-bps 7000] [--reflection-bps 2500] [--ops-bps 500] [--draw-interval-seconds 3600] [--ops-wallet <pubkey>] [--network mainnet|devnet]');
+ if (!opts.name) throw new Error('--name is required');
+ if (!opts.symbol) throw new Error('--symbol is required');
+ if (!opts['creator-wallet']) throw new Error('--creator-wallet is required (the pump.fun creator pubkey for this mint)');
+
+ // Validate pubkey shape.
+ new PublicKey(mint);
+ new PublicKey(opts['creator-wallet']);
+ if (opts['ops-wallet']) new PublicKey(opts['ops-wallet']);
+
+ const lottery_bps = parseInt(opts['lottery-bps'] || '7000', 10);
+ const reflection_bps = parseInt(opts['reflection-bps'] || '2500', 10);
+ const ops_bps = parseInt(opts['ops-bps'] || '500', 10);
+ if (lottery_bps + reflection_bps + ops_bps !== 10_000) {
+ throw new Error('lottery_bps + reflection_bps + ops_bps must sum to 10000');
+ }
+ const draw_interval = parseInt(opts['draw-interval-seconds'] || '3600', 10);
+ const reflection_interval = parseInt(opts['reflection-interval-seconds'] || String(draw_interval), 10);
+
+ const metadata = {
+ notes: opts.notes || null,
+ treasury_is_creator: !!opts['treasury-is-creator'],
+ };
+ if (opts['creator-secret-b64']) {
+ metadata.creator_secret_b64 = opts['creator-secret-b64'];
+ }
+
+ const sql = await neonSql();
+ const rows = await sql`
+ insert into coin_launches (
+ mint, name, symbol, network, creator_wallet, ops_wallet,
+ lottery_bps, reflection_bps, ops_bps,
+ draw_interval_seconds, reflection_interval_seconds,
+ metadata, is_live
+ ) values (
+ ${mint}, ${opts.name}, ${opts.symbol}, ${opts.network || 'mainnet'},
+ ${opts['creator-wallet']}, ${opts['ops-wallet'] || null},
+ ${lottery_bps}, ${reflection_bps}, ${ops_bps},
+ ${draw_interval}, ${reflection_interval},
+ ${JSON.stringify(metadata)}::jsonb, false
+ )
+ on conflict (mint) do update set
+ name = excluded.name,
+ symbol = excluded.symbol,
+ creator_wallet = excluded.creator_wallet,
+ ops_wallet = excluded.ops_wallet,
+ lottery_bps = excluded.lottery_bps,
+ reflection_bps = excluded.reflection_bps,
+ ops_bps = excluded.ops_bps,
+ draw_interval_seconds = excluded.draw_interval_seconds,
+ reflection_interval_seconds = excluded.reflection_interval_seconds,
+ metadata = excluded.metadata,
+ updated_at = now()
+ returning id, mint, is_live, is_active
+ `;
+ const row = rows[0];
+ console.log(JSON.stringify({
+ coin_id: row.id,
+ mint: row.mint,
+ is_live: row.is_live,
+ is_active: row.is_active,
+ dashboard: `${process.env.PUBLIC_APP_ORIGIN || 'https://three.ws'}/coin/${row.mint}`,
+ next_step: opts['creator-secret-b64']
+ ? `Run: node scripts/coin-cli.mjs activate ${mint} --enable (after verifying the dry-run cron output)`
+ : `Set COIN_CREATOR_SECRET_KEY_B64_${mint} in Vercel env, then activate with --enable.`,
+ }, null, 2));
+}
+
+async function cmdActivate(positional, opts) {
+ const [mint] = positional;
+ if (!mint) throw new Error('Usage: activate <mint> --enable|--disable');
+ const enable = !!opts.enable;
+ const disable = !!opts.disable;
+ if (enable === disable) throw new Error('exactly one of --enable / --disable required');
+ const sql = await neonSql();
+ const rows = await sql`
+ update coin_launches set is_live = ${enable}, updated_at = now()
+ where mint = ${mint}
+ returning id, mint, is_live, is_active
+ `;
+ if (rows.length === 0) throw new Error(`no coin_launches row for mint ${mint}`);
+ console.log(JSON.stringify(rows[0], null, 2));
+}
+
+// ── main ────────────────────────────────────────────────────────────────────
+
+async function main() {
+ const { cmd, positional, opts } = parseArgs(process.argv);
+ if (!cmd || cmd === 'help' || cmd === '--help') {
+ console.error('coin-cli — lottery + reflection coin lifecycle');
+ console.error('');
+ console.error(' keygen [--out <path>]');
+ console.error(' prepare <name> <symbol> [--description "..."] [--image <url>] [--website https://three.ws]');
+ console.error(' launch <metadata-url> --wallet <buyer.json> --creator <creator.json> --name "..." --symbol "..."');
+ console.error(' [--buy <sol>] [--mint-keypair <path>] [--network mainnet|devnet] [--rpc <url>] [--execute]');
+ console.error(' register <mint> --name "..." --symbol "..." --creator-wallet <pubkey>');
+ console.error(' [--creator-secret-b64 <b64>] [--lottery-bps 7000] [--reflection-bps 2500] [--ops-bps 500]');
+ console.error(' [--draw-interval-seconds 3600] [--ops-wallet <pubkey>] [--network mainnet|devnet]');
+ console.error(' activate <mint> --enable|--disable');
+ process.exit(cmd ? 1 : 0);
+ }
+ if (cmd === 'keygen') await cmdKeygen(opts);
+ else if (cmd === 'prepare') await cmdPrepare(positional, opts);
+ else if (cmd === 'launch') await cmdLaunch(positional, opts);
+ else if (cmd === 'register') await cmdRegister(positional, opts);
+ else if (cmd === 'activate') await cmdActivate(positional, opts);
+ else throw new Error(`unknown subcommand: ${cmd}`);
+}
+
+main().catch((err) => {
+ console.error('ERROR:', err.message);
+ if (err.logs) for (const l of err.logs) console.error(' ', l);
+ process.exit(1);
+});
diff --git a/scripts/generate-accessory-glbs.mjs b/scripts/generate-accessory-glbs.mjs
new file mode 100644
index 000000000..0f7583b76
--- /dev/null
+++ b/scripts/generate-accessory-glbs.mjs
@@ -0,0 +1,458 @@
+#!/usr/bin/env node
+// Procedural accessory GLB generator.
+//
+// Builds the seven small GLB files referenced in public/accessories/presets.json:
+// hat-baseball.glb, hat-beanie.glb, hat-cowboy.glb,
+// glasses-round.glb, glasses-shades.glb,
+// earrings-hoops.glb, earrings-studs.glb
+//
+// Each is a real glTF 2.0 binary with positions, normals, UVs, indices, and a
+// PBR material — small enough (< 8 KB) to commit to the repo, large enough to
+// be visibly correct when attached to a humanoid avatar's Head bone.
+//
+// Coordinates are in meters, oriented for a head bone whose +Y is up and +Z
+// is forward (the standard glTF convention used by Mixamo, RPM, and Avaturn
+// outputs). The Head bone is typically located at the top of the neck; these
+// meshes are offset to sit naturally on top of / in front of / beside it.
+//
+// Run with: node scripts/generate-accessory-glbs.mjs
+
+import { Document, NodeIO } from '@gltf-transform/core';
+import { writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const OUT_DIR = path.resolve(HERE, '..', 'public', 'accessories');
+
+// ── Geometry primitives ────────────────────────────────────────────────────
+
+// Tessellated half-sphere ("dome") of radius r, sliced at y = 0.
+function halfSphere({ r = 1, segments = 16, rings = 8, yOffset = 0 } = {}) {
+ const positions = [];
+ const normals = [];
+ const uvs = [];
+ const indices = [];
+
+ for (let i = 0; i <= rings; i++) {
+ const v = i / rings;
+ const phi = v * (Math.PI / 2); // 0 (top) → π/2 (equator)
+ for (let j = 0; j <= segments; j++) {
+ const u = j / segments;
+ const theta = u * Math.PI * 2;
+ const x = r * Math.sin(phi) * Math.cos(theta);
+ const y = r * Math.cos(phi) + yOffset;
+ const z = r * Math.sin(phi) * Math.sin(theta);
+ positions.push(x, y, z);
+ const nLen = Math.hypot(x, y - yOffset, z) || 1;
+ normals.push(x / nLen, (y - yOffset) / nLen, z / nLen);
+ uvs.push(u, 1 - v);
+ }
+ }
+
+ const stride = segments + 1;
+ for (let i = 0; i < rings; i++) {
+ for (let j = 0; j < segments; j++) {
+ const a = i * stride + j;
+ const b = a + stride;
+ indices.push(a, b, a + 1, b, b + 1, a + 1);
+ }
+ }
+ return { positions, normals, uvs, indices };
+}
+
+// Solid cylinder of radius r between y=y0 and y=y1. side + caps.
+function cylinder({ r = 1, y0 = 0, y1 = 1, segments = 24 } = {}) {
+ const positions = [];
+ const normals = [];
+ const uvs = [];
+ const indices = [];
+
+ // Side
+ for (let j = 0; j <= segments; j++) {
+ const u = j / segments;
+ const theta = u * Math.PI * 2;
+ const x = Math.cos(theta);
+ const z = Math.sin(theta);
+ // bottom + top
+ positions.push(r * x, y0, r * z);
+ normals.push(x, 0, z);
+ uvs.push(u, 0);
+ positions.push(r * x, y1, r * z);
+ normals.push(x, 0, z);
+ uvs.push(u, 1);
+ }
+ for (let j = 0; j < segments; j++) {
+ const a = j * 2;
+ const b = a + 2;
+ indices.push(a, a + 1, b + 1, a, b + 1, b);
+ }
+
+ // Caps — fan triangulated from centers.
+ const ringStart = positions.length / 3;
+ // Top center
+ positions.push(0, y1, 0);
+ normals.push(0, 1, 0);
+ uvs.push(0.5, 0.5);
+ const topCenter = ringStart;
+ for (let j = 0; j <= segments; j++) {
+ const u = j / segments;
+ const theta = u * Math.PI * 2;
+ positions.push(r * Math.cos(theta), y1, r * Math.sin(theta));
+ normals.push(0, 1, 0);
+ uvs.push(0.5 + 0.5 * Math.cos(theta), 0.5 + 0.5 * Math.sin(theta));
+ }
+ for (let j = 0; j < segments; j++) {
+ indices.push(topCenter, topCenter + 1 + j, topCenter + 2 + j);
+ }
+
+ const botCenter = positions.length / 3;
+ positions.push(0, y0, 0);
+ normals.push(0, -1, 0);
+ uvs.push(0.5, 0.5);
+ for (let j = 0; j <= segments; j++) {
+ const u = j / segments;
+ const theta = u * Math.PI * 2;
+ positions.push(r * Math.cos(theta), y0, r * Math.sin(theta));
+ normals.push(0, -1, 0);
+ uvs.push(0.5 + 0.5 * Math.cos(theta), 0.5 + 0.5 * Math.sin(theta));
+ }
+ for (let j = 0; j < segments; j++) {
+ indices.push(botCenter, botCenter + 2 + j, botCenter + 1 + j);
+ }
+
+ return { positions, normals, uvs, indices };
+}
+
+// Annulus (flat ring) lying in the XZ plane at height y. innerR..outerR.
+function annulus({ y = 0, innerR = 1, outerR = 1.4, segments = 32 } = {}) {
+ const positions = [];
+ const normals = [];
+ const uvs = [];
+ const indices = [];
+ for (let j = 0; j <= segments; j++) {
+ const u = j / segments;
+ const theta = u * Math.PI * 2;
+ const c = Math.cos(theta);
+ const s = Math.sin(theta);
+ positions.push(innerR * c, y, innerR * s);
+ normals.push(0, 1, 0);
+ uvs.push(u, 0);
+ positions.push(outerR * c, y, outerR * s);
+ normals.push(0, 1, 0);
+ uvs.push(u, 1);
+ }
+ for (let j = 0; j < segments; j++) {
+ const a = j * 2;
+ const b = a + 2;
+ indices.push(a, a + 1, b + 1, a, b + 1, b);
+ indices.push(a, b + 1, a + 1, a, b, b + 1); // double-sided
+ }
+ return { positions, normals, uvs, indices };
+}
+
+// Torus in the XY plane, tube radius r2, ring radius r1.
+function torus({ r1 = 1, r2 = 0.1, segments = 32, tubeSegments = 12 } = {}) {
+ const positions = [];
+ const normals = [];
+ const uvs = [];
+ const indices = [];
+ for (let i = 0; i <= segments; i++) {
+ const u = i / segments;
+ const theta = u * Math.PI * 2;
+ const cx = r1 * Math.cos(theta);
+ const cy = r1 * Math.sin(theta);
+ for (let j = 0; j <= tubeSegments; j++) {
+ const v = j / tubeSegments;
+ const phi = v * Math.PI * 2;
+ const nx = Math.cos(theta) * Math.cos(phi);
+ const ny = Math.sin(theta) * Math.cos(phi);
+ const nz = Math.sin(phi);
+ positions.push(cx + r2 * nx, cy + r2 * ny, r2 * nz);
+ normals.push(nx, ny, nz);
+ uvs.push(u, v);
+ }
+ }
+ const stride = tubeSegments + 1;
+ for (let i = 0; i < segments; i++) {
+ for (let j = 0; j < tubeSegments; j++) {
+ const a = i * stride + j;
+ const b = a + stride;
+ indices.push(a, b, a + 1, b, b + 1, a + 1);
+ }
+ }
+ return { positions, normals, uvs, indices };
+}
+
+// Full sphere of radius r centered at origin.
+function sphere({ r = 1, segments = 16, rings = 10 } = {}) {
+ const positions = [];
+ const normals = [];
+ const uvs = [];
+ const indices = [];
+ for (let i = 0; i <= rings; i++) {
+ const v = i / rings;
+ const phi = v * Math.PI;
+ for (let j = 0; j <= segments; j++) {
+ const u = j / segments;
+ const theta = u * Math.PI * 2;
+ const x = Math.sin(phi) * Math.cos(theta);
+ const y = Math.cos(phi);
+ const z = Math.sin(phi) * Math.sin(theta);
+ positions.push(r * x, r * y, r * z);
+ normals.push(x, y, z);
+ uvs.push(u, 1 - v);
+ }
+ }
+ const stride = segments + 1;
+ for (let i = 0; i < rings; i++) {
+ for (let j = 0; j < segments; j++) {
+ const a = i * stride + j;
+ const b = a + stride;
+ indices.push(a, b, a + 1, b, b + 1, a + 1);
+ }
+ }
+ return { positions, normals, uvs, indices };
+}
+
+// ── GLB writer ─────────────────────────────────────────────────────────────
+
+// Build a GLB from an array of { geom, color, name, translate? } parts.
+// All parts live under a single root node so the AccessoryManager / bake step
+// can re-parent the whole accessory under a bone with one operation.
+async function writeGLB(filePath, parts, { rootName }) {
+ const doc = new Document();
+ doc.createBuffer();
+ doc.getRoot().getAsset().generator = 'three.ws procedural accessory generator';
+
+ const root = doc.createNode(rootName);
+
+ for (const part of parts) {
+ const positions = doc
+ .createAccessor(part.name + '_pos')
+ .setType('VEC3')
+ .setArray(new Float32Array(part.geom.positions));
+ const normals = doc
+ .createAccessor(part.name + '_nor')
+ .setType('VEC3')
+ .setArray(new Float32Array(part.geom.normals));
+ const uvs = doc
+ .createAccessor(part.name + '_uv')
+ .setType('VEC2')
+ .setArray(new Float32Array(part.geom.uvs));
+ const indices = doc
+ .createAccessor(part.name + '_idx')
+ .setType('SCALAR')
+ .setArray(new Uint16Array(part.geom.indices));
+
+ const material = doc
+ .createMaterial(part.name + '_mat')
+ .setBaseColorFactor([part.color[0], part.color[1], part.color[2], 1])
+ .setMetallicFactor(part.metallic ?? 0.05)
+ .setRoughnessFactor(part.roughness ?? 0.7)
+ .setDoubleSided(true);
+
+ const prim = doc
+ .createPrimitive()
+ .setAttribute('POSITION', positions)
+ .setAttribute('NORMAL', normals)
+ .setAttribute('TEXCOORD_0', uvs)
+ .setIndices(indices)
+ .setMaterial(material);
+
+ const mesh = doc.createMesh(part.name).addPrimitive(prim);
+ const node = doc.createNode(part.name).setMesh(mesh);
+ if (part.translate) node.setTranslation(part.translate);
+ if (part.rotation) node.setRotation(part.rotation);
+ if (part.scale) node.setScale(part.scale);
+ root.addChild(node);
+ }
+
+ const scene = doc.createScene(rootName).addChild(root);
+ doc.getRoot().setDefaultScene(scene);
+
+ const io = new NodeIO();
+ const bytes = await io.writeBinary(doc);
+ await writeFile(filePath, Buffer.from(bytes));
+ return bytes.byteLength;
+}
+
+// ── Accessory definitions ──────────────────────────────────────────────────
+//
+// All meshes are authored relative to the Head bone origin, which on a Mixamo
+// rig sits at the top of the neck. +Y is up, +Z is forward, scale is meters.
+// Head radius is roughly 0.10–0.12 m, so a hat needs r ≈ 0.11 to fit snugly.
+
+const ACCESSORIES = {
+ 'hat-baseball.glb': {
+ rootName: 'HatBaseball',
+ parts: [
+ // Crown: dome above the head, sitting just above the head bone.
+ {
+ name: 'crown',
+ geom: halfSphere({ r: 0.115, segments: 24, rings: 10, yOffset: 0.10 }),
+ color: [0.07, 0.18, 0.45], // navy
+ },
+ // Visor: thin disc, offset forward.
+ {
+ name: 'visor',
+ geom: annulus({ y: 0.105, innerR: 0.06, outerR: 0.17, segments: 24 }),
+ color: [0.07, 0.18, 0.45],
+ translate: [0, 0, 0.06], // push forward
+ scale: [1, 1, 0.6], // squash front-back so it looks like a visor not a disc
+ },
+ ],
+ },
+
+ 'hat-beanie.glb': {
+ rootName: 'HatBeanie',
+ parts: [
+ {
+ name: 'beanie',
+ geom: halfSphere({ r: 0.125, segments: 20, rings: 10, yOffset: 0.08 }),
+ color: [0.55, 0.12, 0.22], // wine red
+ roughness: 0.95, // wool
+ },
+ // Cuff (folded brim) — short cylinder around the base.
+ {
+ name: 'cuff',
+ geom: cylinder({ r: 0.125, y0: 0.07, y1: 0.10, segments: 24 }),
+ color: [0.45, 0.08, 0.16],
+ roughness: 0.95,
+ },
+ ],
+ },
+
+ 'hat-cowboy.glb': {
+ rootName: 'HatCowboy',
+ parts: [
+ // Crown — tall halfsphere
+ {
+ name: 'crown',
+ geom: halfSphere({ r: 0.11, segments: 20, rings: 10, yOffset: 0.11 }),
+ color: [0.32, 0.18, 0.07], // saddle brown
+ scale: [1, 1.4, 1],
+ },
+ // Brim — wide flat ring with subtle upcurl approximated via scale.
+ {
+ name: 'brim',
+ geom: annulus({ y: 0.11, innerR: 0.10, outerR: 0.24, segments: 32 }),
+ color: [0.32, 0.18, 0.07],
+ },
+ ],
+ },
+
+ 'glasses-round.glb': {
+ rootName: 'GlassesRound',
+ parts: [
+ // Left lens rim
+ {
+ name: 'rim_l',
+ geom: torus({ r1: 0.034, r2: 0.005, segments: 24, tubeSegments: 8 }),
+ color: [0.08, 0.08, 0.08],
+ metallic: 0.7,
+ roughness: 0.3,
+ translate: [-0.038, 0.005, 0.085],
+ },
+ // Right lens rim
+ {
+ name: 'rim_r',
+ geom: torus({ r1: 0.034, r2: 0.005, segments: 24, tubeSegments: 8 }),
+ color: [0.08, 0.08, 0.08],
+ metallic: 0.7,
+ roughness: 0.3,
+ translate: [0.038, 0.005, 0.085],
+ },
+ // Bridge
+ {
+ name: 'bridge',
+ geom: cylinder({ r: 0.005, y0: 0, y1: 0.018, segments: 8 }),
+ color: [0.08, 0.08, 0.08],
+ metallic: 0.7,
+ roughness: 0.3,
+ translate: [-0.009, 0.012, 0.085],
+ rotation: [0, 0, -0.707, 0.707], // rotate to lie horizontally along X
+ },
+ ],
+ },
+
+ 'glasses-shades.glb': {
+ rootName: 'GlassesShades',
+ parts: [
+ // Single wraparound lens approximated by a flat squashed annulus.
+ {
+ name: 'lens',
+ geom: annulus({ y: 0, innerR: 0.0, outerR: 0.085, segments: 32 }),
+ color: [0.05, 0.05, 0.08],
+ metallic: 0.1,
+ roughness: 0.15,
+ translate: [0, 0.005, 0.09],
+ scale: [1, 0.45, 0.4],
+ },
+ ],
+ },
+
+ 'earrings-hoops.glb': {
+ rootName: 'EarringsHoops',
+ parts: [
+ {
+ name: 'hoop_l',
+ geom: torus({ r1: 0.018, r2: 0.0025, segments: 20, tubeSegments: 8 }),
+ color: [0.95, 0.78, 0.20], // gold
+ metallic: 1.0,
+ roughness: 0.2,
+ translate: [-0.085, -0.02, 0.0],
+ },
+ {
+ name: 'hoop_r',
+ geom: torus({ r1: 0.018, r2: 0.0025, segments: 20, tubeSegments: 8 }),
+ color: [0.95, 0.78, 0.20],
+ metallic: 1.0,
+ roughness: 0.2,
+ translate: [0.085, -0.02, 0.0],
+ },
+ ],
+ },
+
+ 'earrings-studs.glb': {
+ rootName: 'EarringsStuds',
+ parts: [
+ {
+ name: 'stud_l',
+ geom: sphere({ r: 0.005, segments: 12, rings: 8 }),
+ color: [0.95, 0.95, 0.98],
+ metallic: 1.0,
+ roughness: 0.1,
+ translate: [-0.082, -0.005, 0.0],
+ },
+ {
+ name: 'stud_r',
+ geom: sphere({ r: 0.005, segments: 12, rings: 8 }),
+ color: [0.95, 0.95, 0.98],
+ metallic: 1.0,
+ roughness: 0.1,
+ translate: [0.082, -0.005, 0.0],
+ },
+ ],
+ },
+};
+
+// ── Main ───────────────────────────────────────────────────────────────────
+
+async function main() {
+ const results = [];
+ for (const [filename, spec] of Object.entries(ACCESSORIES)) {
+ const out = path.join(OUT_DIR, filename);
+ const bytes = await writeGLB(out, spec.parts, { rootName: spec.rootName });
+ results.push({ filename, bytes });
+ }
+ console.log('Wrote', results.length, 'accessory GLBs to', OUT_DIR);
+ for (const r of results) {
+ console.log(` ${r.filename.padEnd(28)} ${r.bytes.toString().padStart(6)} bytes`);
+ }
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/sdk/README.md b/sdk/README.md
index b9d0753a9..1950f9c02 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -28,6 +28,44 @@ agent.mount(document.body);
That's it — you now have a floating chat panel with voice I/O in the bottom-left corner.
+## Embed a 3D avatar
+
+Drop the avatar of any three.ws agent onto your page in two lines. Works in any
+framework or plain HTML — the helper lazy-loads the published
+[`<agent-3d>`](https://three.ws/agent-3d/latest/agent-3d.js) custom element
+from the three.ws CDN.
+
+```js
+import { loadAvatar } from '@nirholas/agent-kit';
+
+const handle = await loadAvatar({
+ agentId: 'agt_abc123',
+ container: document.getElementById('hero'),
+ controls: 'orbit',
+});
+
+handle.playAnimation('wave');
+// handle.dispose() when you're done
+```
+
+| Option | Type | Description |
+| ----------- | ----------------------- | --------------------------------------------------------------- |
+| `agentId` | `string` **(req)** | three.ws agent id |
+| `container` | `HTMLElement` **(req)** | Mount target |
+| `controls` | `'orbit' \| 'none'` | Camera controls (default: `'orbit'`) |
+| `cdnUrl` | `string` | Override the agent-3d script URL |
+| `integrity` | `string` | Optional SRI hash for the script tag |
+| `width` | `string` | CSS width (default: `'100%'`) |
+| `height` | `string` | CSS height (default: `'100%'`) |
+| `attrs` | `Record<string,string>` | Extra attributes forwarded to `<agent-3d>` (e.g. `bg`, `theme`) |
+
+Prefer plain HTML? Drop the script tag and element directly:
+
+```html
+<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
+<agent-3d agent-id="agt_abc123" controls="orbit"></agent-3d>
+```
+
## Register on-chain
```js
diff --git a/sdk/src/avatar.js b/sdk/src/avatar.js
new file mode 100644
index 000000000..06d9d41d7
--- /dev/null
+++ b/sdk/src/avatar.js
@@ -0,0 +1,125 @@
+/**
+ * @three-ws/sdk — Avatar embed helper.
+ *
+ * Drops a real, animated three.ws avatar onto any page. Works on any framework
+ * (or none) because under the hood it loads the published `<agent-3d>` custom
+ * element from the three.ws CDN.
+ *
+ * import { loadAvatar } from '@three-ws/sdk';
+ *
+ * const handle = await loadAvatar({
+ * agentId: 'agt_abc123',
+ * container: document.getElementById('hero'),
+ * controls: 'orbit',
+ * });
+ *
+ * // Later:
+ * handle.playAnimation('wave');
+ * handle.dispose();
+ *
+ * The script tag is injected at most once per page; subsequent calls reuse it.
+ * If your CSP blocks the default CDN you can pass `cdnUrl` to a self-hosted
+ * mirror — the script must define the `agent-3d` custom element.
+ */
+
+const DEFAULT_CDN = 'https://three.ws/agent-3d/latest/agent-3d.js';
+const CHANNEL_TO_INTEGRITY = new Map(); // cdnUrl -> Promise<void>
+
+/**
+ * @typedef {Object} LoadAvatarOptions
+ * @property {string} agentId three.ws agent id (required)
+ * @property {HTMLElement} container where to mount the element (required)
+ * @property {'orbit'|'none'} [controls] 'orbit' (default) or 'none'
+ * @property {string} [cdnUrl] override the agent-3d CDN URL
+ * @property {string} [integrity] optional SRI hash for the script tag
+ * @property {string} [width] CSS width (default: '100%')
+ * @property {string} [height] CSS height (default: '100%')
+ * @property {Object<string,string>} [attrs] extra attributes to forward to <agent-3d>
+ */
+
+/**
+ * Load the three.ws avatar component and mount it for a given agent.
+ *
+ * @param {LoadAvatarOptions} opts
+ * @returns {Promise<{ element: HTMLElement, playAnimation: (hint: string) => void, dispose: () => void }>}
+ */
+export async function loadAvatar(opts) {
+ if (!opts || typeof opts !== 'object') {
+ throw new TypeError('loadAvatar: options object required');
+ }
+ const { agentId, container } = opts;
+ if (!agentId) throw new TypeError('loadAvatar: agentId is required');
+ if (!container || !(container instanceof Element)) {
+ throw new TypeError('loadAvatar: container must be a DOM element');
+ }
+
+ const cdnUrl = opts.cdnUrl || DEFAULT_CDN;
+ await ensureAgent3DScript(cdnUrl, opts.integrity);
+
+ const el = document.createElement('agent-3d');
+ el.setAttribute('agent-id', agentId);
+ el.setAttribute('controls', opts.controls || 'orbit');
+ el.style.width = opts.width || '100%';
+ el.style.height = opts.height || '100%';
+ el.style.display = 'block';
+
+ if (opts.attrs && typeof opts.attrs === 'object') {
+ for (const [k, v] of Object.entries(opts.attrs)) {
+ if (v != null) el.setAttribute(k, String(v));
+ }
+ }
+
+ container.appendChild(el);
+
+ return {
+ element: el,
+ playAnimation(hint) {
+ if (typeof el.playAnimation === 'function') return el.playAnimation(hint);
+ if (typeof el.playAnimationByHint === 'function') return el.playAnimationByHint(hint);
+ return false;
+ },
+ dispose() {
+ el.remove();
+ },
+ };
+}
+
+function ensureAgent3DScript(cdnUrl, integrity) {
+ if (typeof customElements !== 'undefined' && customElements.get('agent-3d')) {
+ return Promise.resolve();
+ }
+ if (CHANNEL_TO_INTEGRITY.has(cdnUrl)) return CHANNEL_TO_INTEGRITY.get(cdnUrl);
+
+ const p = new Promise((resolve, reject) => {
+ const existing = document.querySelector(`script[data-three-ws-agent3d="${cssEscape(cdnUrl)}"]`);
+ if (existing) {
+ if (customElements.get('agent-3d')) return resolve();
+ existing.addEventListener('load', () => resolve(), { once: true });
+ existing.addEventListener('error', () => reject(new Error(`Failed to load ${cdnUrl}`)), { once: true });
+ return;
+ }
+ const s = document.createElement('script');
+ s.type = 'module';
+ s.src = cdnUrl;
+ s.async = true;
+ s.crossOrigin = 'anonymous';
+ s.dataset.threeWsAgent3d = cdnUrl;
+ if (integrity) s.integrity = integrity;
+ s.addEventListener('load', () => {
+ if (typeof customElements?.whenDefined === 'function') {
+ customElements.whenDefined('agent-3d').then(() => resolve(), reject);
+ } else {
+ resolve();
+ }
+ });
+ s.addEventListener('error', () => reject(new Error(`Failed to load ${cdnUrl}`)));
+ document.head.appendChild(s);
+ });
+
+ CHANNEL_TO_INTEGRITY.set(cdnUrl, p);
+ return p;
+}
+
+function cssEscape(s) {
+ return String(s).replace(/["\\]/g, '\\$&');
+}
diff --git a/sdk/src/index.d.ts b/sdk/src/index.d.ts
index 6b2c9dc49..7071ace06 100644
--- a/sdk/src/index.d.ts
+++ b/sdk/src/index.d.ts
@@ -55,6 +55,37 @@ export class AgentPanel {
dispose(): void;
}
+// ---------------------------------------------------------------------------
+// Avatar embed
+// ---------------------------------------------------------------------------
+
+export interface LoadAvatarOptions {
+ /** three.ws agent id (e.g. "agt_abc123") */
+ agentId: string;
+ /** Element to mount the avatar into */
+ container: HTMLElement;
+ /** 'orbit' (default) or 'none' */
+ controls?: 'orbit' | 'none';
+ /** Override the agent-3d CDN URL */
+ cdnUrl?: string;
+ /** Optional SRI integrity hash for the script tag */
+ integrity?: string;
+ /** CSS width (default: '100%') */
+ width?: string;
+ /** CSS height (default: '100%') */
+ height?: string;
+ /** Extra attributes to forward to the <agent-3d> element */
+ attrs?: Record<string, string>;
+}
+
+export interface AvatarHandle {
+ element: HTMLElement;
+ playAnimation(hint: string): unknown;
+ dispose(): void;
+}
+
+export function loadAvatar(options: LoadAvatarOptions): Promise<AvatarHandle>;
+
// ---------------------------------------------------------------------------
// AgentKit — the primary API
// ---------------------------------------------------------------------------
diff --git a/sdk/src/index.js b/sdk/src/index.js
index 2e0d85bea..61e7de047 100644
--- a/sdk/src/index.js
+++ b/sdk/src/index.js
@@ -26,6 +26,7 @@
*/
export { AgentPanel } from './panel.js';
+export { loadAvatar } from './avatar.js';
export { agentRegistration, agentCard, aiPlugin } from './manifests.js';
export {
connectWallet,
diff --git a/sdk/test/avatar.test.js b/sdk/test/avatar.test.js
new file mode 100644
index 000000000..487d93689
--- /dev/null
+++ b/sdk/test/avatar.test.js
@@ -0,0 +1,168 @@
+/**
+ * loadAvatar — unit tests
+ *
+ * Uses the Node built-in test runner (node:test) with a lightweight DOM shim.
+ * No real script is loaded — we assert on the elements created and the
+ * `src` attribute of the injected script tag.
+ */
+
+import { test, beforeEach } from 'node:test';
+import assert from 'node:assert/strict';
+
+// ---------------------------------------------------------------------------
+// Minimal DOM shim
+// ---------------------------------------------------------------------------
+
+class FakeNode {
+ constructor(tag) {
+ this.tagName = String(tag || '').toUpperCase();
+ this.children = [];
+ this.parent = null;
+ this.attributes = {};
+ this.dataset = {};
+ this.style = {};
+ this._listeners = {};
+ }
+ setAttribute(k, v) { this.attributes[k] = String(v); }
+ getAttribute(k) { return this.attributes[k]; }
+ appendChild(child) {
+ child.parent = this;
+ this.children.push(child);
+ // Auto-fire load on injected scripts so loadAvatar's await resolves.
+ if (child.tagName === 'SCRIPT') {
+ queueMicrotask(() => child._fire('load'));
+ }
+ return child;
+ }
+ remove() {
+ if (this.parent) {
+ const idx = this.parent.children.indexOf(this);
+ if (idx >= 0) this.parent.children.splice(idx, 1);
+ }
+ }
+ addEventListener(type, fn) {
+ (this._listeners[type] ||= []).push(fn);
+ }
+ _fire(type) {
+ (this._listeners[type] || []).forEach((fn) => fn({ type }));
+ }
+ querySelector(_sel) { return null; }
+}
+
+class FakeElement extends FakeNode {}
+
+function installDom() {
+ const document = {
+ head: new FakeNode('head'),
+ body: new FakeNode('body'),
+ createElement(tag) {
+ if (tag === 'script') {
+ const n = new FakeNode('script');
+ Object.defineProperty(n, 'src', {
+ get() { return this.attributes.src; },
+ set(v) { this.attributes.src = String(v); },
+ });
+ return n;
+ }
+ return new FakeElement(tag);
+ },
+ querySelector(_sel) { return null; },
+ };
+ const customElements = {
+ _defined: new Set(),
+ get(name) { return this._defined.has(name) ? function () {} : undefined; },
+ whenDefined(name) {
+ if (this._defined.has(name)) return Promise.resolve();
+ return new Promise((resolve) => {
+ const i = setInterval(() => {
+ if (this._defined.has(name)) { clearInterval(i); resolve(); }
+ }, 5);
+ });
+ },
+ _define(name) { this._defined.add(name); },
+ };
+ global.document = document;
+ global.customElements = customElements;
+ // Element ctor presence so instanceof checks pass for our fake nodes
+ global.Element = FakeNode;
+}
+
+beforeEach(() => {
+ installDom();
+ // Reset the module's internal cache between tests by re-importing fresh.
+});
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+test('loadAvatar injects the agent-3d script and mounts the element', async () => {
+ const { loadAvatar } = await import(`../src/avatar.js?fresh=${Date.now()}`);
+
+ // Resolve customElements.whenDefined as soon as the script's onload fires.
+ const origAppend = global.document.head.appendChild.bind(global.document.head);
+ global.document.head.appendChild = function (node) {
+ origAppend(node);
+ if (node.tagName === 'SCRIPT') global.customElements._define('agent-3d');
+ return node;
+ };
+
+ const container = global.document.createElement('div');
+ const handle = await loadAvatar({ agentId: 'agt_test_123', container });
+
+ // One script was added to <head>, pointing at the default CDN.
+ const scripts = global.document.head.children.filter((c) => c.tagName === 'SCRIPT');
+ assert.equal(scripts.length, 1);
+ assert.equal(scripts[0].attributes.src, 'https://three.ws/agent-3d/latest/agent-3d.js');
+ assert.equal(scripts[0].attributes.crossorigin || scripts[0].crossOrigin, 'anonymous');
+
+ // One agent-3d element was added to the container.
+ assert.equal(container.children.length, 1);
+ const el = container.children[0];
+ assert.equal(el.tagName, 'AGENT-3D');
+ assert.equal(el.getAttribute('agent-id'), 'agt_test_123');
+ assert.equal(el.getAttribute('controls'), 'orbit');
+ assert.equal(typeof handle.dispose, 'function');
+ assert.equal(typeof handle.playAnimation, 'function');
+
+ handle.dispose();
+ assert.equal(container.children.length, 0);
+});
+
+test('loadAvatar honours custom cdnUrl, controls, width, height, and extra attrs', async () => {
+ const { loadAvatar } = await import(`../src/avatar.js?fresh=${Date.now()}`);
+
+ const origAppend = global.document.head.appendChild.bind(global.document.head);
+ global.document.head.appendChild = function (node) {
+ origAppend(node);
+ if (node.tagName === 'SCRIPT') global.customElements._define('agent-3d');
+ return node;
+ };
+
+ const container = global.document.createElement('div');
+ await loadAvatar({
+ agentId: 'agt_xyz',
+ container,
+ controls: 'none',
+ cdnUrl: 'https://cdn.example.com/agent-3d.js',
+ width: '480px',
+ height: '320px',
+ attrs: { 'data-theme': 'dark', 'bg': 'transparent' },
+ });
+
+ const script = global.document.head.children.find((c) => c.tagName === 'SCRIPT');
+ assert.equal(script.attributes.src, 'https://cdn.example.com/agent-3d.js');
+
+ const el = container.children[0];
+ assert.equal(el.getAttribute('controls'), 'none');
+ assert.equal(el.style.width, '480px');
+ assert.equal(el.style.height, '320px');
+ assert.equal(el.getAttribute('data-theme'), 'dark');
+ assert.equal(el.getAttribute('bg'), 'transparent');
+});
+
+test('loadAvatar rejects missing agentId or container', async () => {
+ const { loadAvatar } = await import(`../src/avatar.js?fresh=${Date.now()}`);
+ await assert.rejects(() => loadAvatar({}), /agentId is required/);
+ await assert.rejects(() => loadAvatar({ agentId: 'x' }), /container must be a DOM element/);
+});
diff --git a/src/account.js b/src/account.js
index 0cfd68996..187409701 100644
--- a/src/account.js
+++ b/src/account.js
@@ -142,9 +142,84 @@ export async function saveRemoteGlbToAccount(source, meta = {}) {
console.warn('[account] thumbnail/auto-tag pipeline failed silently', err?.message);
});
+ // Fire-and-forget USDZ companion + half-body variant generation. iOS Quick
+ // Look needs a USDZ; VR seats use a waist-up GLB. Both are derived from
+ // the source blob in-memory, uploaded via dedicated presigns, then
+ // PATCHed onto the avatar row so the viewer picks them up next load.
+ generateAndSaveCompanions(avatar.id, blob).catch((err) => {
+ console.warn('[account] usdz/halfbody pipeline failed silently', err?.message);
+ });
+
return avatar;
}
+async function generateAndSaveCompanions(avatarId, glbBlob) {
+ const { glbBlobToUsdzBlob, glbBlobToHalfBodyBlob } = await import('./usdz-pipeline.js');
+
+ // USDZ companion for iOS Quick Look. Independent of the half-body pass so
+ // a failure in one doesn't poison the other.
+ (async () => {
+ let usdzBlob;
+ try {
+ usdzBlob = await glbBlobToUsdzBlob(glbBlob);
+ } catch (err) {
+ console.warn('[account] usdz export failed:', err?.message);
+ return;
+ }
+ try {
+ const pre = await postJson('/api/avatars/presign-usdz', {
+ avatar_id: avatarId,
+ size_bytes: usdzBlob.size,
+ });
+ const put = await fetch(pre.upload_url, {
+ method: 'PUT',
+ headers: { 'content-type': 'model/vnd.usdz+zip' },
+ body: usdzBlob,
+ });
+ if (!put.ok) throw new Error(`R2 usdz upload failed: ${put.status}`);
+ await apiFetch(`/api/avatars/${avatarId}`, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ usdz_key: pre.usdz_key }),
+ });
+ } catch (err) {
+ console.warn('[account] usdz upload/patch failed:', err?.message);
+ }
+ })();
+
+ // Half-body variant for VR. Optional — not every avatar has the recognizable
+ // lower-body bones we need to strip, in which case the generator throws and
+ // we silently skip.
+ (async () => {
+ let halfBlob;
+ try {
+ halfBlob = await glbBlobToHalfBodyBlob(glbBlob);
+ } catch (err) {
+ // Expected when an avatar has no leg bones (busts, robots, non-humans).
+ return;
+ }
+ try {
+ const pre = await postJson('/api/avatars/presign-halfbody', {
+ avatar_id: avatarId,
+ size_bytes: halfBlob.size,
+ });
+ const put = await fetch(pre.upload_url, {
+ method: 'PUT',
+ headers: { 'content-type': 'model/gltf-binary' },
+ body: halfBlob,
+ });
+ if (!put.ok) throw new Error(`R2 halfbody upload failed: ${put.status}`);
+ await apiFetch(`/api/avatars/${avatarId}`, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ halfbody_key: pre.halfbody_key }),
+ });
+ } catch (err) {
+ console.warn('[account] halfbody upload/patch failed:', err?.message);
+ }
+ })();
+}
+
async function captureAndTagAvatar(avatarId, storageKey) {
// Resolve the public GLB URL from the storage key.
const glbUrl = storageKey.startsWith('http')
diff --git a/src/agent-edit.js b/src/agent-edit.js
index be0ef40b3..f0cb79a4a 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -1,3 +1,6 @@
+import { AvatarCreator } from './avatar-creator.js';
+import { saveRemoteGlbToAccount } from './account.js';
+
const API_BASE = '/api';
const params = new URLSearchParams(location.search);
const agentId = params.get('id');
@@ -286,6 +289,7 @@ async function ensureOutfitTab() {
preview.appendChild(a3d);
await renderAvatarList();
+ await renderAnimationsPicker();
}
async function renderAvatarList() {
@@ -306,7 +310,14 @@ async function renderAvatarList() {
return;
}
- container.innerHTML = availableAvatars.map((av) => {
+ const createTile = `
+ <button type="button" class="avatar-tile avatar-create-tile" id="avatar-create-tile" title="Create a new avatar">
+ <div class="avatar-tile-ph avatar-create-icon" aria-hidden="true">+</div>
+ <span class="avatar-tile-name">Create new</span>
+ </button>
+ `;
+
+ const tiles = availableAvatars.map((av) => {
const thumb = av.thumbnail_url || av.url || '';
const isCurrent = av.id === agentData.avatar_id;
return `
@@ -318,9 +329,267 @@ async function renderAvatarList() {
`;
}).join('');
- container.querySelectorAll('.avatar-tile').forEach((btn) => {
+ container.innerHTML = createTile + tiles;
+
+ container.querySelectorAll('.avatar-tile[data-avatar-id]').forEach((btn) => {
btn.addEventListener('click', () => selectAvatar(btn.dataset.avatarId));
});
+ container.querySelector('#avatar-create-tile')?.addEventListener('click', () => openAvatarCreateMenu());
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Inline avatar creation
+// ─────────────────────────────────────────────────────────────────────────────
+
+let _avatarCreator = null;
+function getAvatarCreator() {
+ if (_avatarCreator) return _avatarCreator;
+ _avatarCreator = new AvatarCreator(document.body, async (blob, meta = {}) => {
+ await saveNewAvatarAndSelect(blob, meta);
+ });
+ return _avatarCreator;
+}
+
+function openAvatarCreateMenu() {
+ // Close any existing menu first.
+ document.getElementById('avatar-create-menu')?.remove();
+
+ const tile = document.getElementById('avatar-create-tile');
+ if (!tile) return;
+
+ const menu = document.createElement('div');
+ menu.id = 'avatar-create-menu';
+ menu.className = 'avatar-create-menu';
+ menu.setAttribute('role', 'menu');
+ menu.innerHTML = `
+ <button type="button" role="menuitem" data-source="characterstudio">
+ <span class="acm-title">Character Studio</span>
+ <span class="acm-sub">In-browser builder — hair, clothing, body</span>
+ </button>
+ <button type="button" role="menuitem" data-source="avaturn">
+ <span class="acm-title">Avaturn editor</span>
+ <span class="acm-sub">Selfie → photoreal avatar</span>
+ </button>
+ <button type="button" role="menuitem" data-source="upload">
+ <span class="acm-title">Upload GLB</span>
+ <span class="acm-sub">Bring your own model</span>
+ </button>
+ `;
+ document.body.appendChild(menu);
+
+ const r = tile.getBoundingClientRect();
+ menu.style.top = `${Math.round(window.scrollY + r.bottom + 8)}px`;
+ menu.style.left = `${Math.round(window.scrollX + r.left)}px`;
+
+ const close = () => {
+ menu.remove();
+ document.removeEventListener('mousedown', onDocDown, true);
+ document.removeEventListener('keydown', onKey, true);
+ };
+ const onDocDown = (e) => {
+ if (!menu.contains(e.target) && e.target !== tile) close();
+ };
+ const onKey = (e) => {
+ if (e.key === 'Escape') close();
+ };
+ document.addEventListener('mousedown', onDocDown, true);
+ document.addEventListener('keydown', onKey, true);
+
+ menu.querySelectorAll('button[data-source]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const src = btn.dataset.source;
+ close();
+ startAvatarCreate(src);
+ });
+ });
+}
+
+function startAvatarCreate(source) {
+ if (source === 'upload') {
+ triggerHiddenGlbInput();
+ return;
+ }
+ const creator = getAvatarCreator();
+ if (source === 'characterstudio') creator.open();
+ else if (source === 'avaturn') creator.openDefaultEditor();
+}
+
+function triggerHiddenGlbInput() {
+ let input = document.getElementById('inline-glb-input');
+ if (!input) {
+ input = document.createElement('input');
+ input.type = 'file';
+ input.accept = '.glb,model/gltf-binary';
+ input.id = 'inline-glb-input';
+ input.hidden = true;
+ document.body.appendChild(input);
+ input.addEventListener('change', async (e) => {
+ const file = e.target.files?.[0];
+ e.target.value = '';
+ if (!file) return;
+ // GLB magic-byte check before uploading.
+ const head = new Uint8Array(await file.slice(0, 4).arrayBuffer());
+ if (head[0] !== 0x67 || head[1] !== 0x6c || head[2] !== 0x54 || head[3] !== 0x46) {
+ const status = $('outfit-status');
+ if (status) { status.textContent = 'Not a valid .glb file.'; status.className = 'outfit-status err'; }
+ return;
+ }
+ const name = file.name.replace(/\.glb$/i, '').trim() || 'My Avatar';
+ await saveNewAvatarAndSelect(file, { provider: 'upload', name });
+ });
+ }
+ input.click();
+}
+
+async function saveNewAvatarAndSelect(blob, meta = {}) {
+ const status = $('outfit-status');
+ if (status) { status.textContent = 'Saving avatar…'; status.className = 'outfit-status saving'; }
+ try {
+ const provider = meta.provider || 'upload';
+ const source = provider === 'avaturn' ? 'avaturn' : provider === 'upload' ? 'upload' : 'import';
+ const source_meta = { provider, ...(meta.sourceUrl ? { source_url: meta.sourceUrl } : {}) };
+ const avatar = await saveRemoteGlbToAccount(blob, {
+ source,
+ source_meta,
+ name: meta.name,
+ });
+ if (status) { status.textContent = 'Attaching to agent…'; }
+ await selectAvatar(avatar.id);
+ // Refresh the picker so the new avatar shows up; selectAvatar already
+ // re-renders, but availableAvatars may be stale if the request raced.
+ if (!availableAvatars.some((a) => a.id === avatar.id)) {
+ availableAvatars = [avatar, ...availableAvatars];
+ await renderAvatarList();
+ }
+ } catch (err) {
+ if (status) { status.textContent = `Error: ${err.message || 'Failed to save avatar.'}`; status.className = 'outfit-status err'; }
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Animation picker
+// ─────────────────────────────────────────────────────────────────────────────
+
+const ANIMATIONS_MAX = 30;
+
+let animationLibrary = null; // [{ name, url, label, icon, loop }]
+let selectedAnimNames = new Set();
+let originalAnimNames = new Set();
+
+async function renderAnimationsPicker() {
+ const grid = $('anims-picker-grid');
+ const status = $('anims-status');
+ const saveBtn = $('anims-save');
+ if (!grid) return;
+
+ if (!animationLibrary) {
+ try {
+ const r = await fetch('/animations/manifest.json', { credentials: 'omit' });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ animationLibrary = await r.json();
+ } catch (err) {
+ grid.innerHTML = `<div class="error-msg" style="padding:1rem">Could not load animation library: ${escapeHtml(err.message)}</div>`;
+ return;
+ }
+ }
+
+ const current = Array.isArray(agentData.meta?.animations) ? agentData.meta.animations : [];
+ selectedAnimNames = new Set(current.map((a) => a.name));
+ originalAnimNames = new Set(selectedAnimNames);
+
+ grid.innerHTML = animationLibrary.map((a) => {
+ const selected = selectedAnimNames.has(a.name);
+ return `
+ <button type="button" class="anim-tile${selected ? ' selected' : ''}" data-anim-name="${escapeHtml(a.name)}" title="${escapeHtml(a.label || a.name)}">
+ <span class="anim-tile-icon" aria-hidden="true">${escapeHtml(a.icon || '🎬')}</span>
+ <span class="anim-tile-name">${escapeHtml(a.label || a.name)}</span>
+ <span class="anim-tile-check" aria-hidden="true">✓</span>
+ </button>
+ `;
+ }).join('');
+
+ grid.querySelectorAll('.anim-tile').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const name = btn.dataset.animName;
+ if (selectedAnimNames.has(name)) {
+ selectedAnimNames.delete(name);
+ btn.classList.remove('selected');
+ } else {
+ if (selectedAnimNames.size >= ANIMATIONS_MAX) {
+ if (status) {
+ status.textContent = `Up to ${ANIMATIONS_MAX} clips per agent.`;
+ status.className = 'form-status err';
+ }
+ return;
+ }
+ selectedAnimNames.add(name);
+ btn.classList.add('selected');
+ }
+ updateAnimSaveButton();
+ });
+ });
+
+ if (saveBtn && !saveBtn.dataset.wired) {
+ saveBtn.dataset.wired = '1';
+ saveBtn.addEventListener('click', saveAnimations);
+ }
+ updateAnimSaveButton();
+}
+
+function updateAnimSaveButton() {
+ const saveBtn = $('anims-save');
+ if (!saveBtn) return;
+ const dirty = selectedAnimNames.size !== originalAnimNames.size
+ || [...selectedAnimNames].some((n) => !originalAnimNames.has(n));
+ saveBtn.disabled = !dirty;
+}
+
+async function saveAnimations() {
+ const status = $('anims-status');
+ const saveBtn = $('anims-save');
+ if (!status || !saveBtn) return;
+
+ const animations = animationLibrary
+ .filter((a) => selectedAnimNames.has(a.name))
+ .map((a) => ({
+ name: a.name,
+ url: a.url,
+ loop: a.loop !== false,
+ source: 'mixamo',
+ addedAt: new Date().toISOString(),
+ }));
+
+ saveBtn.disabled = true;
+ status.textContent = 'Saving…';
+ status.className = 'form-status';
+
+ try {
+ const r = await fetch(`${API_BASE}/agents/${agentId}/animations`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ animations }),
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ throw new Error(j.error_description || j.error || `HTTP ${r.status}`);
+ }
+ const j = await r.json();
+ if (!agentData.meta) agentData.meta = {};
+ agentData.meta.animations = j.animations;
+ originalAnimNames = new Set(j.animations.map((a) => a.name));
+ selectedAnimNames = new Set(originalAnimNames);
+ status.textContent = `Saved ${j.animations.length} animation${j.animations.length === 1 ? '' : 's'}.`;
+ status.className = 'form-status ok';
+ // Repaint the live preview so the new clips are available immediately.
+ reloadOutfitPreview();
+ setTimeout(() => { status.textContent = ''; status.className = 'form-status'; }, 2500);
+ } catch (err) {
+ status.textContent = `Error: ${err.message}`;
+ status.className = 'form-status err';
+ } finally {
+ updateAnimSaveButton();
+ }
}
async function selectAvatar(avatarId) {
diff --git a/src/app.js b/src/app.js
index ab1fa4ca4..4adab15e9 100644
--- a/src/app.js
+++ b/src/app.js
@@ -853,6 +853,8 @@ class App {
await this.identity.load();
let glbUrl = '/avatars/cz.glb';
+ this._currentUsdzUrl = null;
+ this._currentHalfbodyUrl = null;
if (this.identity.avatarId) {
try {
const resp = await fetch(`/api/avatars/${this.identity.avatarId}`, {
@@ -861,6 +863,8 @@ class App {
if (resp.ok) {
const { avatar } = await resp.json();
if (avatar?.url) glbUrl = avatar.url;
+ this._currentUsdzUrl = avatar?.usdz_url || null;
+ this._currentHalfbodyUrl = avatar?.halfbody_url || null;
}
} catch {
/* fall through to default */
@@ -884,6 +888,8 @@ class App {
// Fetch the agent record and load its GLB into the editor (main UI, not embed)
let glbUrl = null;
+ this._currentUsdzUrl = null;
+ this._currentHalfbodyUrl = null;
try {
const resp = await fetch(`/api/agents/${agentId}`, { credentials: 'include' });
if (resp.ok) {
@@ -895,6 +901,8 @@ class App {
if (avatarResp.ok) {
const { avatar } = await avatarResp.json();
if (avatar?.url) glbUrl = avatar.url;
+ this._currentUsdzUrl = avatar?.usdz_url || null;
+ this._currentHalfbodyUrl = avatar?.halfbody_url || null;
}
}
}
@@ -1423,10 +1431,12 @@ class App {
// Configure external animations (Mixamo-style) for skinned models
this._configureAnimations(viewer);
- // Update AR button target (GLB URL only; no USDZ companion in this project)
+ // Update AR button target. iOS Quick Look uses the USDZ companion
+ // when present; Android/WebXR fall back to the GLB URL. Both come
+ // from the avatar record fetched before view() (_currentUsdzUrl).
if (viewer.setARTarget) {
const glbUrl = typeof rootFile === 'string' ? fileURL : null;
- viewer.setARTarget(glbUrl);
+ viewer.setARTarget(glbUrl, this._currentUsdzUrl || null);
}
if (!this.options.kiosk) {
diff --git a/src/ar/webxr.js b/src/ar/webxr.js
index 4639e38d0..21c8fb7a4 100644
--- a/src/ar/webxr.js
+++ b/src/ar/webxr.js
@@ -2,9 +2,34 @@
//
// Reuses the element's existing Three.js renderer by enabling XR mode on start
// and restoring the RAF loop on end. Hit-test places the agent on tap.
+//
+// XR also enables half-body mode by scaling every lower-body bone (leg, foot,
+// toe…) to zero, collapsing the corresponding skinned geometry to the bone's
+// rest position. This mirrors what the half-body GLB variant does, but at
+// runtime, without reloading the model — so the AgentAvatar empathy bindings
+// and animation manager stay attached.
import { Matrix4, Vector3 } from 'three';
+const LOWER_BODY_FRAGMENTS = [
+ 'upleg', 'leg', 'thigh', 'knee', 'shin', 'calf',
+ 'foot', 'toe', 'ankle',
+];
+
+function _normalizeBone(name) {
+ return String(name || '')
+ .toLowerCase()
+ .replace(/^mixamorig:?_?/, '')
+ .replace(/^cc_base_/, '')
+ .replace(/^armature[:_|]/, '')
+ .replace(/^rig[:_]/, '');
+}
+
+function _isLowerBody(name) {
+ const norm = _normalizeBone(name);
+ return LOWER_BODY_FRAGMENTS.some((f) => norm.includes(f));
+}
+
export class WebXRSession {
constructor(viewer, { onEnd } = {}) {
this._viewer = viewer;
@@ -17,6 +42,8 @@ export class WebXRSession {
this._savedBg = null;
this._savedPos = null;
this._savedRot = null;
+ /** @type {Array<{ bone: import('three').Bone, scale: Vector3 }>} */
+ this._halfBodyBones = [];
this._handleEnd = this._handleEnd.bind(this);
this._handleSelect = this._handleSelect.bind(this);
}
@@ -60,6 +87,10 @@ export class WebXRSession {
this._savedPos = content?.position.clone() ?? null;
this._savedRot = content?.rotation.clone() ?? null;
+ // Collapse lower-body bones so the avatar reads as a half-body bust in
+ // VR/AR — the user doesn't see their own legs in a passthrough rig.
+ this._enterHalfBody();
+
// Hand the render loop to the XR system (replaces RAF)
if (viewer._rafId !== null) {
cancelAnimationFrame(viewer._rafId);
@@ -148,10 +179,50 @@ export class WebXRSession {
if (viewer.content && this._savedPos) viewer.content.position.copy(this._savedPos);
if (viewer.content && this._savedRot) viewer.content.rotation.copy(this._savedRot);
+ // Restore full-body bone scales captured at XR start.
+ this._exitHalfBody();
+
viewer.controls.enabled = true;
viewer._needsRender = true;
viewer._updateRenderLoop();
this._onEnd?.();
}
+
+ // ── Half-body mode ────────────────────────────────────────────────────────
+
+ _enterHalfBody() {
+ const content = this._viewer.content;
+ if (!content) return;
+ this._halfBodyBones = [];
+
+ content.traverse((obj) => {
+ if (!obj.isSkinnedMesh || !obj.skeleton) return;
+ for (const bone of obj.skeleton.bones || []) {
+ if (!_isLowerBody(bone.name)) continue;
+ // Each bone may appear in multiple meshes; only record it once.
+ if (this._halfBodyBones.some((b) => b.bone === bone)) continue;
+ this._halfBodyBones.push({ bone, scale: bone.scale.clone() });
+ bone.scale.set(0.0001, 0.0001, 0.0001);
+ }
+ });
+ // Skeleton matrices need a fresh update so the zero-scale propagates
+ // to every dependent vertex on the next render.
+ content.traverse((obj) => {
+ if (obj.isSkinnedMesh && obj.skeleton) obj.skeleton.update();
+ });
+ }
+
+ _exitHalfBody() {
+ for (const { bone, scale } of this._halfBodyBones) {
+ bone.scale.copy(scale);
+ }
+ this._halfBodyBones = [];
+ const content = this._viewer.content;
+ if (content) {
+ content.traverse((obj) => {
+ if (obj.isSkinnedMesh && obj.skeleton) obj.skeleton.update();
+ });
+ }
+ }
}
diff --git a/src/avatar-creator.js b/src/avatar-creator.js
index 86b279610..2145ceca5 100644
--- a/src/avatar-creator.js
+++ b/src/avatar-creator.js
@@ -11,23 +11,48 @@ function getStudioUrl() {
return 'http://localhost:5173';
}
+function getReadyPlayerMeSubdomain() {
+ try {
+ if (typeof import.meta !== 'undefined' && import.meta.env?.VITE_RPM_SUBDOMAIN) {
+ return String(import.meta.env.VITE_RPM_SUBDOMAIN)
+ .trim()
+ .replace(/^https?:\/\//, '')
+ .replace(/\.readyplayer\.me.*$/, '');
+ }
+ } catch (_) {}
+ return 'demo';
+}
+
+// RPM iframe posts JSON-stringified payloads; older builds and some hosts have
+// posted raw objects too. Accept both shapes.
+function parseRpmEvent(data) {
+ if (typeof data === 'string') {
+ try { return JSON.parse(data); } catch { return null; }
+ }
+ if (data && typeof data === 'object') return data;
+ return null;
+}
+
export class AvatarCreator {
/**
* @param {Element} containerEl - Parent element to mount the modal into
- * @param {function(Blob): void} onExport - Called with the exported GLB Blob
+ * @param {function(Blob, {provider:string, sourceUrl?:string|null}): void} onExport - Called with the exported GLB Blob and provenance
* @param {object} [opts]
* @param {string} [opts.studioUrl] - Override the CharacterStudio URL
+ * @param {string} [opts.rpmSubdomain] - Override the Ready Player Me subdomain
*/
constructor(containerEl, onExport, opts = {}) {
this.container = containerEl;
this.onExport = onExport;
this.studioUrl = opts.studioUrl || getStudioUrl();
+ this.rpmSubdomain = opts.rpmSubdomain || getReadyPlayerMeSubdomain();
this.modal = null;
this.iframe = null;
this.sdk = null;
this._onMessage = null;
this._onKeyDown = null;
+ this._provider = null;
}
/**
@@ -38,8 +63,10 @@ export class AvatarCreator {
async open(sessionUrl) {
if (this.modal) return;
if (sessionUrl) {
+ this._provider = 'avaturn';
await this._openAvaturn(sessionUrl);
} else {
+ this._provider = 'characterstudio';
this._buildModal(true);
this._onMessage = (e) => this._handleCharacterStudioMessage(e);
window.addEventListener('message', this._onMessage);
@@ -53,9 +80,83 @@ export class AvatarCreator {
*/
async openDefaultEditor() {
if (this.modal) return;
+ this._provider = 'avaturn';
await this._openAvaturn();
}
+ /**
+ * Opens the Ready Player Me avatar creator in an iframe.
+ * Uses the Frame API: subscribes to v1 events and captures the GLB URL on export.
+ * Subdomain comes from VITE_RPM_SUBDOMAIN, defaulting to "demo".
+ *
+ * @param {object} [opts]
+ * @param {('halfbody'|'fullbody')} [opts.bodyType] - 'fullbody' (default) or 'halfbody'
+ * @param {boolean} [opts.clearCache] - clear stored RPM session (default true)
+ * @param {boolean} [opts.quickStart] - skip account creation prompts (default false)
+ */
+ async openReadyPlayerMe(opts = {}) {
+ if (this.modal) return;
+ this._provider = 'readyplayer';
+ this._buildModal(true);
+
+ const bodyType = opts.bodyType || 'fullbody';
+ const clearCache = opts.clearCache !== false;
+ const quickStart = !!opts.quickStart;
+ const params = new URLSearchParams({
+ frameApi: '',
+ bodyType,
+ ...(clearCache && { clearCache: 'true' }),
+ ...(quickStart && { quickStart: 'true' }),
+ });
+ const url = `https://${this.rpmSubdomain}.readyplayer.me/avatar?${params.toString()}`;
+
+ this._onMessage = (e) => this._handleReadyPlayerMessage(e);
+ window.addEventListener('message', this._onMessage);
+ this.iframe.src = url;
+ }
+
+ _handleReadyPlayerMessage(event) {
+ const json = parseRpmEvent(event.data);
+ if (!json || json.source !== 'readyplayerme') return;
+
+ if (json.eventName === 'v1.frame.ready') {
+ try {
+ this.iframe?.contentWindow?.postMessage(
+ JSON.stringify({
+ target: 'readyplayerme',
+ type: 'subscribe',
+ eventName: 'v1.**',
+ }),
+ '*',
+ );
+ } catch (err) {
+ console.error('[AvatarCreator] RPM subscribe failed:', err);
+ }
+ const loading = this.modal?.querySelector('.avatar-creator-loading');
+ if (loading) loading.style.display = 'none';
+ return;
+ }
+
+ if (json.eventName === 'v1.avatar.exported') {
+ const glbUrl = json.data?.url;
+ if (!glbUrl) return;
+ (async () => {
+ try {
+ const res = await fetch(glbUrl);
+ if (!res.ok) throw new Error(`RPM GLB fetch failed: ${res.status}`);
+ const blob = await res.blob();
+ const glbBlob = blob.type
+ ? blob
+ : new Blob([await blob.arrayBuffer()], { type: 'model/gltf-binary' });
+ this._fireExport(glbBlob, { sourceUrl: glbUrl });
+ } catch (err) {
+ console.error('[AvatarCreator] failed to fetch RPM GLB:', err);
+ this._showError('Failed to download the avatar. Please try again.');
+ }
+ })();
+ }
+ }
+
async _openAvaturn(url) {
this._buildModal(false);
try {
@@ -84,7 +185,7 @@ export class AvatarCreator {
const glbBlob = blob.type
? blob
: new Blob([await blob.arrayBuffer()], { type: 'model/gltf-binary' });
- this._fireExport(glbBlob);
+ this._fireExport(glbBlob, { sourceUrl: data.urlType === 'dataURL' ? null : glbUrl });
} catch (err) {
console.error('[AvatarCreator] failed to fetch Avaturn GLB:', err);
}
@@ -111,10 +212,10 @@ export class AvatarCreator {
this._fireExport(blob);
}
- _fireExport(blob) {
+ _fireExport(blob, meta = {}) {
if (this.onExport) {
try {
- this.onExport(blob);
+ this.onExport(blob, { provider: this._provider, ...meta });
} catch (err) {
console.error('[AvatarCreator] onExport handler threw:', err);
}
@@ -130,7 +231,7 @@ export class AvatarCreator {
}
/**
- * @param {boolean} withIframe - true for CharacterStudio (needs a pre-rendered iframe),
+ * @param {boolean} withIframe - true for CharacterStudio/RPM (needs a pre-rendered iframe),
* false for Avaturn SDK (SDK injects its own iframe).
*/
_buildModal(withIframe) {
diff --git a/src/avatar-page.js b/src/avatar-page.js
index e3b5886e4..e7683e85e 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -194,6 +194,9 @@ function renderShell(glbUrl) {
tone-mapping="aces"
environment-image="neutral"
reveal="auto"
+ ar
+ ar-modes="webxr scene-viewer quick-look"
+ ${avatar.usdz_url ? `ios-src="${esc(avatar.usdz_url)}"` : ''}
></model-viewer>
</div>
<div class="av-meta-strip" id="av-meta-strip">
diff --git a/src/create.js b/src/create.js
index 70c1221db..a396ec1b5 100644
--- a/src/create.js
+++ b/src/create.js
@@ -5,9 +5,16 @@ import { AvatarCreator } from './avatar-creator.js';
const GLB_MAGIC = [0x67, 0x6c, 0x54, 0x46];
async function boot() {
- const creator = new AvatarCreator(document.body, (blob) =>
- saveAndRedirect(blob, { source: 'avaturn' }),
- );
+ const creator = new AvatarCreator(document.body, (blob, meta = {}) => {
+ const provider = meta.provider || 'avaturn';
+ // Forward-compatible source mapping:
+ // - 'avaturn' is its own enum value (auto-links to default agent)
+ // - 'readyplayer' uses the API's 'import' value today (older deploys reject 'readyplayer'),
+ // with the canonical provider stored in source_meta so server-side auto-link still triggers
+ const source = provider === 'avaturn' ? 'avaturn' : 'import';
+ const source_meta = { provider, ...(meta.sourceUrl ? { source_url: meta.sourceUrl } : {}) };
+ return saveAndRedirect(blob, { source, source_meta });
+ });
document.getElementById('back-btn')?.addEventListener('click', () => {
if (history.length > 1) history.back();
@@ -18,6 +25,10 @@ async function boot() {
if (await isAtAvatarLimit()) return;
creator.openDefaultEditor();
});
+ wireCard('card-selfie', async () => {
+ if (await isAtAvatarLimit()) return;
+ creator.openDefaultEditor();
+ });
wireCard('card-upload-glb', (e) => {
// Tooltip anchors live inside the card; let them navigate normally.
if (e && e.target && e.target.closest('a')) return;
diff --git a/src/runtime/lipsync.js b/src/runtime/lipsync.js
index 9b57f7385..cb0ffcee3 100644
--- a/src/runtime/lipsync.js
+++ b/src/runtime/lipsync.js
@@ -103,7 +103,7 @@ function _resetMap(map) {
/**
* Drive jaw/mouth morph targets in sync with speech text via a phoneme heuristic.
- * Supports ARKit viseme_* targets (Ready Player Me avatars) and jawOpen/mouthOpen fallbacks.
+ * Supports ARKit viseme_* targets (Avaturn / Character Studio / Mixamo / VRM avatars) and jawOpen/mouthOpen fallbacks.
*
* @param {string} text — the spoken text
* @param {import('three').Object3D} root — avatar root (or scene) to traverse for morph targets
diff --git a/src/usdz-pipeline.js b/src/usdz-pipeline.js
new file mode 100644
index 000000000..b4ca0bd19
--- /dev/null
+++ b/src/usdz-pipeline.js
@@ -0,0 +1,157 @@
+// USDZ + half-body pipeline.
+//
+// Both helpers run entirely client-side:
+// 1. Load a GLB Blob into a Three.js scene via GLTFLoader.
+// 2. Either USDZ-export the whole scene, or strip the lower-body and GLB-
+// export the upper half.
+// 3. Return the resulting Blob, ready to PUT to a presigned R2 URL.
+//
+// The viewer pulls the resulting URLs from the avatar record and feeds them
+// into setARTarget() / loadHalfBody(), so iOS Quick Look and VR seats work
+// without any external converter or hosted RPM endpoint.
+
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
+import { USDZExporter } from 'three/addons/exporters/USDZExporter.js';
+import { MeshStandardMaterial, Color, DoubleSide } from 'three';
+
+// Bone-name fragments that mark the lower body. Matched case-insensitively
+// after stripping the standard prefixes (mixamorig:, CC_Base_, Armature|).
+const LOWER_BODY_FRAGMENTS = [
+ 'upleg', 'leg', 'thigh', 'knee', 'shin', 'calf',
+ 'foot', 'toe', 'ankle',
+];
+
+function _normalizeBone(name) {
+ return String(name || '')
+ .toLowerCase()
+ .replace(/^mixamorig:?_?/, '')
+ .replace(/^cc_base_/, '')
+ .replace(/^armature[:_|]/, '')
+ .replace(/^rig[:_]/, '');
+}
+
+function _isLowerBody(name) {
+ const norm = _normalizeBone(name);
+ return LOWER_BODY_FRAGMENTS.some((f) => norm.includes(f));
+}
+
+async function _loadGlbBlob(blob) {
+ const loader = new GLTFLoader();
+ const arrayBuf = await blob.arrayBuffer();
+ return new Promise((resolve, reject) => {
+ loader.parse(arrayBuf, '', resolve, reject);
+ });
+}
+
+/**
+ * Convert a GLB Blob to a USDZ Blob using three.js's USDZExporter.
+ *
+ * Materials are coerced to MeshStandardMaterial — USDZ only supports
+ * UsdPreviewSurface, and the exporter throws on unlit / phong / toon.
+ *
+ * @param {Blob} glbBlob — bytes of the source GLB
+ * @returns {Promise<Blob>} bytes packaged as a .usdz (zip-based) blob
+ */
+export async function glbBlobToUsdzBlob(glbBlob) {
+ const gltf = await _loadGlbBlob(glbBlob);
+ const scene = gltf.scene || gltf.scenes?.[0];
+ if (!scene) throw new Error('USDZ: glb contained no scene');
+
+ // Quick Look refuses Unlit/Phong/Toon materials; coerce to standard. The
+ // visual result is close-to-identical for the typical avatar PBR setup.
+ scene.traverse((obj) => {
+ if (!obj.isMesh) return;
+ const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
+ mats.forEach((m, i) => {
+ if (!m) return;
+ if (m.isMeshStandardMaterial) return;
+ const replacement = new MeshStandardMaterial({
+ color: m.color ? m.color.clone() : new Color(0xffffff),
+ map: m.map || null,
+ normalMap: m.normalMap || null,
+ roughness: typeof m.roughness === 'number' ? m.roughness : 0.85,
+ metalness: typeof m.metalness === 'number' ? m.metalness : 0.0,
+ transparent: !!m.transparent,
+ opacity: typeof m.opacity === 'number' ? m.opacity : 1,
+ side: m.side ?? DoubleSide,
+ });
+ if (Array.isArray(obj.material)) obj.material[i] = replacement;
+ else obj.material = replacement;
+ });
+ });
+
+ const exporter = new USDZExporter();
+ const usdzBytes = await exporter.parseAsync(scene);
+ return new Blob([usdzBytes], { type: 'model/vnd.usdz+zip' });
+}
+
+/**
+ * Build a half-body GLB from a full-body GLB by hiding the lower-body
+ * skeleton + skinned vertices, then GLB-exporting the result.
+ *
+ * Strategy: walk every skinned mesh, identify bone indices whose bone name
+ * looks like leg/foot/toe, and zero the bone weights for those vertices.
+ * Bone hierarchy is left intact so animation clips that reference lower
+ * bones still apply cleanly — they just don't deform any geometry.
+ *
+ * @param {Blob} glbBlob — bytes of the source GLB
+ * @returns {Promise<Blob>} half-body GLB blob
+ */
+export async function glbBlobToHalfBodyBlob(glbBlob) {
+ const gltf = await _loadGlbBlob(glbBlob);
+ const scene = gltf.scene || gltf.scenes?.[0];
+ if (!scene) throw new Error('halfbody: glb contained no scene');
+
+ let trimmedAny = false;
+
+ scene.traverse((obj) => {
+ if (!obj.isSkinnedMesh || !obj.skeleton) return;
+ const bones = obj.skeleton.bones || [];
+ const lowerBoneSet = new Set();
+ bones.forEach((b, idx) => {
+ if (_isLowerBody(b.name)) lowerBoneSet.add(idx);
+ });
+ if (!lowerBoneSet.size) return;
+
+ const skinIdx = obj.geometry.getAttribute('skinIndex');
+ const skinW = obj.geometry.getAttribute('skinWeight');
+ if (!skinIdx || !skinW) return;
+
+ // Zero out weights of vertices that are predominantly bound to lower
+ // bones. We keep the geometry around — Quick Look-friendly and avoids
+ // expensive re-indexing — and rely on the weight=0 to collapse those
+ // triangles to the rest pose (head/torso).
+ const count = skinIdx.count;
+ for (let v = 0; v < count; v++) {
+ let lowerWeight = 0;
+ for (let i = 0; i < 4; i++) {
+ const bone = skinIdx.getComponent(v, i);
+ const w = skinW.getComponent(v, i);
+ if (lowerBoneSet.has(bone)) lowerWeight += w;
+ }
+ if (lowerWeight > 0.5) {
+ for (let i = 0; i < 4; i++) {
+ skinW.setComponent(v, i, 0);
+ }
+ }
+ }
+ skinW.needsUpdate = true;
+ trimmedAny = true;
+ });
+
+ if (!trimmedAny) {
+ throw new Error('halfbody: no recognizable lower-body bones — skipping');
+ }
+
+ const exporter = new GLTFExporter();
+ const buffer = await new Promise((resolve, reject) => {
+ exporter.parse(
+ scene,
+ (out) => resolve(out),
+ (err) => reject(err),
+ { binary: true, embedImages: true },
+ );
+ });
+ return new Blob([buffer], { type: 'model/gltf-binary' });
+}
diff --git a/tests/avatar-bake.test.js b/tests/avatar-bake.test.js
new file mode 100644
index 000000000..03831bcc1
--- /dev/null
+++ b/tests/avatar-bake.test.js
@@ -0,0 +1,217 @@
+// Tests for the server-side avatar appearance baker.
+//
+// These exercise bakeAppearance() directly (no DB, no R2) using:
+// - a base GLB built in-memory containing a Head bone-style node and a mesh
+// with named morph targets we can verify get baked.
+// - the real public/accessories/*.glb files generated by
+// scripts/generate-accessory-glbs.mjs.
+//
+// Verifies:
+// 1. Morph weights from outfit.morphBinding are baked into node.weights
+// so a downstream loader sees the dressed pose without runtime work.
+// 2. A bone-attached accessory GLB ends up parented under the matching bone.
+// 3. appearanceHash() is order-invariant: { outfit: a, accessories: [b, c] }
+// hashes identically to { accessories: [b, c], outfit: a }.
+// 4. isBakeable() is false for null / empty appearance.
+
+import { describe, it, expect, beforeAll } from 'vitest';
+import { Document, NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import {
+ bakeAppearance,
+ appearanceHash,
+ isBakeable,
+ bakedStorageKeyFor,
+} from '../api/_lib/bake.js';
+
+// ── In-memory test base GLB ────────────────────────────────────────────────
+
+// Builds a tiny skeleton-shaped GLB with:
+// - a "Hips" → "Spine" → "Head" node chain (the bone names AccessoryManager
+// and bake.findBone() look for)
+// - a single triangle mesh under the root with two morph targets named
+// "Outfit_Casual" and "Outfit_Formal" so we can verify weight baking
+async function buildTestBaseGlb() {
+ const doc = new Document();
+ doc.createBuffer();
+ doc.getRoot().getAsset().generator = 'avatar-bake.test fixture';
+
+ // Bone chain
+ const hips = doc.createNode('Hips');
+ const spine = doc.createNode('Spine');
+ const head = doc.createNode('Head');
+ hips.addChild(spine);
+ spine.addChild(head);
+
+ // One triangle, three morph targets that displace the apex vertex.
+ const basePositions = new Float32Array([
+ 0, 0, 0,
+ 1, 0, 0,
+ 0.5, 1, 0,
+ ]);
+ const baseNormals = new Float32Array([
+ 0, 0, 1,
+ 0, 0, 1,
+ 0, 0, 1,
+ ]);
+ const indices = new Uint16Array([0, 1, 2]);
+
+ const posAccessor = doc.createAccessor('positions').setType('VEC3').setArray(basePositions);
+ const norAccessor = doc.createAccessor('normals').setType('VEC3').setArray(baseNormals);
+ const idxAccessor = doc.createAccessor('indices').setType('SCALAR').setArray(indices);
+
+ // Morph targets are stored as Primitive targets; each target is an
+ // {attribute → accessor} mapping describing the delta from base.
+ const targetCasualPos = doc
+ .createAccessor('outfit_casual_pos_delta')
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 0, 0, 0, 0, 0, 0.5, 0]));
+ const targetFormalPos = doc
+ .createAccessor('outfit_formal_pos_delta')
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 0, 0, 0, 0, 0, 1.0, 0]));
+
+ const prim = doc
+ .createPrimitive()
+ .setAttribute('POSITION', posAccessor)
+ .setAttribute('NORMAL', norAccessor)
+ .setIndices(idxAccessor)
+ .setMaterial(doc.createMaterial('base').setBaseColorFactor([0.5, 0.5, 0.5, 1]));
+
+ const targetCasual = doc.createPrimitiveTarget('Outfit_Casual').setAttribute('POSITION', targetCasualPos);
+ const targetFormal = doc.createPrimitiveTarget('Outfit_Formal').setAttribute('POSITION', targetFormalPos);
+ prim.addTarget(targetCasual);
+ prim.addTarget(targetFormal);
+
+ const mesh = doc.createMesh('body').addPrimitive(prim);
+ // Target names live on mesh.extras.targetNames per the KHR convention.
+ mesh.setExtras({ targetNames: ['Outfit_Casual', 'Outfit_Formal'] });
+
+ const bodyNode = doc.createNode('body').setMesh(mesh);
+
+ const scene = doc.createScene('root').addChild(hips).addChild(bodyNode);
+ doc.getRoot().setDefaultScene(scene);
+
+ const io = new NodeIO();
+ return io.writeBinary(doc);
+}
+
+let BASE_GLB = null;
+let BASEBALL_GLB = null;
+
+beforeAll(async () => {
+ BASE_GLB = await buildTestBaseGlb();
+ BASEBALL_GLB = await readFile(
+ path.resolve(process.cwd(), 'public/accessories/hat-baseball.glb'),
+ );
+});
+
+// ── Helpers ────────────────────────────────────────────────────────────────
+
+async function inspect(glbBytes) {
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ return io.readBinary(new Uint8Array(glbBytes));
+}
+
+function findNode(doc, name) {
+ return doc.getRoot().listNodes().find((n) => n.getName() === name) || null;
+}
+
+// ── Tests ──────────────────────────────────────────────────────────────────
+
+describe('isBakeable', () => {
+ it('rejects null / undefined / empty', () => {
+ expect(isBakeable(null)).toBe(false);
+ expect(isBakeable(undefined)).toBe(false);
+ expect(isBakeable({})).toBe(false);
+ expect(isBakeable({ accessories: [] })).toBe(false);
+ expect(isBakeable({ morphs: {} })).toBe(false);
+ });
+
+ it('accepts any non-empty field', () => {
+ expect(isBakeable({ outfit: 'outfit-casual' })).toBe(true);
+ expect(isBakeable({ accessories: ['hat-baseball'] })).toBe(true);
+ expect(isBakeable({ morphs: { Smile: 0.5 } })).toBe(true);
+ });
+});
+
+describe('appearanceHash', () => {
+ it('is stable across key order', () => {
+ const a = appearanceHash({ outfit: 'outfit-casual', accessories: ['hat-baseball'] });
+ const b = appearanceHash({ accessories: ['hat-baseball'], outfit: 'outfit-casual' });
+ expect(a).toBe(b);
+ });
+
+ it('differs when content differs', () => {
+ const a = appearanceHash({ outfit: 'outfit-casual' });
+ const b = appearanceHash({ outfit: 'outfit-formal' });
+ expect(a).not.toBe(b);
+ });
+
+ it('is 64 hex chars (sha256)', () => {
+ expect(appearanceHash({ outfit: 'outfit-casual' })).toMatch(/^[a-f0-9]{64}$/);
+ });
+});
+
+describe('bakedStorageKeyFor', () => {
+ it('keeps the user/slug prefix and embeds a hash slice', () => {
+ const key = bakedStorageKeyFor({
+ baseStorageKey: 'u/abc123/dancer/xyz.glb',
+ hash: 'a'.repeat(64),
+ });
+ expect(key.startsWith('u/abc123/dancer/baked-')).toBe(true);
+ expect(key.endsWith('.glb')).toBe(true);
+ });
+});
+
+describe('bakeAppearance — morph weights', () => {
+ it('bakes outfit morphBinding into the mesh weights so downstream loaders see the pose', async () => {
+ const baked = await bakeAppearance(BASE_GLB, {
+ outfit: 'outfit-casual', // public/accessories/presets.json → { Outfit_Casual: 1.0 }
+ });
+
+ const doc = await inspect(baked);
+ const bodyNode = findNode(doc, 'body');
+ expect(bodyNode).toBeTruthy();
+
+ // Either node-level weights or mesh-level weights should carry the bake.
+ const weights = bodyNode.getWeights();
+ expect(weights.length).toBe(2);
+ // Outfit_Casual is target #0 in our fixture.
+ expect(weights[0]).toBeCloseTo(1.0, 3);
+ expect(weights[1]).toBeCloseTo(0.0, 3);
+ });
+
+ it('applies appearance.morphs overrides on top of preset bindings', async () => {
+ const baked = await bakeAppearance(BASE_GLB, {
+ outfit: 'outfit-casual',
+ morphs: { Outfit_Casual: 0.25, Outfit_Formal: 0.75 },
+ });
+ const doc = await inspect(baked);
+ const bodyNode = findNode(doc, 'body');
+ const weights = bodyNode.getWeights();
+ expect(weights[0]).toBeCloseTo(0.25, 3);
+ expect(weights[1]).toBeCloseTo(0.75, 3);
+ });
+});
+
+describe('bakeAppearance — bone-attached accessories', () => {
+ it('parents the hat-baseball mesh under the Head bone after baking', async () => {
+ const baked = await bakeAppearance(BASE_GLB, {
+ accessories: ['hat-baseball'],
+ });
+ const doc = await inspect(baked);
+
+ const head = findNode(doc, 'Head');
+ expect(head).toBeTruthy();
+
+ // After bake, Head should have at least one child that came from the
+ // hat-baseball.glb root (named "HatBaseball" by the generator).
+ const headChildren = head.listChildren();
+ const hatRoot = headChildren.find((n) => n.getName() === 'HatBaseball');
+ expect(hatRoot).toBeTruthy();
+ });
+});
diff --git a/vercel.json b/vercel.json
index bae2a7d94..926224d5a 100644
--- a/vercel.json
+++ b/vercel.json
@@ -732,6 +732,42 @@
"src": "/api/pump/recent-graduations",
"dest": "/api/pump/[action]?action=recent-graduations"
},
+ {
+ "src": "/api/coin/state",
+ "dest": "/api/coin/[action]?action=state"
+ },
+ {
+ "src": "/api/coin/holder",
+ "dest": "/api/coin/[action]?action=holder"
+ },
+ {
+ "src": "/api/coin/history",
+ "dest": "/api/coin/[action]?action=history"
+ },
+ {
+ "src": "/api/coin/events",
+ "dest": "/api/coin/[action]?action=events"
+ },
+ {
+ "src": "/api/coin/winners",
+ "dest": "/api/coin/[action]?action=winners"
+ },
+ {
+ "src": "/api/coin/holders",
+ "dest": "/api/coin/[action]?action=holders"
+ },
+ {
+ "src": "/coin",
+ "dest": "/coin/index.html"
+ },
+ {
+ "src": "/coin/",
+ "dest": "/coin/index.html"
+ },
+ {
+ "src": "/coin/([1-9A-HJ-NP-Za-km-z]{32,44})/?",
+ "dest": "/coin/index.html"
+ },
{
"src": "/api/avatars/presign",
"dest": "/api/avatars/[id]"
@@ -745,6 +781,14 @@
"src": "/api/avatars/presign-thumbnail",
"dest": "/api/avatars/[id]"
},
+ {
+ "src": "/api/avatars/presign-usdz",
+ "dest": "/api/avatars/[id]"
+ },
+ {
+ "src": "/api/avatars/presign-halfbody",
+ "dest": "/api/avatars/[id]"
+ },
{
"src": "/api/avatars/auto-tag",
"dest": "/api/avatars/[id]"
@@ -1455,6 +1499,14 @@
{
"path": "/api/cron/process-subscriptions",
"schedule": "0 */6 * * *"
+ },
+ {
+ "path": "/api/cron/run-coin-cycle",
+ "schedule": "*/5 * * * *"
+ },
+ {
+ "path": "/api/cron/run-coin-payouts",
+ "schedule": "1-59/5 * * * *"
}
]
}