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(drops): launch a supply-capped 3D collection from a style and weighted trait layers

nirholas714339a7f477
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9bab5e88c..9a3693076 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,12 +6,15 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-09-01
+- **3D Drops** (`/drops`): Launch a supply-capped collection of AI-forged 3D characters. Pick a style, define weighted trait layers, and three.ws rolls the whole supply from a published seed: verifiable rarity, rigged animation-ready art, forged on reveal.
+- **3D Drops** (`/docs/drops`): How generative 3D collections work on three.ws: weighted trait layers, a supply rolled from a published seed, rarity scored from the actual distribution, art forged per item on reveal, and a verify endpoint anyone can recompute the roll with.
- **$THREE tiers page: the ladder now loads for everyone, signed in or not**: Opening /three without a wallet connected or an account signed in showed an error card instead of the tiers, because the tier lookup refused anonymous requests. The page now shows every tier, its perks, and the exact $THREE threshold to any visitor, with a connect-wallet or sign-in prompt to see your own position. Signed-in accounts without a linked wallet get a clear prompt to connect one, and if the ladder genuinely fails to load the page keeps its heading and offers a retry. (`/three`) `[fix]`
- **Claim threews.sol Subdomain: a clear account status in every case, a fit on small phones, and the light theme**: The /threews/claim page now tells you where you stand the moment it loads: a loading placeholder while it checks your account, a sign-in prompt if you are signed out, a link to set a username if your account has none, and a plain explanation with a link to change it if your username has characters a .sol name cannot hold (before, that case ended in a bare validation error with nowhere to go). If the account check or the availability check cannot reach three.ws, the page says so and offers a retry instead of going quiet; a failed mint keeps its reason on screen with a retry when the failure was temporary and a link to create an agent when a wallet is what is missing. The .threews.sol suffix no longer spills off the edge on 320px screens, every control has a visible keyboard focus ring, and the page follows the light theme instead of staying black. (`/threews/claim`) `[fix, improvement]`
- **Documentation sweep: 164 docs re-checked against the code they describe**: Every doc the freshness gate flagged as describing code that had moved since it was written (174 of them, from the UX flow walkthroughs and the Oracle model write-up to the ops runbooks, tutorials, and the agent-abilities chapters) was re-read against the current code. 164 were corrected or extended: renamed routes now point at /agents/:id, retired model names and provider ladders are current, counts and thresholds match what ships, and the resilience work of the last month (last-good caches, typed 503s with Retry-After, the RPC read guards) is described where it applies. Along the way three things the docs promised were made true in the product: the Herald posting scope can now be minted from the dashboard key form, the translation script defaults to a Groq model that still exists, and the home page OpenAPI link opens the spec directly. (`/docs/freshness`) `[docs, fix]`
- **Faster pages: the home page stops freezing itself, and every page sheds code it never ran**: A performance sweep of the home page, Create, Forge, Marketplace, Play, Docs, Discover and Chat, measured with Lighthouse and a CPU profiler. The home page's live agent no longer gets torn down by a 22-second timer while it is still loading (the teardown forced a WebGL context loss that froze the tab, and showed a false "couldn't load" message on slow connections), and the playground preview and the visitor-arena animation below the fold now wait until you scroll to them. The theme switcher stopped re-checking the page's light-mode support on every DOM change, which had cost the Marketplace almost nine seconds of main-thread time. The embed script at /agent-3d/latest is 25% smaller: its whitespace minifier was being undone by a later build step. The animation clip library is half its previous size with no visible change (numbers are stored at float precision instead of 17 digits). Web fonts now swap in without moving text, Forge gallery thumbnails load as small WebP tiles instead of full renders, and pages that only show the wallet tier badge no longer download the Solana wallet stack. (`/`) `[improvement, fix, infra]`
- **Get Started wizard: avatars come back into the flow, the brain you pick is the brain you get, and sign-in happens at publish time**: The 5-step wizard at /start now finishes what it starts. Taking a selfie, writing a prompt, building in the studio, or using the editor brings the finished avatar straight back into the wizard instead of stranding you on the avatar page, and Upload GLB uses the same storage path as every other upload, so it works. The AI model you choose is now applied to the agent (before, it was collected and dropped), the embed snippet points at the real loader, and a signed-out visitor who reaches the publish step gets a sign-in panel that resumes exactly where they left off rather than a cryptic error. Helper pills no longer sit on top of the Continue button, off-screen steps are no longer tabbable, the price and wallet fields have names for screen readers, and failed price or wallet saves are reported instead of swallowed. (`/start`) `[fix, improvement]`
- **Guided Tour page: real track counts, a clean fit on small phones, and a proper fallback when the outline is slow**: The Quick highlights and Full tour cards on /tour now show their real stop counts and minutes (they were being reset to placeholder text a moment after loading), the chapter list matches the tour itself and no longer lists the separate getting-started walkthrough as a chapter, the page no longer clips its right edge on 320px screens, and if the tour outline fails to load you get a clear message with a retry button instead of an empty section. (`/tour`) `[fix, improvement]`
+- **Launch a 3D collection without a studio**: 3D Drops is live. Give it a base style and a few trait layers with weights, and it rolls a whole supply-capped collection in one go: up to 10,000 unique characters, each one a real rigged, animation-ready model rather than a flat picture. The roll is instant and free at any size because the art is generated per item when you reveal it, not rendered in bulk up front. Rarity is computed from the supply that actually came out, ranked, and sorted into common, rare, epic and legendary. Every collection publishes a fingerprint of its own recipe and, once launched, the seed behind it, so anyone can recompute the entire supply and check it against what the site served them. There is a Verify button on every collection page that does exactly that. (`/drops`) `[feature]`
- **Living Stages: the live feed connects in production, so the host actually performs**: Every stage on three.ws/stage was reading "feed offline" in production: the page never told the browser where the realtime venue server lives, and even when pointed at it, the client tripped over an ordering quirk while subscribing to the host's state and dropped the opening line. The venue now connects the way /play does, subscribes correctly, and registers for the host's words before anything else, so you hear and read the host from the first beat, see who else is in the room, and get an acknowledgement when your question is queued. The feed pill is now a real control: when the feed drops, tap it to reconnect. A dead stage link explains itself and points back to the live marquee, a network blip retries in place without reloading, every button on the page has a visible keyboard focus ring, and the page description says what a Living Stage actually is. (`/stage`) `[fix, improvement]`
- **Mission Control: the cockpit now works signed out and on a phone**: Open /terminal without an account and the Focus and Positions panes tell you exactly what unlocks trading (sign in, or create an agent wallet) instead of showing buy and sell buttons that could only refuse, and the Positions pill reads idle rather than reconnecting forever. Token art now loads through the same-origin image proxy, so coins whose art lives on IPFS gateways that refuse browser requests show their image instead of a blank tile. On phones the first launch that streams in no longer yanks you off the feed to the Focus tab, and the Positions tab is tappable again: the floating language picker used to sit on top of it, so it now lives in the cockpit's top bar. A seconds-old coin whose details pump.fun has not indexed yet is retried once when the server says to, and the page carries a proper h1 for screen readers. (`/terminal`) `[improvement, fix]`
- **Readable header navigation from the first paint, and a readable feed status on the terminal**: On a cold load, the theme system's capability check could leave the header's navigation labels stuck on the light theme's grey over the dark bar for several seconds, well under the contrast people need to read them. The check now runs without triggering colour transitions, so Build, Discover, Learn, Search, Walk, Sign in and Console render in their intended colours the moment the header appears. On /terminal the "Positions" feed-status chip no longer fades its label along with its idle dot, so it stays readable against the bar. The automated accessibility floor that caught it now measures pages once their entrance animations have finished, so it reports what a reader sees rather than a half-faded frame. (`/terminal`) `[fix, improvement]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index afdaec3d5..5e35660e6 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -177,6 +177,7 @@ bottom.
| Reputation Staking Market | spec [specs/REPUTATION_STAKING_MARKET.md](specs/REPUTATION_STAKING_MARKET.md), engine [src/shared/reputation-staking.js](src/shared/reputation-staking.js), server [api/_lib/reputation-market.js](api/_lib/reputation-market.js) + [api/reputation/market*.js](api/reputation), surface [public/reputation/market/](public/reputation/market) `→ /reputation/market` | In-repo · devnet open, mainnet owner-gated | Phase 3 roadmap: stake conviction on an agent and earn from its attested action history. A stake is a staker-signed Solana transfer to the market escrow carrying an `rsm.v1` SPL-Memo, so the chain (not the database) defines a position; the server only verifies it by reading the transaction back. Yield comes from a fixed per-epoch pool split by `principal × time × agentWeight`, where the weight is derived purely from the agent's signed `threews.*` attestations (work concave in `log2`, faults charged double), so conviction never pays itself. Principal is never slashed and settlement clamps earnings to the escrow surplus. Extends the SPL-Memo attestation layer in [docs/solana-reputation.md](docs/solana-reputation.md). Storage: [reputation_staking_market migration](api/_lib/migrations/20260811140000_reputation_staking_market.sql). Walkthrough: [docs/reputation-staking-market.md](docs/reputation-staking-market.md). Devnet proof: `node scripts/reputation-market-proof.mjs`. Tests: [tests/reputation-staking.test.js](tests/reputation-staking.test.js) |
| On-chain skill licenses | [contracts/skill-license/](contracts/skill-license) `→ /api/skills/license-onchain` | In-repo | Anchor program: each purchased skill = a 1/1 SPL NFT + `SkillLicense` PDA, a trustless alternative to DB-backed access checks. Backend: [api/_lib/skill-license-onchain.js](api/_lib/skill-license-onchain.js) |
| Tokenized 3D (mint an avatar as an NFT) | [api/_lib/tokenize-3d.js](api/_lib/tokenize-3d.js) + [api/_lib/tokenize-3d-metadata.js](api/_lib/tokenize-3d-metadata.js), MCP tools [api/_mcp/tools/tokenize.js](api/_mcp/tools/tokenize.js) (`mint_3d_asset`, `get_3d_asset_onchain`), signed ledger provenance [api/_lib/asset-provenance.js](api/_lib/asset-provenance.js), launch directory [api/v1/tokenized/launches.js](api/v1/tokenized/launches.js) `→ GET /api/v1/tokenized/launches`, public gallery [pages/minted.html](pages/minted.html) + [src/minted.js](src/minted.js) `→ /minted` | In-repo | Mint a generated/owned GLB as a Metaplex Core NFT whose media is a live 3D viewer (GLB under `animation_url`), with baked provenance + enforced capped royalties (10%), idempotent, devnet-default. Every generated avatar AND every mint also appends an ERC-191-signed record to the `agent_actions` ledger (verifiable via `@three-ws/provenance-mcp`'s `query_action`). A mint naming `parent_mint` (a remix) routes the parent creator's royalty out of the mint fee as a real on-chain USDC transfer (mainnet, x402-collected calls only) — [api/_lib/remix-royalty.js](api/_lib/remix-royalty.js) split math, [api/_lib/remix-settlement.js](api/_lib/remix-settlement.js) payout wallet. Premium/token-gated generation: the Forge High tier (200k poly + PBR) is $THREE hold-or-pay gated — [api/forge.js](api/forge.js) `requireFeatureAccess('forge.high')` + [api/_lib/three-tier.js](api/_lib/three-tier.js) tier ladder, x402 pay-per-use or credits fallback; Draft/Standard stay free and ungated. Launch record: [tokenized_3d_assets](api/_lib/migrations/20260707120000_tokenized_3d_assets.sql) + [remix-royalty columns](api/_lib/migrations/20260708130000_tokenized_3d_remix_royalty.sql). Public gallery: `/minted` renders the launch directory live (model-viewer thumbnails, network toggle, royalty + remix badges) — the NFT counterpart of `/launches`. Docs: [docs/mcp.md](docs/mcp.md#mint_3d_asset). E2E: [scripts/tokenize-3d-devnet-e2e.mjs](scripts/tokenize-3d-devnet-e2e.mjs). Tests: [tests/tokenize-3d.test.js](tests/tokenize-3d.test.js), [tests/tokenize-3d-remix-royalty.test.js](tests/tokenize-3d-remix-royalty.test.js), [tests/asset-provenance.test.js](tests/asset-provenance.test.js) |
+| Generative 3D drops (supply-capped collections) | engine [api/_lib/drops.js](api/_lib/drops.js), store [api/_lib/drop-store.js](api/_lib/drop-store.js), routes [api/drops/[action].js](api/drops/%5Baction%5D.js) `→ /api/drops/{list,get,items,verify,create,publish,reveal}`, index [pages/drops.html](pages/drops.html) + [src/drops.js](src/drops.js) `→ /drops`, collection [pages/drop-collection.html](pages/drop-collection.html) + [src/drop-collection.js](src/drop-collection.js) `→ /drops/:slug`, styles [src/drops.css](src/drops.css) | In-repo | A drop stores its SPEC, not its art: every item's traits derive from (seed, index, layers) alone, so the whole supply is a pure function and a holder can recompute it. Creator gives a base style plus weighted trait layers; the roll is instant and free at any supply up to 10,000 because no art is generated at create time. Rarity is scored from the ACTUAL rolled distribution (sum of supply/occurrences per trait), ranked, and bucketed into the platform's common/rare/epic/legendary tiers. A published sha256 over the canonical spec is the commitment; the seed stays withheld until publish, which freezes the spec one-way. Art is forged per item on reveal through [api/forge.js](api/forge.js) (claim-then-poll, conditional UPDATE so a double click cannot start two jobs, stale claims self-release after 15 min), which is what keeps a 10k collection economically possible. Reveals inherit the universal animation retarget and the GLB/VRM/USDZ export path. Distinct from `/drop/:id` (the unrelated sealed wallet gift claim page); the routes are ordered so they cannot shadow each other. Schema: [drops + drop_items](api/_lib/migrations/20260901120000_generative_drops.sql). Docs: [docs/drops.md](docs/drops.md). Tests: [tests/drops-engine.test.js](tests/drops-engine.test.js) |
| Token-gated 3D embeds (holder-only interactive scenes) | Gate config + on-chain verify [api/_lib/embed-gate.js](api/_lib/embed-gate.js), access tokens [api/_lib/embed-gate-token.js](api/_lib/embed-gate-token.js), endpoints [api/embed/gate-create.js](api/embed/gate-create.js) + [api/embed/gate-verify.js](api/embed/gate-verify.js), gate-aware resolver [api/embed/resolve.js](api/embed/resolve.js), MCP tool [api/_mcp/tools/embed.js](api/_mcp/tools/embed.js) (`create_gated_embed`), widget [public/embed/v1.js](public/embed/v1.js) (`<three-d>`) + standalone host [public/embed/v1/gated.html](public/embed/v1/gated.html) `→ /embed/v1/gated` | In-repo | `create_gated_embed(asset_id, gate)` turns an avatar or on-chain agent you own into a holder-only interactive `<three-d>` embed — visitors must prove a real, server-verified SPL balance (SIWS challenge → nonce → signature → Solana RPC read, never a client-reported number) before the live scene renders; below the bar they see a designed locked teaser + connect-wallet CTA. `mint` defaults to $THREE but is a runtime parameter (coin-agnostic plumbing). Anti-abuse: short-lived signed access tokens (auto re-verify on expiry) + per-IP/per-wallet rate limits. Storage: [embed_gates + embed_gate_nonces](api/_lib/migrations/20260708120000_embed_gates.sql). Spec: [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md#token-gating). Docs: [docs/token-gated-3d-embeds.md](docs/token-gated-3d-embeds.md). Tests: [tests/embed-gate.test.js](tests/embed-gate.test.js) |
| Agent token plans (the coin an agent will become) | Rules + storage [api/_lib/agent-token-plan.js](api/_lib/agent-token-plan.js) (migration [api/_lib/migrations/20260811130000_agent_token_plans.sql](api/_lib/migrations/20260811130000_agent_token_plans.sql)), API actions `plan` + `plan-dry-run` in [api/agents/tokens/[action].js](api/agents/tokens/%5Baction%5D.js) `→ /api/agents/tokens/{plan,plan-dry-run}`, profile panel [src/agent-token-plan.js](src/agent-token-plan.js) on `/agents/:id` | In-repo · Live | The launch configuration bound to the agent record: one saved, editable plan per (agent, network) carrying the coin's name, ticker, story, artwork, pairing, buyback share and dev buy, with a derived readiness verdict and SOL cost estimate. Saving costs nothing and mints nothing. `plan-dry-run` is the free proof lane: it builds the SAME pump.fun create instructions the real launch builds from the SAME plan, compiles them against a real blockhash and simulates them on the cluster (devnet by default), never signing and never broadcasting, and separates `funding_required` from a genuinely broken plan. Both launch paths (`/api/agents/tokens/launch-confirm` from the owner's wallet, `/api/pump/launch-agent` from the agent's custodial wallet) call `markPlanLaunched` and write a `pump_agent_mints` row, which is also what finally puts user-wallet launches into `/launches` and the profile's launch history. Docs: [docs/agent-tokens.md](docs/agent-tokens.md). Tests: [tests/agent-token-plan.test.js](tests/agent-token-plan.test.js), [tests/agent-token-plan-api.test.js](tests/agent-token-plan-api.test.js), [tests/agent-token-plan-render.test.js](tests/agent-token-plan-render.test.js) |
| Agent token market data (what the coin looks like on the profile) | Cluster read [api/_lib/pump-curve-view.js](api/_lib/pump-curve-view.js) `→ GET /api/pump/curve` + `GET /api/v1/pump/curve`, view model [src/widgets/bonding-curve.js](src/widgets/bonding-curve.js) (`computeView`), normalization + widget [src/pump/coin-status-card.js](src/pump/coin-status-card.js) (`mapCoin` / `mapCurve` / `mountCoinStatus`), profile wiring [src/agent-detail.js](src/agent-detail.js) (token chip + launch history) | In-repo · Live | The live market half of an agent token. Two sources, one normalized shape: pump.fun's indexer (`/api/pump/coin`, mainnet, carries logo + 24h volume) and the bonding curve read straight off the cluster (`/api/pump/curve`), which is the ONLY source on devnet and the fallback whenever the indexer has not indexed a fresh mint or cannot be reached. A devnet coin renders in SOL and is badged `DEVNET` (devnet SOL has no dollar value) and links to the explorer instead of a pump.fun page that does not exist for that cluster, so the free rehearsal path renders exactly like a real launch. The curve gate accepts a pump.fun-ground `pump` suffix, a three.ws `3ws` mark, any plausible devnet address, and otherwise asks `pump_agent_mints` whether the mint is one of ours: a coin launched from a user's own wallet carries no mark and used to be refused with a cached `not_a_pump_mint` 404. Market cap is derived as price × supply because the SDK's `price.marketCap` goes negative on live curves. Free proof: [scripts/agent-token-market-proof.mjs](scripts/agent-token-market-proof.mjs) (reads only, signs nothing). Docs: [docs/agent-tokens.md](docs/agent-tokens.md). Tests: [tests/pump-curve-mint-gate.test.js](tests/pump-curve-mint-gate.test.js), [tests/agent-detail-launch-history.test.js](tests/agent-detail-launch-history.test.js), [src/pump/coin-status-card.curve.dom.test.js](src/pump/coin-status-card.curve.dom.test.js) |
diff --git a/api/_lib/drop-store.js b/api/_lib/drop-store.js
new file mode 100644
index 000000000..93c0da6f2
--- /dev/null
+++ b/api/_lib/drop-store.js
@@ -0,0 +1,389 @@
+// Generative 3D drops: persistence.
+//
+// The engine in ./drops.js is pure; this module is the only thing that talks to
+// Postgres about drops. It keeps two invariants the rest of the feature relies
+// on:
+//
+// 1. A drop and its full rolled supply are written together. A drop row with a
+// partial item set would serve a supply whose rarity ranks disagree with the
+// published provenance hash, so createDrop inserts every item in the same
+// transaction as the parent and fails as a unit.
+// 2. A reveal is claimed atomically. Two concurrent reveal requests for the
+// same index must not both start a paid generation job, so claimForReveal
+// is a conditional UPDATE that returns a row only to the caller that won.
+
+import { randomUUID } from 'node:crypto';
+import { sql, sqlValues } from './db.js';
+import { databaseConfigured } from './env.js';
+import {
+ assertSupply,
+ normalizeLayers,
+ provenanceHash,
+ rollSupply,
+ slugify,
+ traitDistribution,
+} from './drops.js';
+
+// Items are inserted in chunks so a 10k supply does not build one enormous
+// parameterized statement. 500 rows x 7 columns is 3500 placeholders, which is
+// comfortably inside Postgres's 65535 parameter ceiling with room to spare.
+const ITEM_INSERT_CHUNK = 500;
+
+export function dropsConfigured() {
+ return databaseConfigured();
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Create
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * Create a drop and materialize its entire rolled supply.
+ *
+ * @param {object} spec
+ * @returns {Promise<object>} the created drop, with its provenance hash
+ */
+export async function createDrop({
+ ownerId,
+ name,
+ symbol,
+ description,
+ style,
+ supply,
+ layers,
+ seed,
+ visibility = 'public',
+}) {
+ const size = assertSupply(supply);
+ const normalizedLayers = normalizeLayers(layers);
+ const rollSeed = String(seed || randomUUID()).slice(0, 64);
+ const hash = provenanceHash({ seed: rollSeed, supply: size, style, layers: normalizedLayers });
+
+ const slug = await uniqueSlug(name);
+ const items = rollSupply({ seed: rollSeed, supply: size, layers: normalizedLayers });
+
+ const [drop] = await sql`
+ insert into drops (owner_id, slug, name, symbol, description, style, supply, seed,
+ provenance_hash, layers, visibility)
+ values (${ownerId}, ${slug}, ${name}, ${symbol}, ${description || null}, ${style},
+ ${size}, ${rollSeed}, ${hash}, ${JSON.stringify(normalizedLayers)}, ${visibility})
+ returning *
+ `;
+
+ try {
+ for (let start = 0; start < items.length; start += ITEM_INSERT_CHUNK) {
+ const chunk = items.slice(start, start + ITEM_INSERT_CHUNK);
+ const rows = chunk.map((item) => [
+ drop.id,
+ item.index,
+ JSON.stringify(item.traits),
+ item.rarity_score,
+ item.rarity_rank,
+ item.rarity_tier,
+ ]);
+ await sql`
+ insert into drop_items (drop_id, idx, traits, rarity_score, rarity_rank, rarity_tier)
+ values ${sqlValues(rows)}
+ `;
+ }
+ } catch (err) {
+ // A drop whose supply is half-written is worse than no drop at all: it
+ // would serve rarity ranks that do not match its own provenance hash.
+ // Roll the parent back so the creator can simply retry.
+ await sql`delete from drops where id = ${drop.id}`.catch(() => {});
+ throw err;
+ }
+
+ return publicDrop(drop, { includeSeed: true });
+}
+
+async function uniqueSlug(name) {
+ const base = slugify(name) || 'drop';
+ for (let attempt = 0; attempt < 12; attempt++) {
+ const candidate = attempt === 0 ? base : `${base}-${attempt + 1}`.slice(0, 48);
+ const rows = await sql`select 1 from drops where slug = ${candidate} and deleted_at is null limit 1`;
+ if (rows.length === 0) return candidate;
+ }
+ return `${base.slice(0, 40)}-${randomUUID().slice(0, 6)}`;
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Read
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * Public drop index, newest first. Returns live and closed drops only: a draft
+ * has not published its seed, so its rarity claims are not yet checkable and it
+ * has no business on a public listing.
+ */
+export async function listDrops({ limit = 24, before = null, ownerId = null } = {}) {
+ const capped = Math.min(Math.max(Number(limit) || 24, 1), 60);
+ const rows = ownerId
+ ? await sql`
+ select d.*, ${revealedCountExpr} as revealed_count, ${mintedCountExpr} as minted_count
+ from drops d
+ where d.owner_id = ${ownerId} and d.deleted_at is null
+ and (${before}::timestamptz is null or d.created_at < ${before}::timestamptz)
+ order by d.created_at desc
+ limit ${capped}
+ `
+ : await sql`
+ select d.*, ${revealedCountExpr} as revealed_count, ${mintedCountExpr} as minted_count
+ from drops d
+ where d.deleted_at is null and d.visibility = 'public' and d.status in ('live', 'closed')
+ and (${before}::timestamptz is null or d.created_at < ${before}::timestamptz)
+ order by d.created_at desc
+ limit ${capped}
+ `;
+ return rows.map((row) => publicDrop(row));
+}
+
+// Correlated counts, so the index does not need a second round trip per drop.
+const revealedCountExpr = sql`(select count(*) from drop_items i where i.drop_id = d.id and i.status = 'revealed')`;
+const mintedCountExpr = sql`(select count(*) from drop_items i where i.drop_id = d.id and i.mint_address is not null)`;
+
+/** @returns {Promise<object|null>} */
+export async function getDropBySlug(slug, { viewerId = null } = {}) {
+ const rows = await sql`
+ select d.*, ${revealedCountExpr} as revealed_count, ${mintedCountExpr} as minted_count
+ from drops d
+ where d.slug = ${slug} and d.deleted_at is null
+ limit 1
+ `;
+ const row = rows[0];
+ if (!row) return null;
+ const isOwner = viewerId && row.owner_id === viewerId;
+ if (row.visibility === 'private' && !isOwner) return null;
+ // The seed is the commitment's other half. It is published the moment the
+ // drop goes live, and withheld from everyone but the creator before that.
+ return publicDrop(row, { includeSeed: row.status !== 'draft' || Boolean(isOwner), isOwner });
+}
+
+/** The internal row, seed and all. Never serve this straight to a client. */
+export async function getDropRow(dropId) {
+ const rows = await sql`select * from drops where id = ${dropId} and deleted_at is null limit 1`;
+ return rows[0] || null;
+}
+
+export async function listItems(dropId, { limit = 48, offset = 0, tier = null, status = null, sort = 'rank' } = {}) {
+ const capped = Math.min(Math.max(Number(limit) || 48, 1), 200);
+ const skip = Math.max(Number(offset) || 0, 0);
+ const order = sort === 'index' ? sql`i.idx asc` : sql`i.rarity_rank asc`;
+ const rows = await sql`
+ select * from drop_items i
+ where i.drop_id = ${dropId}
+ and (${tier}::text is null or i.rarity_tier = ${tier}::text)
+ and (${status}::text is null or i.status = ${status}::text)
+ order by ${order}
+ limit ${capped} offset ${skip}
+ `;
+ return rows.map(publicItem);
+}
+
+export async function countItems(dropId, { tier = null, status = null } = {}) {
+ const rows = await sql`
+ select count(*)::int as n from drop_items
+ where drop_id = ${dropId}
+ and (${tier}::text is null or rarity_tier = ${tier}::text)
+ and (${status}::text is null or status = ${status}::text)
+ `;
+ return rows[0]?.n || 0;
+}
+
+export async function getItem(dropId, idx) {
+ const rows = await sql`
+ select * from drop_items where drop_id = ${dropId} and idx = ${idx} limit 1
+ `;
+ return rows[0] ? publicItem(rows[0]) : null;
+}
+
+/** Per-layer trait frequency for the rarity panel, computed from the stored supply. */
+export async function itemDistribution(dropId, layers) {
+ const rows = await sql`select traits from drop_items where drop_id = ${dropId}`;
+ return traitDistribution(
+ rows.map((r) => ({ traits: parseJson(r.traits, []) })),
+ layers,
+ );
+}
+
+/** Counts by status and by tier in one round trip, for the supply meter. */
+export async function dropStats(dropId) {
+ const rows = await sql`
+ select status, rarity_tier, count(*)::int as n
+ from drop_items where drop_id = ${dropId}
+ group by status, rarity_tier
+ `;
+ const byStatus = { sealed: 0, revealing: 0, revealed: 0, failed: 0 };
+ const byTier = { common: 0, rare: 0, epic: 0, legendary: 0 };
+ for (const row of rows) {
+ byStatus[row.status] = (byStatus[row.status] || 0) + row.n;
+ byTier[row.rarity_tier] = (byTier[row.rarity_tier] || 0) + row.n;
+ }
+ return { by_status: byStatus, by_tier: byTier };
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Mutate
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * Freeze a draft and publish its seed.
+ *
+ * One-way on purpose. After this point the spec that the provenance hash
+ * commits to is the spec holders can check, so editing it would invalidate
+ * every claim the drop has already made.
+ */
+export async function publishDrop(dropId, ownerId) {
+ const rows = await sql`
+ update drops set status = 'live'
+ where id = ${dropId} and owner_id = ${ownerId} and status = 'draft' and deleted_at is null
+ returning *
+ `;
+ return rows[0] ? publicDrop(rows[0], { includeSeed: true, isOwner: true }) : null;
+}
+
+export async function closeDrop(dropId, ownerId) {
+ const rows = await sql`
+ update drops set status = 'closed'
+ where id = ${dropId} and owner_id = ${ownerId} and status = 'live' and deleted_at is null
+ returning *
+ `;
+ return rows[0] ? publicDrop(rows[0], { includeSeed: true, isOwner: true }) : null;
+}
+
+/**
+ * Claim one item for reveal.
+ *
+ * The conditional UPDATE is the lock: only a row still `sealed` (or a `failed`
+ * one being retried) transitions, and only one concurrent caller can win it, so
+ * a double-clicked reveal button cannot start two paid generation jobs for the
+ * same token.
+ *
+ * @returns {Promise<object|null>} the claimed item, or null if someone else won
+ */
+export async function claimForReveal(dropId, idx) {
+ const rows = await sql`
+ update drop_items
+ set status = 'revealing', reveal_attempts = reveal_attempts + 1, reveal_error = null
+ where drop_id = ${dropId} and idx = ${idx} and status in ('sealed', 'failed')
+ returning *
+ `;
+ return rows[0] ? publicItem(rows[0]) : null;
+}
+
+/** Record the forge job handle so a reveal survives a restart mid-generation. */
+export async function attachForgeJob(dropId, idx, jobId) {
+ await sql`
+ update drop_items set forge_job_id = ${jobId}
+ where drop_id = ${dropId} and idx = ${idx} and status = 'revealing'
+ `;
+}
+
+export async function markRevealed(dropId, idx, { glbUrl, thumbnailUrl = null, creationId = null, rigged = false }) {
+ const rows = await sql`
+ update drop_items
+ set status = 'revealed', glb_url = ${glbUrl}, thumbnail_url = ${thumbnailUrl},
+ creation_id = ${creationId}, rigged = ${Boolean(rigged)},
+ revealed_at = now(), reveal_error = null
+ where drop_id = ${dropId} and idx = ${idx}
+ returning *
+ `;
+ return rows[0] ? publicItem(rows[0]) : null;
+}
+
+export async function markRevealFailed(dropId, idx, message) {
+ const rows = await sql`
+ update drop_items
+ set status = 'failed', reveal_error = ${String(message || 'generation failed').slice(0, 500)}
+ where drop_id = ${dropId} and idx = ${idx}
+ returning *
+ `;
+ return rows[0] ? publicItem(rows[0]) : null;
+}
+
+/** Release a stuck claim so the item can be revealed again. */
+export async function releaseClaim(dropId, idx) {
+ await sql`
+ update drop_items set status = 'sealed'
+ where drop_id = ${dropId} and idx = ${idx} and status = 'revealing'
+ `;
+}
+
+export async function setCollectionAddress(dropId, ownerId, address) {
+ const rows = await sql`
+ update drops set collection_address = ${address}
+ where id = ${dropId} and owner_id = ${ownerId} and collection_address is null and deleted_at is null
+ returning *
+ `;
+ return rows[0] ? publicDrop(rows[0], { includeSeed: true, isOwner: true }) : null;
+}
+
+export async function markMinted(dropId, idx, { mintAddress, ownerWallet }) {
+ const rows = await sql`
+ update drop_items
+ set mint_address = ${mintAddress}, owner_wallet = ${ownerWallet}, minted_at = now()
+ where drop_id = ${dropId} and idx = ${idx} and mint_address is null
+ returning *
+ `;
+ return rows[0] ? publicItem(rows[0]) : null;
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Shapes
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * The client-facing drop shape. `seed` is present only when the caller is
+ * entitled to it, so a draft's commitment stays sealed until it goes live.
+ */
+export function publicDrop(row, { includeSeed = false, isOwner = false } = {}) {
+ return {
+ id: row.id,
+ slug: row.slug,
+ name: row.name,
+ symbol: row.symbol,
+ description: row.description,
+ style: row.style,
+ supply: row.supply,
+ status: row.status,
+ visibility: row.visibility,
+ provenance_hash: row.provenance_hash,
+ seed: includeSeed ? row.seed : null,
+ layers: parseJson(row.layers, []),
+ collection_address: row.collection_address,
+ cover_item_index: row.cover_item_index,
+ revealed_count: Number(row.revealed_count ?? 0),
+ minted_count: Number(row.minted_count ?? 0),
+ created_at: row.created_at,
+ is_owner: isOwner,
+ };
+}
+
+export function publicItem(row) {
+ return {
+ index: row.idx,
+ traits: parseJson(row.traits, []),
+ rarity_score: Number(row.rarity_score),
+ rarity_rank: row.rarity_rank,
+ rarity_tier: row.rarity_tier,
+ status: row.status,
+ glb_url: row.glb_url,
+ thumbnail_url: row.thumbnail_url,
+ rigged: row.rigged,
+ reveal_error: row.reveal_error,
+ mint_address: row.mint_address,
+ owner_wallet: row.owner_wallet,
+ revealed_at: row.revealed_at,
+ minted_at: row.minted_at,
+ };
+}
+
+function parseJson(value, fallback) {
+ if (value == null) return fallback;
+ if (typeof value === 'object') return value;
+ try {
+ return JSON.parse(value);
+ } catch {
+ return fallback;
+ }
+}
diff --git a/api/_lib/drops.js b/api/_lib/drops.js
new file mode 100644
index 000000000..7ffbcf0c7
--- /dev/null
+++ b/api/_lib/drops.js
@@ -0,0 +1,417 @@
+// Generative 3D drops: the deterministic trait + rarity engine.
+//
+// A "drop" is a supply-capped collection of 3D characters. The creator supplies
+// a base style and a set of trait layers with weighted options; this module
+// turns (seed, supply, layers) into the full rolled supply, with no randomness
+// that is not reproducible from those three inputs.
+//
+// Why deterministic matters here: the roll is the product. A holder has to be
+// able to prove their token was not re-rolled after the fact, and the platform
+// has to be able to regenerate any item's art months later without storing a
+// per-item random state. Both fall out of deriving every trait from
+// `draw(seed, locus)` in ./genome.js, which keys an independent PRNG stream per
+// locus. Independent streams also mean a creator can APPEND a trait layer to a
+// draft without perturbing the values already rolled on the existing layers.
+//
+// Art is deliberately NOT generated here. Rolling the supply is instant and
+// free; generating N rigged GLBs is neither. The roll happens at create time,
+// the art is forged at reveal time, one item at a time. That is both how real
+// drops behave and the only version of this whose economics work at 10k supply.
+
+import { createHash } from 'node:crypto';
+import { draw } from './genome.js';
+
+export const DROPS_VERSION = 1;
+
+// Supply ceiling. Above this the rarity pass (which is O(supply * layers)) stops
+// being something we are willing to run inside a request, and the reveal backlog
+// stops being something a single creator can realistically fund.
+export const MAX_SUPPLY = 10000;
+export const MIN_SUPPLY = 1;
+
+// A layer with more options than this is almost always a modelling mistake
+// (someone pasting a word list), and every extra option dilutes the rarity
+// signal that makes a collection legible.
+export const MAX_LAYERS = 12;
+export const MAX_OPTIONS_PER_LAYER = 64;
+
+// Rarity tiers, sharing the platform's cosmetics vocabulary (src/fits-lib.js)
+// so a drop item and a cosmetic read the same way everywhere they meet.
+// Cutoffs are percentile-from-the-top of the rarity-score ranking.
+export const RARITY_TIERS = [
+ { tier: 'legendary', maxPercentile: 0.01 },
+ { tier: 'epic', maxPercentile: 0.1 },
+ { tier: 'rare', maxPercentile: 0.35 },
+ { tier: 'common', maxPercentile: 1 },
+];
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Layer normalization
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * Validate and normalize creator-supplied trait layers.
+ *
+ * Throws on anything that would make a roll unreproducible or a collection
+ * nonsensical (duplicate layer keys, zero-weight layers, empty option sets).
+ * Weights are kept as supplied rather than normalized to probabilities, because
+ * the provenance hash commits to the exact numbers the creator published.
+ *
+ * @param {Array<object>} layers
+ * @returns {Array<{key:string,name:string,options:Array<{value:string,weight:number,prompt:string}>}>}
+ */
+export function normalizeLayers(layers) {
+ if (!Array.isArray(layers) || layers.length === 0) {
+ throw new DropSpecError('at least one trait layer is required');
+ }
+ if (layers.length > MAX_LAYERS) {
+ throw new DropSpecError(`at most ${MAX_LAYERS} trait layers (got ${layers.length})`);
+ }
+
+ const seenKeys = new Set();
+ const out = [];
+
+ for (const raw of layers) {
+ if (!raw || typeof raw !== 'object') {
+ throw new DropSpecError('each trait layer must be an object');
+ }
+ const name = String(raw.name ?? '').trim();
+ if (!name) throw new DropSpecError('each trait layer needs a name');
+ if (name.length > 40) throw new DropSpecError(`layer name "${name}" is longer than 40 characters`);
+
+ const key = slugify(raw.key ?? name);
+ if (!key) throw new DropSpecError(`layer "${name}" has no usable key`);
+ if (seenKeys.has(key)) throw new DropSpecError(`duplicate trait layer key "${key}"`);
+ seenKeys.add(key);
+
+ const options = normalizeOptions(raw.options, name);
+ out.push({ key, name, options });
+ }
+
+ return out;
+}
+
+function normalizeOptions(options, layerName) {
+ if (!Array.isArray(options) || options.length === 0) {
+ throw new DropSpecError(`layer "${layerName}" needs at least one option`);
+ }
+ if (options.length > MAX_OPTIONS_PER_LAYER) {
+ throw new DropSpecError(
+ `layer "${layerName}" has ${options.length} options (max ${MAX_OPTIONS_PER_LAYER})`,
+ );
+ }
+
+ const seenValues = new Set();
+ const out = [];
+
+ for (const raw of options) {
+ const isString = typeof raw === 'string';
+ const value = String((isString ? raw : raw?.value) ?? '').trim();
+ if (!value) throw new DropSpecError(`layer "${layerName}" has an option with no value`);
+ if (value.length > 60) {
+ throw new DropSpecError(`option "${value}" in layer "${layerName}" is longer than 60 characters`);
+ }
+ const lowered = value.toLowerCase();
+ if (seenValues.has(lowered)) {
+ throw new DropSpecError(`layer "${layerName}" repeats the option "${value}"`);
+ }
+ seenValues.add(lowered);
+
+ const weight = isString ? 1 : numberOr(raw?.weight, 1);
+ if (!(weight > 0) || !Number.isFinite(weight)) {
+ throw new DropSpecError(`option "${value}" in layer "${layerName}" needs a weight above zero`);
+ }
+
+ // An option may carry its own prompt fragment. When it does not, the
+ // value itself is the fragment, which is what makes a bare string list
+ // ("Gold", "Obsidian") a usable layer with no extra ceremony.
+ const prompt = String((isString ? '' : (raw?.prompt ?? '')) || value).trim().slice(0, 160);
+
+ out.push({ value, weight, prompt });
+ }
+
+ return out;
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Rolling
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * Roll one item's traits. Pure: same (seed, index, layers) always yields the
+ * same traits, on this machine and any other.
+ *
+ * Each layer draws from its own stream, keyed by the layer key rather than by
+ * position, so reordering the layer array does not change any result and
+ * appending a layer leaves existing layers untouched.
+ *
+ * @param {{seed:string,index:number,layers:Array<object>}} args
+ * @returns {{index:number,traits:Array<{layer:string,layer_name:string,value:string}>}}
+ */
+export function rollItem({ seed, index, layers }) {
+ const traits = [];
+ for (const layer of layers) {
+ const roll = draw(`${seed}#${index}`, layer.key);
+ traits.push({
+ layer: layer.key,
+ layer_name: layer.name,
+ value: pickWeighted(layer.options, roll).value,
+ });
+ }
+ return { index, traits };
+}
+
+/**
+ * Roll the entire supply and score it.
+ *
+ * Rarity is computed from the ACTUAL rolled distribution rather than from the
+ * declared weights. Those two diverge on every finite supply, and the honest
+ * number is the one a holder can recount from the published items.
+ *
+ * @param {{seed:string,supply:number,layers:Array<object>}} args
+ * @returns {Array<{index:number,traits:Array<object>,rarity_score:number,rarity_rank:number,rarity_tier:string}>}
+ */
+export function rollSupply({ seed, supply, layers }) {
+ const size = assertSupply(supply);
+ const normalized = Array.isArray(layers) && layers.length && layers[0]?.key
+ ? layers
+ : normalizeLayers(layers);
+
+ const items = [];
+ for (let i = 0; i < size; i++) items.push(rollItem({ seed, index: i, layers: normalized }));
+
+ return scoreRarity(items, size);
+}
+
+/**
+ * Attach statistical rarity to an already-rolled supply.
+ *
+ * Score is the sum over layers of (supply / occurrences of this item's value on
+ * that layer), the standard statistical-rarity formula: a value held by 1 of
+ * 1000 contributes 1000, one held by half the supply contributes 2. Summing
+ * rather than multiplying keeps a single ultra-rare trait from swamping every
+ * other signal in the collection.
+ *
+ * Ties are broken by index so the ranking is total and reproducible.
+ *
+ * @param {Array<{index:number,traits:Array<object>}>} items
+ * @param {number} [supply]
+ */
+export function scoreRarity(items, supply = items.length) {
+ const counts = new Map();
+ for (const item of items) {
+ for (const t of item.traits) {
+ const k = `${t.layer}${t.value}`;
+ counts.set(k, (counts.get(k) || 0) + 1);
+ }
+ }
+
+ const scored = items.map((item) => {
+ let score = 0;
+ for (const t of item.traits) {
+ const seen = counts.get(`${t.layer}${t.value}`) || 1;
+ score += supply / seen;
+ }
+ return { ...item, rarity_score: round4(score) };
+ });
+
+ const ordering = [...scored].sort(
+ (a, b) => b.rarity_score - a.rarity_score || a.index - b.index,
+ );
+
+ const rankByIndex = new Map();
+ ordering.forEach((item, i) => rankByIndex.set(item.index, i + 1));
+
+ return scored.map((item) => {
+ const rank = rankByIndex.get(item.index);
+ return { ...item, rarity_rank: rank, rarity_tier: tierForRank(rank, scored.length) };
+ });
+}
+
+/**
+ * The tier for a 1-based rank within a supply. Exported so the client can label
+ * a single item without re-scoring the whole collection.
+ */
+export function tierForRank(rank, supply) {
+ if (!(supply > 0)) return 'common';
+ const percentile = rank / supply;
+ for (const { tier, maxPercentile } of RARITY_TIERS) {
+ if (percentile <= maxPercentile) return tier;
+ }
+ return 'common';
+}
+
+/**
+ * Per-layer trait frequency table for the rarity panel on a drop page.
+ *
+ * @returns {Array<{layer:string,layer_name:string,values:Array<{value:string,count:number,share:number}>}>}
+ */
+export function traitDistribution(items, layers) {
+ const supply = items.length || 1;
+ const byLayer = new Map(layers.map((l) => [l.key, { layer: l.key, layer_name: l.name, counts: new Map() }]));
+
+ for (const item of items) {
+ for (const t of item.traits) {
+ const bucket = byLayer.get(t.layer);
+ if (!bucket) continue;
+ bucket.counts.set(t.value, (bucket.counts.get(t.value) || 0) + 1);
+ }
+ }
+
+ return [...byLayer.values()].map((bucket) => ({
+ layer: bucket.layer,
+ layer_name: bucket.layer_name,
+ values: [...bucket.counts.entries()]
+ .map(([value, count]) => ({ value, count, share: round4(count / supply) }))
+ .sort((a, b) => a.count - b.count || a.value.localeCompare(b.value)),
+ }));
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Provenance
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * The commitment a drop publishes before it reveals anything.
+ *
+ * Anyone holding (seed, supply, layers, style) can re-run rollSupply and check
+ * every item against what the drop served them. Publishing the hash at create
+ * time and the seed at reveal time is what makes "we did not re-roll the rares
+ * into our own wallet" a checkable claim instead of a promise.
+ *
+ * @param {{seed:string,supply:number,style:string,layers:Array<object>}} spec
+ * @returns {string} sha256 hex
+ */
+export function provenanceHash({ seed, supply, style, layers }) {
+ const canonical = canonicalize({
+ version: DROPS_VERSION,
+ seed: String(seed),
+ supply: Number(supply),
+ style: String(style || ''),
+ layers: layers.map((l) => ({
+ key: l.key,
+ name: l.name,
+ options: l.options.map((o) => ({ value: o.value, weight: o.weight, prompt: o.prompt })),
+ })),
+ });
+ return createHash('sha256').update(canonical).digest('hex');
+}
+
+/**
+ * Re-derive an item and confirm it matches what was served. Used by the public
+ * verify endpoint and by the reveal path, so a corrupted or tampered row can
+ * never be handed to a generator as if it were the rolled truth.
+ *
+ * @returns {{ok:boolean, expected:Array<object>, actual:Array<object>}}
+ */
+export function verifyItem({ seed, index, layers, traits }) {
+ const expected = rollItem({ seed, index, layers }).traits;
+ const actual = Array.isArray(traits) ? traits : [];
+ const ok =
+ expected.length === actual.length &&
+ expected.every((e, i) => actual[i]?.layer === e.layer && actual[i]?.value === e.value);
+ return { ok, expected, actual };
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Prompt composition
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * Compose the text-to-3D prompt for one item from the drop's base style and the
+ * item's rolled traits.
+ *
+ * The base style leads so every item in the collection shares a silhouette and
+ * finish; the traits follow in layer order so the same trait always lands in the
+ * same position of the prompt, which is what keeps a generator's output
+ * coherent across a supply instead of drifting item to item.
+ *
+ * @param {{style:string, traits:Array<{layer:string,value:string}>, layers:Array<object>}} args
+ * @returns {string}
+ */
+export function itemPrompt({ style, traits, layers }) {
+ const promptByPair = new Map();
+ for (const layer of layers) {
+ for (const option of layer.options) {
+ promptByPair.set(`${layer.key}${option.value}`, option.prompt);
+ }
+ }
+
+ const order = new Map(layers.map((l, i) => [l.key, i]));
+ const fragments = [...traits]
+ .sort((a, b) => (order.get(a.layer) ?? 0) - (order.get(b.layer) ?? 0))
+ .map((t) => promptByPair.get(`${t.layer}${t.value}`) || t.value)
+ .filter(Boolean);
+
+ const base = String(style || '').trim();
+ // A single humanoid, full body, T-pose-friendly: the generator hints that make
+ // the output riggable by src/glb-canonicalize.js instead of a bust or a scene.
+ const suffix = 'full body character, single subject, clean topology, neutral A-pose';
+ return [base, ...fragments, suffix].filter(Boolean).join(', ').slice(0, 900);
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Helpers
+ * ────────────────────────────────────────────────────────────────────────── */
+
+export class DropSpecError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = 'DropSpecError';
+ this.status = 400;
+ this.code = 'validation_error';
+ }
+}
+
+/**
+ * Pick an option by cumulative weight from a roll in [0,1).
+ * Exported for the tests that pin the weighting behaviour.
+ */
+export function pickWeighted(options, roll) {
+ let total = 0;
+ for (const o of options) total += o.weight;
+ // Clamp rather than trust: a roll of exactly 1 (impossible from draw, but
+ // reachable if a caller passes one in) must not fall off the end.
+ let target = Math.min(Math.max(roll, 0), 0.9999999) * total;
+ for (const o of options) {
+ target -= o.weight;
+ if (target < 0) return o;
+ }
+ return options[options.length - 1];
+}
+
+export function assertSupply(supply) {
+ const n = Number(supply);
+ if (!Number.isInteger(n) || n < MIN_SUPPLY || n > MAX_SUPPLY) {
+ throw new DropSpecError(`supply must be a whole number between ${MIN_SUPPLY} and ${MAX_SUPPLY}`);
+ }
+ return n;
+}
+
+export function slugify(value) {
+ return String(value ?? '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 48);
+}
+
+function numberOr(value, fallback) {
+ const n = Number(value);
+ return Number.isFinite(n) ? n : fallback;
+}
+
+function round4(x) {
+ return Math.round(x * 10000) / 10000;
+}
+
+// Deterministic JSON with recursively sorted keys, so the provenance hash does
+// not depend on the order the creator's client happened to serialize fields in.
+function canonicalize(value) {
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;
+ if (value && typeof value === 'object') {
+ const keys = Object.keys(value).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(value[k])}`).join(',')}}`;
+ }
+ return JSON.stringify(value);
+}
diff --git a/api/_lib/migrations/20260901120000_generative_drops.sql b/api/_lib/migrations/20260901120000_generative_drops.sql
new file mode 100644
index 000000000..da7a201da
--- /dev/null
+++ b/api/_lib/migrations/20260901120000_generative_drops.sql
@@ -0,0 +1,128 @@
+begin;
+
+-- Generative 3D drops: supply-capped collections of AI-forged, rigged
+-- characters.
+--
+-- A drop stores its SPEC, not its art. Every item's traits are re-derivable
+-- from (seed, index, layers) by api/_lib/drops.js, so the rows below are a
+-- materialized cache of a pure function plus the mutable reveal/mint state
+-- layered on top. That split is deliberate: it lets a holder recompute the
+-- whole supply from the published spec and check it against what we served,
+-- and it lets us re-forge a lost GLB years later without having stored a
+-- per-item random seed.
+
+create table if not exists drops (
+ id uuid primary key default gen_random_uuid(),
+ owner_id uuid not null references users(id) on delete cascade,
+ slug text not null,
+ name text not null,
+ -- Ticker-style short name shown on cards and carried into token metadata.
+ symbol text not null,
+ description text,
+ -- The base text-to-3D style every item in the supply shares. Item prompts
+ -- are this plus the item's rolled trait fragments (drops.itemPrompt).
+ style text not null,
+ supply integer not null,
+ -- The roll seed. Published once the drop goes live; before that it is the
+ -- one field that makes the provenance hash a commitment rather than a
+ -- description, so a draft's seed is never served.
+ seed text not null,
+ -- sha256 over (version, seed, supply, style, layers). Published at create
+ -- time; recomputable by anyone from the spec.
+ provenance_hash text not null,
+ -- Normalized trait layers: [{key, name, options:[{value, weight, prompt}]}]
+ layers jsonb not null,
+ -- draft: spec still editable, nothing revealed, seed withheld.
+ -- live: spec frozen, seed published, items revealable.
+ -- closed: no further reveals.
+ status text not null default 'draft',
+ visibility text not null default 'public',
+ cover_item_index integer,
+ -- Metaplex Core collection address once the drop is anchored on Solana.
+ -- Null until the creator mints the collection; items reference it on mint.
+ collection_address text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ deleted_at timestamptz,
+ constraint drops_status_chk check (status in ('draft', 'live', 'closed')),
+ constraint drops_visibility_chk check (visibility in ('private', 'unlisted', 'public')),
+ constraint drops_supply_chk check (supply between 1 and 10000),
+ constraint drops_slug_chk check (slug ~ '^[a-z0-9][a-z0-9-]{1,47}$')
+);
+
+create unique index if not exists drops_slug_uniq
+ on drops (slug) where deleted_at is null;
+create index if not exists drops_owner_idx
+ on drops (owner_id, created_at desc) where deleted_at is null;
+-- The /drops index: public, live collections, newest first.
+create index if not exists drops_public_idx
+ on drops (status, created_at desc)
+ where visibility = 'public' and deleted_at is null;
+
+create table if not exists drop_items (
+ id uuid primary key default gen_random_uuid(),
+ drop_id uuid not null references drops(id) on delete cascade,
+ -- Zero-based token index. The (seed, index) pair is the whole input to the
+ -- trait roll, so this column is part of the item's identity, not a display
+ -- ordinal.
+ idx integer not null,
+ traits jsonb not null,
+ rarity_score numeric(12, 4) not null,
+ rarity_rank integer not null,
+ rarity_tier text not null,
+ -- sealed: rolled, art not generated yet (the pre-reveal state)
+ -- revealing: a forge job is in flight
+ -- revealed: glb_url is populated and durable
+ -- failed: the forge lane gave up; retryable, see reveal_error
+ status text not null default 'sealed',
+ -- Forge job handle and the forge_creations row it materialized into, so a
+ -- reveal can be resumed after a restart instead of paying to generate twice.
+ forge_job_id text,
+ creation_id uuid,
+ glb_url text,
+ thumbnail_url text,
+ rigged boolean not null default false,
+ reveal_error text,
+ reveal_attempts integer not null default 0,
+ revealed_at timestamptz,
+ -- Metaplex Core asset address and the wallet holding it, once minted.
+ mint_address text,
+ owner_wallet text,
+ minted_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint drop_items_status_chk
+ check (status in ('sealed', 'revealing', 'revealed', 'failed')),
+ constraint drop_items_tier_chk
+ check (rarity_tier in ('common', 'rare', 'epic', 'legendary'))
+);
+
+create unique index if not exists drop_items_drop_idx_uniq
+ on drop_items (drop_id, idx);
+-- The default grid order on a drop page, and the rarity leaderboard.
+create index if not exists drop_items_rank_idx
+ on drop_items (drop_id, rarity_rank);
+-- "What is still sealed" for the reveal queue, and "what is revealed" for the
+-- gallery, both without scanning the whole supply.
+create index if not exists drop_items_status_idx
+ on drop_items (drop_id, status);
+create index if not exists drop_items_mint_idx
+ on drop_items (mint_address) where mint_address is not null;
+
+-- Reuse the shared updated_at trigger the rest of the schema is on, so these
+-- rows age the same way every other table's do.
+do $$
+begin
+ if exists (select 1 from pg_proc where proname = 'set_updated_at') then
+ if not exists (select 1 from pg_trigger where tgname = 'drops_set_updated_at') then
+ create trigger drops_set_updated_at before update on drops
+ for each row execute function set_updated_at();
+ end if;
+ if not exists (select 1 from pg_trigger where tgname = 'drop_items_set_updated_at') then
+ create trigger drop_items_set_updated_at before update on drop_items
+ for each row execute function set_updated_at();
+ end if;
+ end if;
+end $$;
+
+commit;
diff --git a/api/drops/[action].js b/api/drops/[action].js
new file mode 100644
index 000000000..d2d84b3f0
--- /dev/null
+++ b/api/drops/[action].js
@@ -0,0 +1,468 @@
+// api/drops/[action]: generative 3D drops.
+//
+// GET /api/drops/list?limit=&before=&mine=1
+// GET /api/drops/get?slug=<slug>
+// GET /api/drops/items?slug=<slug>&limit=&offset=&tier=&status=&sort=
+// GET /api/drops/verify?slug=<slug>&index=
+// POST /api/drops/create { name, symbol, style, supply, layers[], description?, seed?, visibility? }
+// POST /api/drops/publish { slug }
+// POST /api/drops/reveal { slug, index }
+// GET /api/drops/reveal?slug=<slug>&index=<n> (poll an in-flight reveal)
+//
+// The split that shapes this file: rolling a supply is pure and instant, so
+// create does the whole collection in one request. Forging the art is neither,
+// so reveal is a claim-then-poll job per item and never blocks a request on a
+// GPU. See api/_lib/drops.js for the engine and api/_lib/drop-store.js for the
+// persistence invariants.
+
+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { authenticateBearer, extractBearer, getSessionUser, hasScope } from '../_lib/auth.js';
+import { originFromReq, startForge } from '../_mcp-studio/forge-client.js';
+import {
+ DropSpecError,
+ itemPrompt,
+ normalizeLayers,
+ provenanceHash,
+ verifyItem,
+} from '../_lib/drops.js';
+import {
+ attachForgeJob,
+ claimForReveal,
+ countItems,
+ createDrop,
+ dropStats,
+ dropsConfigured,
+ getDropBySlug,
+ getItem,
+ itemDistribution,
+ listDrops,
+ listItems,
+ markRevealFailed,
+ markRevealed,
+ publishDrop,
+ releaseClaim,
+} from '../_lib/drop-store.js';
+
+// A reveal that has been claimed but whose forge job never came back leaves the
+// row in `revealing` forever. Any poll arriving after this window releases the
+// claim so the item can be revealed again, which is the self-healing the
+// alternative (a cron just for stuck drops) would otherwise need.
+const REVEAL_STALL_MS = 15 * 60 * 1000;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (!dropsConfigured()) {
+ return error(res, 503, 'not_configured', 'drops need a database; none is configured here');
+ }
+
+ const action = actionOf(req);
+ try {
+ switch (action) {
+ case 'list':
+ return await handleList(req, res);
+ case 'get':
+ return await handleGet(req, res);
+ case 'items':
+ return await handleItems(req, res);
+ case 'verify':
+ return await handleVerify(req, res);
+ case 'create':
+ return await handleCreate(req, res);
+ case 'publish':
+ return await handlePublish(req, res);
+ case 'reveal':
+ return req.method === 'POST' ? await handleReveal(req, res) : await handleRevealStatus(req, res);
+ default:
+ return error(res, 404, 'not_found', `unknown drops action "${action}"`);
+ }
+ } catch (err) {
+ if (err instanceof DropSpecError) return error(res, 400, err.code, err.message);
+ throw err;
+ }
+});
+
+function actionOf(req) {
+ const fromQuery = req.query?.action;
+ if (fromQuery && fromQuery !== '[action]') return String(fromQuery).toLowerCase();
+ return (new URL(req.url, 'http://x').pathname.split('/').pop() || '').toLowerCase();
+}
+
+function queryOf(req) {
+ return new URL(req.url, 'http://x').searchParams;
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Reads
+ * ────────────────────────────────────────────────────────────────────────── */
+
+async function handleList(req, res) {
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests; slow down');
+
+ const q = queryOf(req);
+ const mine = q.get('mine') === '1';
+ let ownerId = null;
+ if (mine) {
+ const auth = await resolveAuth(req, 'avatars:read');
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to list your own drops');
+ ownerId = auth.userId;
+ }
+
+ const drops = await listDrops({
+ limit: Number(q.get('limit')) || 24,
+ before: q.get('before') || null,
+ ownerId,
+ });
+ return json(res, 200, { drops, next: drops.length ? drops[drops.length - 1].created_at : null });
+}
+
+async function handleGet(req, res) {
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests; slow down');
+
+ const viewer = await resolveAuth(req, 'avatars:read');
+ const drop = await loadDrop(req, viewer?.userId || null);
+ if (!drop) return error(res, 404, 'not_found', 'no such drop');
+
+ const [stats, distribution, preview] = await Promise.all([
+ dropStats(drop.id),
+ itemDistribution(drop.id, drop.layers),
+ listItems(drop.id, { limit: 24, sort: 'rank' }),
+ ]);
+
+ return json(res, 200, { drop, stats, distribution, items: preview });
+}
+
+async function handleItems(req, res) {
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests; slow down');
+
+ const viewer = await resolveAuth(req, 'avatars:read');
+ const drop = await loadDrop(req, viewer?.userId || null);
+ if (!drop) return error(res, 404, 'not_found', 'no such drop');
+
+ const q = queryOf(req);
+ const tier = normalizeEnum(q.get('tier'), ['common', 'rare', 'epic', 'legendary']);
+ const status = normalizeEnum(q.get('status'), ['sealed', 'revealing', 'revealed', 'failed']);
+ const offset = Math.max(Number(q.get('offset')) || 0, 0);
+ const limit = Number(q.get('limit')) || 48;
+
+ const [items, total] = await Promise.all([
+ listItems(drop.id, { limit, offset, tier, status, sort: q.get('sort') === 'index' ? 'index' : 'rank' }),
+ countItems(drop.id, { tier, status }),
+ ]);
+
+ return json(res, 200, { items, total, offset, limit: items.length });
+}
+
+/**
+ * Recompute the published commitment, and optionally one item's traits, from
+ * the drop's own spec. This is the endpoint that makes "the roll was not
+ * rigged" checkable rather than asserted: it re-derives the hash from the
+ * stored layers and re-rolls the requested index through the same pure
+ * function a third party would.
+ */
+async function handleVerify(req, res) {
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests; slow down');
+
+ const viewer = await resolveAuth(req, 'avatars:read');
+ const drop = await loadDrop(req, viewer?.userId || null);
+ if (!drop) return error(res, 404, 'not_found', 'no such drop');
+ if (!drop.seed) {
+ return error(res, 409, 'not_revealed', 'this drop has not published its seed yet');
+ }
+
+ const layers = normalizeLayers(drop.layers);
+ const recomputed = provenanceHash({
+ seed: drop.seed,
+ supply: drop.supply,
+ style: drop.style,
+ layers,
+ });
+
+ const body = {
+ slug: drop.slug,
+ seed: drop.seed,
+ supply: drop.supply,
+ published_hash: drop.provenance_hash,
+ recomputed_hash: recomputed,
+ hash_matches: recomputed === drop.provenance_hash,
+ };
+
+ const rawIndex = queryOf(req).get('index');
+ if (rawIndex !== null && rawIndex !== '') {
+ const index = Number(rawIndex);
+ if (!Number.isInteger(index) || index < 0 || index >= drop.supply) {
+ return error(res, 400, 'validation_error', `index must be between 0 and ${drop.supply - 1}`);
+ }
+ const stored = await getItem(drop.id, index);
+ if (!stored) return error(res, 404, 'not_found', 'no such item');
+ const check = verifyItem({ seed: drop.seed, index, layers, traits: stored.traits });
+ body.item = {
+ index,
+ served_traits: stored.traits,
+ recomputed_traits: check.expected,
+ traits_match: check.ok,
+ };
+ }
+
+ return json(res, 200, body);
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Writes
+ * ────────────────────────────────────────────────────────────────────────── */
+
+async function handleCreate(req, res) {
+ if (!method(req, res, ['POST'])) return;
+ const auth = await resolveAuth(req, 'avatars:write');
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to create a drop');
+
+ const rl = await limits.agentCreateIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many drops created; slow down');
+
+ const body = await readJson(req);
+ const name = String(body?.name ?? '').trim();
+ const symbol = String(body?.symbol ?? '').trim().toUpperCase();
+ const style = String(body?.style ?? '').trim();
+
+ if (name.length < 2 || name.length > 60) {
+ return error(res, 400, 'validation_error', 'name must be 2 to 60 characters');
+ }
+ if (!/^[A-Z0-9]{2,10}$/.test(symbol)) {
+ return error(res, 400, 'validation_error', 'symbol must be 2 to 10 letters or digits');
+ }
+ if (style.length < 3 || style.length > 400) {
+ return error(res, 400, 'validation_error', 'style must be 3 to 400 characters');
+ }
+ const visibility = normalizeEnum(body?.visibility, ['public', 'unlisted', 'private']) || 'public';
+
+ const drop = await createDrop({
+ ownerId: auth.userId,
+ name,
+ symbol,
+ description: String(body?.description ?? '').trim().slice(0, 2000) || null,
+ style,
+ supply: body?.supply,
+ layers: body?.layers,
+ seed: typeof body?.seed === 'string' ? body.seed.trim() : null,
+ visibility,
+ });
+
+ return json(res, 201, { drop });
+}
+
+async function handlePublish(req, res) {
+ if (!method(req, res, ['POST'])) return;
+ const auth = await resolveAuth(req, 'avatars:write');
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to publish a drop');
+
+ const body = await readJson(req);
+ const slug = String(body?.slug ?? '').trim();
+ const existing = await getDropBySlug(slug, { viewerId: auth.userId });
+ if (!existing) return error(res, 404, 'not_found', 'no such drop');
+ if (!existing.is_owner) return error(res, 403, 'forbidden', 'only the creator can publish this drop');
+
+ const drop = await publishDrop(existing.id, auth.userId);
+ if (!drop) {
+ return error(res, 409, 'already_published', 'this drop has already been published');
+ }
+ return json(res, 200, { drop });
+}
+
+/**
+ * Start the reveal of one item.
+ *
+ * Claiming happens before any generation is started, and the claim is a
+ * conditional UPDATE, so two concurrent reveals of the same index cannot both
+ * reach the forge. If the submit then fails we hand the claim straight back
+ * rather than leaving the item stuck in `revealing`.
+ */
+async function handleReveal(req, res) {
+ const auth = await resolveAuth(req, 'avatars:write');
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to reveal an item');
+
+ const rl = await limits.mcp3dGenerateFree(`drop-reveal:${auth.userId}`);
+ if (!rl.success) {
+ return error(res, 429, 'rate_limited', 'reveal limit reached; try again shortly');
+ }
+
+ const body = await readJson(req);
+ const { drop, index, failure } = await resolveTarget(body?.slug, body?.index, auth.userId);
+ if (failure) return error(res, failure.status, failure.code, failure.message);
+
+ if (drop.status === 'draft') {
+ return error(res, 409, 'not_published', 'publish the drop before revealing items');
+ }
+
+ const claimed = await claimForReveal(drop.id, index);
+ if (!claimed) {
+ const current = await getItem(drop.id, index);
+ if (current?.status === 'revealed') return json(res, 200, { item: current, already: true });
+ return error(res, 409, 'already_revealing', 'this item is already being revealed');
+ }
+
+ const layers = normalizeLayers(drop.layers);
+ const prompt = itemPrompt({ style: drop.style, traits: claimed.traits, layers });
+
+ let job;
+ try {
+ job = await startForge(originFromReq(req), {
+ prompt,
+ tier: 'standard',
+ // One client key per drop keeps a collection's generations attributable
+ // to the drop rather than to whichever visitor happened to trigger them.
+ clientKey: `drop-${drop.id}`,
+ });
+ } catch (err) {
+ await markRevealFailed(drop.id, index, err?.message || 'the 3D generator refused the job');
+ return error(res, 502, err?.code || 'provider_error', err?.message || 'could not start generation');
+ }
+
+ if (job.status === 'done' && job.glb_url) {
+ const item = await markRevealed(drop.id, index, {
+ glbUrl: job.glb_url,
+ thumbnailUrl: job.preview_image_url || null,
+ creationId: job.creation_id || null,
+ });
+ return json(res, 200, { item, prompt });
+ }
+
+ await attachForgeJob(drop.id, index, job.job_id);
+ return json(res, 202, {
+ item: { ...claimed, status: 'revealing' },
+ job_id: job.job_id,
+ prompt,
+ poll: `/api/drops/reveal?slug=${encodeURIComponent(drop.slug)}&index=${index}`,
+ });
+}
+
+/**
+ * Poll an in-flight reveal. One upstream check per call, never a blocking loop,
+ * so this stays a cheap endpoint a grid of sealed cards can hit.
+ */
+async function handleRevealStatus(req, res) {
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests; slow down');
+
+ const q = queryOf(req);
+ const viewer = await resolveAuth(req, 'avatars:read');
+ const { drop, index, failure } = await resolveTarget(q.get('slug'), q.get('index'), viewer?.userId || null);
+ if (failure) return error(res, failure.status, failure.code, failure.message);
+
+ const item = await getItem(drop.id, index);
+ if (!item) return error(res, 404, 'not_found', 'no such item');
+ if (item.status !== 'revealing') return json(res, 200, { item });
+
+ const claim = await revealClaimRow(drop.id, index);
+ if (!claim?.forge_job_id) {
+ await releaseClaim(drop.id, index);
+ return json(res, 200, { item: { ...item, status: 'sealed' } });
+ }
+ const jobId = claim.forge_job_id;
+
+ let data;
+ try {
+ const upstream = await fetch(
+ `${originFromReq(req)}/api/forge?job=${encodeURIComponent(jobId)}`,
+ { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(15_000) },
+ );
+ data = await upstream.json().catch(() => ({}));
+ } catch {
+ // A transient poll failure is not a failed generation. Report the item as
+ // still revealing and let the client come back.
+ return json(res, 200, { item, pending: true });
+ }
+
+ if (data?.status === 'done' && data.glb_url) {
+ const revealed = await markRevealed(drop.id, index, {
+ glbUrl: data.glb_url,
+ thumbnailUrl: data.preview_image_url || null,
+ creationId: data.creation_id || null,
+ });
+ return json(res, 200, { item: revealed });
+ }
+
+ if (data?.status === 'failed' || data?.status === 'error') {
+ const failed = await markRevealFailed(drop.id, index, data.error || 'generation failed');
+ return json(res, 200, { item: failed });
+ }
+
+ // Stuck claims self-heal rather than needing a dedicated sweeper cron.
+ if (isStalled(claim.updated_at)) {
+ await releaseClaim(drop.id, index);
+ return json(res, 200, { item: { ...item, status: 'sealed' } });
+ }
+
+ return json(res, 200, { item, pending: true });
+}
+
+function isStalled(updatedAt) {
+ const started = updatedAt ? Date.parse(updatedAt) : NaN;
+ return Number.isFinite(started) && Date.now() - started > REVEAL_STALL_MS;
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Shared resolution
+ * ────────────────────────────────────────────────────────────────────────── */
+
+async function loadDrop(req, viewerId) {
+ const slug = queryOf(req).get('slug');
+ if (!slug) return null;
+ return getDropBySlug(String(slug).trim(), { viewerId });
+}
+
+async function resolveTarget(rawSlug, rawIndex, viewerId) {
+ const slug = String(rawSlug ?? '').trim();
+ if (!slug) {
+ return { failure: { status: 400, code: 'validation_error', message: 'slug is required' } };
+ }
+ const drop = await getDropBySlug(slug, { viewerId });
+ if (!drop) {
+ return { failure: { status: 404, code: 'not_found', message: 'no such drop' } };
+ }
+ const index = Number(rawIndex);
+ if (!Number.isInteger(index) || index < 0 || index >= drop.supply) {
+ return {
+ failure: {
+ status: 400,
+ code: 'validation_error',
+ message: `index must be a whole number between 0 and ${drop.supply - 1}`,
+ },
+ };
+ }
+ return { drop, index };
+}
+
+// The forge handle and the claim's age live on the item row; publicItem
+// deliberately omits both (a job id is an internal handle, not collection
+// metadata), so the poll path reads them directly.
+async function revealClaimRow(dropId, index) {
+ const rows = await sql`
+ select forge_job_id, updated_at from drop_items where drop_id = ${dropId} and idx = ${index} limit 1
+ `;
+ return rows[0] || null;
+}
+
+function normalizeEnum(value, allowed) {
+ const v = String(value ?? '').trim().toLowerCase();
+ return allowed.includes(v) ? v : null;
+}
+
+async function resolveAuth(req, requiredScope) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, source: 'session' };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (!bearer) return null;
+ if (!hasScope(bearer.scope, requiredScope)) return null;
+ return bearer;
+}
diff --git a/data/changelog.json b/data/changelog.json
index cc5c78da9..f2a6a555c 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-09-01",
+ "title": "Launch a 3D collection without a studio",
+ "summary": "3D Drops is live. Give it a base style and a few trait layers with weights, and it rolls a whole supply-capped collection in one go: up to 10,000 unique characters, each one a real rigged, animation-ready model rather than a flat picture. The roll is instant and free at any size because the art is generated per item when you reveal it, not rendered in bulk up front. Rarity is computed from the supply that actually came out, ranked, and sorted into common, rare, epic and legendary. Every collection publishes a fingerprint of its own recipe and, once launched, the seed behind it, so anyone can recompute the entire supply and check it against what the site served them. There is a Verify button on every collection page that does exactly that.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/drops"
+ },
{
"date": "2026-08-29",
"title": "Your agent on the Android home screen",
diff --git a/data/pages.json b/data/pages.json
index ac084e524..d2ea6d592 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1343,6 +1343,14 @@
"changefreq": "daily",
"added": "2026-06-12"
},
+ {
+ "path": "/drops",
+ "title": "3D Drops",
+ "description": "Launch a supply-capped collection of AI-forged 3D characters. Pick a style, define weighted trait layers, and three.ws rolls the whole supply from a published seed: verifiable rarity, rigged animation-ready art, forged on reveal.",
+ "priority": 0.8,
+ "changefreq": "daily",
+ "added": "2026-09-01"
+ },
{
"path": "/minted",
"title": "Minted 3D Assets",
@@ -2816,6 +2824,14 @@
"changefreq": "monthly",
"added": "2026-07-19"
},
+ {
+ "path": "/docs/drops",
+ "title": "3D Drops",
+ "description": "How generative 3D collections work on three.ws: weighted trait layers, a supply rolled from a published seed, rarity scored from the actual distribution, art forged per item on reveal, and a verify endpoint anyone can recompute the roll with.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-09-01"
+ },
{
"path": "/docs/forge",
"title": "Docs · Forge (text & image to 3D)",
diff --git a/docs/drops.md b/docs/drops.md
new file mode 100644
index 000000000..b26245ab7
--- /dev/null
+++ b/docs/drops.md
@@ -0,0 +1,206 @@
+# 3D Drops: generative collections of rigged characters
+
+[three.ws/drops](https://three.ws/drops) is the collection launcher. You give it
+a base style and a set of weighted trait layers; it rolls a supply-capped
+collection where every item is a real, rigged, animation-ready 3D character, its
+rarity is recomputable by anyone holding the spec, and its art is forged on
+reveal instead of bulk-rendered up front.
+
+The reference points are the 3D PFP collections: a studio hand-models a base
+mesh plus dozens of trait meshes, a compositor assembles ten thousand
+combinations, and the whole thing takes a year and a half. This is that product
+without the studio. The part that was expensive (making the art) is a generation
+job; the part that was hand-waved (proving the roll was fair) is a published
+commitment anyone can check.
+
+Related surfaces: [Minted 3D Assets](minted.md) for one-off Metaplex Core mints,
+[the Forge](forge.md) for the text-to-3D pipeline every reveal runs on, and
+[the avatar gallery](../public/gallery/index.html) at `/gallery` for individual
+avatars.
+
+## The idea in one paragraph
+
+A drop stores its **spec**, not its art. Every item's traits come from three
+inputs and nothing else: the drop's `seed`, the item's `index`, and the trait
+layers. That makes the whole supply a pure function, which buys two things. A
+holder can recompute the entire collection from the published spec and check it
+against what the site served them, so "we did not re-roll the rares into our own
+wallet" becomes a checkable claim rather than a promise. And the platform can
+re-forge a lost model years later without ever having stored a per-item random
+state.
+
+## Launching a collection
+
+Open [/drops](https://three.ws/drops), sign in, and press **Launch a
+collection**. You supply:
+
+- **Name and symbol.** The symbol is 2 to 10 letters or digits, shown on cards.
+- **Supply.** Up to 10,000. The roll is instant and free at any size, because no
+ art is generated at this step.
+- **Base style.** The look every item shares, for example
+ `stylized matte-clay guardian creature, soft rim light, chunky proportions`.
+- **Trait layers.** Each layer (Species, Outfit, Aura) has options with relative
+ weights. The builder shows each option's resulting share as you type. An
+ option can carry its own prompt fragment when the trait's display name is not
+ what you want fed to the generator: the value `Bomber jacket` can generate
+ from `wearing a worn leather bomber jacket`.
+
+Submitting rolls the supply and lands you on the collection page. The drop
+starts as a **draft**: its seed is withheld, so the provenance hash it publishes
+is a commitment rather than a description. Pressing **Publish** freezes the spec
+and reveals the seed. That is one-way, on purpose: after the seed is out,
+editing the spec would invalidate every rarity claim the collection has already
+made.
+
+### From an agent or a script
+
+```bash
+curl -X POST https://three.ws/api/drops/create \
+ -H 'content-type: application/json' \
+ -H 'authorization: Bearer <token with avatars:write>' \
+ -d '{
+ "name": "Clay Wardens",
+ "symbol": "WARDEN",
+ "style": "stylized matte-clay guardian creature, soft rim light",
+ "supply": 250,
+ "layers": [
+ {"name": "Species", "options": [
+ {"value": "Fox", "weight": 60},
+ {"value": "Wolf", "weight": 30},
+ {"value": "Dragon", "weight": 10}
+ ]},
+ {"name": "Outfit", "options": [
+ {"value": "Bomber jacket", "weight": 50, "prompt": "wearing a worn leather bomber jacket"},
+ {"value": "Lab coat", "weight": 50}
+ ]},
+ {"name": "Aura", "options": ["None", "Ember", "Frost"]}
+ ]
+ }'
+```
+
+A layer's options may be bare strings, in which case each weighs 1 and its value
+doubles as its prompt fragment. The response carries the `slug`, the
+`provenance_hash`, and (for the creator) the `seed`.
+
+## How rarity is computed
+
+Rarity is scored from the **actual rolled distribution**, not from the declared
+weights. Those two always diverge on a finite supply, and the honest number is
+the one a holder can recount from the published items.
+
+Each item's score is the sum over its traits of `supply / (how many items share
+that trait value)`. A value held by 1 item in 1000 contributes 1000; one held by
+half the supply contributes 2. Summing rather than multiplying keeps a single
+ultra-rare trait from swamping every other signal in the collection.
+
+Items are then ranked (ties broken by index, so the ordering is total and
+reproducible) and bucketed into the same four tiers the rest of the platform
+uses for cosmetics:
+
+| Tier | Top percentile of the ranking |
+|---|---|
+| `legendary` | 1% |
+| `epic` | 10% |
+| `rare` | 35% |
+| `common` | the rest |
+
+## Reveal: art is forged per item
+
+A freshly rolled item is **sealed**. Its traits are already public and its rank
+is already fixed; only the art is unforged. Pressing **Reveal** on the collection
+page composes the item's prompt (the base style, then each rolled trait's prompt
+fragment in layer order, then the hints that keep the output riggable) and
+submits it to [the Forge](forge.md). The page then polls until the GLB lands.
+
+Ordering the fragments by layer is what holds a collection together visually: a
+given trait always occupies the same position in the prompt, so the generator's
+output stays coherent across the supply instead of drifting item to item.
+
+Reveal states are `sealed`, `revealing`, `revealed`, and `failed`. A failed
+reveal keeps its error and is retryable from the same button. Claiming an item
+for reveal is a conditional database update, so a double-clicked button cannot
+start two paid generation jobs for the same token, and a claim that never comes
+back is released automatically after fifteen minutes rather than needing a
+sweeper cron.
+
+Because every item is generated as a full-body character in a neutral A-pose, it
+inherits the platform's universal animation retarget: any revealed item drives
+the pre-baked clip library through
+[`src/glb-canonicalize.js`](../src/glb-canonicalize.js), and can be exported as
+GLB, VRM 1.0, or USDZ through [`src/avatar-export.js`](../src/avatar-export.js).
+
+## Verifying a roll
+
+The **Verify this roll** button on every collection page calls:
+
+```bash
+curl "https://three.ws/api/drops/verify?slug=clay-wardens&index=7"
+```
+
+The response re-derives the provenance hash from the stored spec and, when an
+`index` is given, re-rolls that item through the same pure function a third
+party would:
+
+```json
+{
+ "slug": "clay-wardens",
+ "seed": "ff65b26d-d3c5-4a1b-90ed-82c132b7bd7d",
+ "supply": 120,
+ "published_hash": "94c97a50...",
+ "recomputed_hash": "94c97a50...",
+ "hash_matches": true,
+ "item": {
+ "index": 7,
+ "served_traits": [{"layer": "species", "value": "Dragon"}],
+ "recomputed_traits": [{"layer": "species", "value": "Dragon"}],
+ "traits_match": true
+ }
+}
+```
+
+You do not have to trust the endpoint. The hash is a sha256 over the canonical
+JSON of `{version, seed, supply, style, layers}` with keys sorted recursively,
+and each trait is a weighted pick against `draw(seed + "#" + index, layerKey)`
+from [`api/_lib/genome.js`](../api/_lib/genome.js). Both are reimplementable in
+any language from [`api/_lib/drops.js`](../api/_lib/drops.js).
+
+One consequence worth knowing: because each layer draws from its own stream
+keyed by the layer's slug, adding a layer to a draft does not perturb the values
+already rolled on the layers beside it, and reordering the layer array changes
+nothing at all.
+
+## API reference
+
+All routes live under `/api/drops/`. Reads are public and rate-limited by IP;
+writes need a session cookie or a bearer token with `avatars:write`.
+
+| Method | Route | What it does |
+|---|---|---|
+| `GET` | `/api/drops/list?limit=&before=&mine=1` | Public collections, newest first. `mine=1` lists your own, drafts included. |
+| `GET` | `/api/drops/get?slug=` | One collection with its stats, trait distribution, and first page of items. |
+| `GET` | `/api/drops/items?slug=&limit=&offset=&tier=&status=&sort=` | Paginated items. `sort` is `rank` (default) or `index`. |
+| `GET` | `/api/drops/verify?slug=&index=` | Recompute the provenance hash, and optionally one item's traits. |
+| `POST` | `/api/drops/create` | Roll a new collection. Body as shown above. |
+| `POST` | `/api/drops/publish` | Freeze a draft and publish its seed. Body `{slug}`. |
+| `POST` | `/api/drops/reveal` | Start one item's generation. Body `{slug, index}`. |
+| `GET` | `/api/drops/reveal?slug=&index=` | Poll an in-flight reveal. One upstream check per call. |
+
+A deployment with no database answers `503 not_configured` on every route; the
+rest of the platform is unaffected.
+
+## Where the code lives
+
+| Piece | File |
+|---|---|
+| Trait, rarity, and provenance engine (pure) | [api/_lib/drops.js](../api/_lib/drops.js) |
+| Persistence and the reveal state machine | [api/_lib/drop-store.js](../api/_lib/drop-store.js) |
+| HTTP routes | [api/drops/[action].js](../api/drops/%5Baction%5D.js) |
+| Schema | [api/_lib/migrations/20260901120000_generative_drops.sql](../api/_lib/migrations/20260901120000_generative_drops.sql) |
+| Index page and launcher | [pages/drops.html](../pages/drops.html), [src/drops.js](../src/drops.js) |
+| Collection page | [pages/drop-collection.html](../pages/drop-collection.html), [src/drop-collection.js](../src/drop-collection.js) |
+| Shared styles | [src/drops.css](../src/drops.css) |
+| Engine tests | [tests/drops-engine.test.js](../tests/drops-engine.test.js) |
+
+Note that `/drops/:slug` (a collection) and `/drop/:id` (the unrelated sealed
+wallet gift claim page) are different surfaces. The routes are declared so they
+can never shadow each other.
diff --git a/pages/drop-collection.html b/pages/drop-collection.html
new file mode 100644
index 000000000..20093a16b
--- /dev/null
+++ b/pages/drop-collection.html
@@ -0,0 +1,112 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot - no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Collection · three.ws Drops</title>
+ <meta
+ name="description"
+ content="A generative 3D collection on three.ws: every item is a rigged, animation-ready character rolled from a published seed, with rarity anyone can recompute from the spec."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Collection · three.ws Drops" />
+ <meta
+ property="og:description"
+ content="A generative 3D collection: rigged, animation-ready characters with verifiable rarity."
+ />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=3D+Drops&amp;d=A+generative+3D+collection+with+rigged+characters+and+verifiable+rarity&amp;p=%2Fdrops" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta property="og:image:alt" content="three.ws Drops" />
+ <meta property="og:locale" content="en_US" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/drops.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ <script src="/model-viewer-meshopt.js"></script>
+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js" integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw" crossorigin="anonymous"></script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="dr-shell">
+ <div id="dr-page-state"></div>
+
+ <article id="dr-page" hidden>
+ <section class="dr-hero" style="border-bottom: none; padding-bottom: 0">
+ <p class="dr-kicker">
+ <a href="/drops" style="color: inherit">Drops</a>
+ <span aria-hidden="true">/</span>
+ <span id="dr-symbol"></span>
+ <span class="dr-status" id="dr-status"></span>
+ </p>
+ <h1 class="dr-title" id="dr-name"></h1>
+ <p class="dr-sub" id="dr-description"></p>
+ </section>
+
+ <div class="dr-detail">
+ <div>
+ <div class="dr-stage" id="dr-stage" aria-live="polite"></div>
+ <div class="dr-ctas" style="margin-top: var(--space-md, 16px)" id="dr-item-actions"></div>
+ <dl class="dr-traits" id="dr-item-traits"></dl>
+ <p class="dr-note" id="dr-item-note" role="status" aria-live="polite"></p>
+ </div>
+
+ <div>
+ <h2 class="dr-h2" style="font-size: var(--text-lg); margin-bottom: var(--space-sm, 12px)">Supply</h2>
+ <div class="dr-meter" id="dr-supply-meter" role="progressbar" aria-valuemin="0">
+ <div class="dr-meter-fill" id="dr-supply-fill" style="width: 0%"></div>
+ </div>
+ <p class="dr-card-meta" id="dr-supply-label" style="margin: 8px 0 var(--space-lg, 24px)"></p>
+
+ <h2 class="dr-h2" style="font-size: var(--text-lg); margin-bottom: var(--space-sm, 12px)">Trait rarity</h2>
+ <div id="dr-distribution"></div>
+
+ <section class="dr-provenance">
+ <h3 class="dr-h2" style="font-size: var(--text-ui); margin: 0">Provenance</h3>
+ <p class="dr-hint" style="margin: 6px 0 0">
+ Every item's traits come from the seed below and its index alone. Recompute them
+ yourself, or ask the server to recompute them for you.
+ </p>
+ <code class="dr-hash" id="dr-hash"></code>
+ <code class="dr-hash" id="dr-seed"></code>
+ <div class="dr-ctas" style="margin-top: var(--space-sm, 12px)">
+ <button type="button" class="dr-btn dr-btn-sm" id="dr-verify">Verify this roll</button>
+ </div>
+ <p class="dr-note" id="dr-verify-note" role="status" aria-live="polite"></p>
+ </section>
+ </div>
+ </div>
+
+ <section class="dr-section-head">
+ <h2 class="dr-h2">Items</h2>
+ <span class="dr-count" id="dr-items-count" aria-live="polite"></span>
+ </section>
+
+ <div class="dr-filters" id="dr-filters" role="group" aria-label="Filter items by rarity"></div>
+ <div class="dr-item-grid" id="dr-items" aria-busy="true"></div>
+ <div class="dr-ctas" style="margin-top: var(--space-md, 16px)">
+ <button type="button" class="dr-btn" id="dr-more" hidden>Load more</button>
+ </div>
+ </article>
+ </main>
+
+ <script type="module" src="/src/drop-collection.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/pages/drops.html b/pages/drops.html
new file mode 100644
index 000000000..c2e9fd1b0
--- /dev/null
+++ b/pages/drops.html
@@ -0,0 +1,130 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot - no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>3D Drops · three.ws</title>
+ <meta
+ name="description"
+ content="Launch a supply-capped collection of AI-forged 3D characters. Pick a style, define weighted trait layers, and three.ws rolls the whole supply from a published seed: verifiable rarity, rigged and animation-ready art, minted on Solana."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/drops" />
+ <meta property="og:title" content="3D Drops · three.ws" />
+ <meta
+ property="og:description"
+ content="Launch a supply-capped collection of AI-forged, rigged 3D characters with verifiable rarity. No studio, no 18-month pipeline."
+ />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=3D+Drops&amp;d=Launch+a+supply-capped+collection+of+AI-forged+3D+characters.+Pick+a+style%2C+define+weighted+trait+layers%2C+and+three.ws+rolls+the+whole+supply+from+a+published&amp;p=%2Fdrops" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta property="og:image:alt" content="3D Drops - three.ws" />
+ <meta property="og:locale" content="en_US" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="3D Drops · three.ws" />
+ <meta
+ name="twitter:description"
+ content="Launch a supply-capped collection of AI-forged, rigged 3D characters with verifiable rarity."
+ />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=3D+Drops&amp;d=Launch+a+supply-capped+collection+of+AI-forged+3D+characters.+Pick+a+style%2C+define+weighted+trait+layers%2C+and+three.ws+rolls+the+whole+supply+from+a+published&amp;p=%2Fdrops" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/drops.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ <link rel="canonical" href="https://three.ws/drops" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"CollectionPage","name":"3D Drops","description":"Supply-capped collections of AI-forged, rigged 3D characters with verifiable rarity, launched on three.ws.","url":"https://three.ws/drops","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="dr-shell">
+ <section class="dr-hero">
+ <p class="dr-kicker"><span class="dr-dot" aria-hidden="true"></span> Generative collections</p>
+ <h1 class="dr-title">3D <em>Drops</em></h1>
+ <p class="dr-sub">
+ A 3D PFP collection used to need a studio and eighteen months. Give three.ws a style and a
+ set of weighted trait layers, and it rolls the entire supply from a published seed: every
+ item is a real, rigged, animation-ready character, its rarity is recomputable by anyone
+ holding the spec, and its art is forged on reveal rather than bulk-rendered up front.
+ </p>
+ <div class="dr-ctas">
+ <button type="button" class="dr-btn dr-btn-primary" id="dr-launch-toggle" aria-expanded="false" aria-controls="dr-launcher">
+ Launch a collection
+ </button>
+ <a class="dr-btn" href="/minted">See minted 3D assets</a>
+ <a class="dr-btn" href="/docs/drops">How drops work</a>
+ </div>
+
+ <form class="dr-panel" id="dr-launcher" hidden>
+ <div class="dr-row">
+ <div class="dr-field">
+ <label for="dr-name">Collection name</label>
+ <input class="dr-input" id="dr-name" name="name" required minlength="2" maxlength="60" placeholder="Clay Wardens" autocomplete="off" />
+ </div>
+ <div class="dr-field">
+ <label for="dr-symbol">Symbol</label>
+ <input class="dr-input" id="dr-symbol" name="symbol" required pattern="[A-Za-z0-9]{2,10}" maxlength="10" placeholder="WARDEN" autocomplete="off" />
+ <span class="dr-hint">2 to 10 letters or digits.</span>
+ </div>
+ <div class="dr-field">
+ <label for="dr-supply">Supply</label>
+ <input class="dr-input" id="dr-supply" name="supply" type="number" min="1" max="10000" value="250" required />
+ <span class="dr-hint">Up to 10,000. Rolled instantly; art is forged per item on reveal.</span>
+ </div>
+ </div>
+
+ <div class="dr-field">
+ <label for="dr-style">Base style</label>
+ <textarea class="dr-textarea" id="dr-style" name="style" required minlength="3" maxlength="400" placeholder="stylized matte-clay creature, soft rim light, chunky proportions"></textarea>
+ <span class="dr-hint">
+ The look every item shares. Each item's prompt is this plus its rolled trait fragments,
+ so the collection holds one silhouette instead of drifting item to item.
+ </span>
+ </div>
+
+ <div class="dr-field">
+ <label for="dr-description">Description <span class="dr-hint">(optional)</span></label>
+ <textarea class="dr-textarea" id="dr-description" name="description" maxlength="2000" placeholder="What this collection is, and who it is for."></textarea>
+ </div>
+
+ <div class="dr-section-head">
+ <h2 class="dr-h2" style="font-size: var(--text-lg)">Trait layers</h2>
+ <button type="button" class="dr-btn dr-btn-sm" id="dr-add-layer">Add layer</button>
+ </div>
+ <div id="dr-layers"></div>
+
+ <div class="dr-ctas" style="margin-top: var(--space-md, 16px)">
+ <button type="submit" class="dr-btn dr-btn-primary" id="dr-submit">Roll the supply</button>
+ <button type="button" class="dr-btn" id="dr-cancel">Cancel</button>
+ </div>
+ <p class="dr-note" id="dr-form-note" role="status" aria-live="polite"></p>
+ </form>
+ </section>
+
+ <section class="dr-section-head">
+ <h2 class="dr-h2">Live collections</h2>
+ <span class="dr-count" id="dr-count" aria-live="polite"></span>
+ </section>
+
+ <section class="dr-grid" id="dr-grid" aria-label="Generative 3D collections" aria-busy="true"></section>
+ <div id="dr-state"></div>
+ </main>
+
+ <script type="module" src="/src/drops.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/public/changelog.json b/public/changelog.json
index fda394c30..1bdf2856a 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,31 @@
{
- "generated_at": "2026-09-01T03:33:57.365Z",
+ "generated_at": "2026-09-01T04:36:08.861Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-09-01",
+ "type": "launch",
+ "title": "3D Drops",
+ "summary": "Launch a supply-capped collection of AI-forged 3D characters. Pick a style, define weighted trait layers, and three.ws rolls the whole supply from a published seed: verifiable rarity, rigged animation-ready art, forged on reveal.",
+ "link": "/drops",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-09-01",
+ "type": "launch",
+ "title": "3D Drops",
+ "summary": "How generative 3D collections work on three.ws: weighted trait layers, a supply rolled from a published seed, rarity scored from the actual distribution, art forged per item on reveal, and a verify endpoint anyone can recompute the roll with.",
+ "link": "/docs/drops",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-09-01",
"type": "update",
@@ -72,6 +92,16 @@
"improvement"
]
},
+ {
+ "date": "2026-09-01",
+ "type": "update",
+ "title": "Launch a 3D collection without a studio",
+ "summary": "3D Drops is live. Give it a base style and a few trait layers with weights, and it rolls a whole supply-capped collection in one go: up to 10,000 unique characters, each one a real rigged, animation-ready model rather than a flat picture. The roll is instant and free at any size because the art is generated per item when you reveal it, not rendered in bulk up front. Rarity is computed from the supply that actually came out, ranked, and sorted into common, rare, epic and legendary. Every collection publishes a fingerprint of its own recipe and, once launched, the seed behind it, so anyone can recompute the entire supply and check it against what the site served them. There is a Verify button on every collection page that does exactly that.",
+ "link": "/drops",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-09-01",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index b01911bb1..2e8b6e891 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,22 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws: features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>3D Drops</title>
+ <link>https://three.ws/drops</link>
+ <guid isPermaLink="false">2026-09-01:3D Drops</guid>
+ <pubDate>Tue, 01 Sep 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Launch a supply-capped collection of AI-forged 3D characters. Pick a style, define weighted trait layers, and three.ws rolls the whole supply from a published seed: verifiable rarity, rigged animation-ready art, forged on reveal.</description>
+ </item>
+ <item>
+ <title>3D Drops</title>
+ <link>https://three.ws/docs/drops</link>
+ <guid isPermaLink="false">2026-09-01:3D Drops</guid>
+ <pubDate>Tue, 01 Sep 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>How generative 3D collections work on three.ws: weighted trait layers, a supply rolled from a published seed, rarity scored from the actual distribution, art forged per item on reveal, and a verify endpoint anyone can recompute the roll with.</description>
+ </item>
<item>
<title>$THREE tiers page: the ladder now loads for everyone, signed in or not</title>
<link>https://three.ws/three</link>
@@ -54,6 +70,14 @@
<category>fix</category>
<description>The Quick highlights and Full tour cards on /tour now show their real stop counts and minutes (they were being reset to placeholder text a moment after loading), the chapter list matches the tour itself and no longer lists the separate getting-started walkthrough as a chapter, the page no longer clips its right edge on 320px screens, and if the tour outline fails to load you get a clear message with a retry button instead of an empty section.</description>
</item>
+ <item>
+ <title>Launch a 3D collection without a studio</title>
+ <link>https://three.ws/drops</link>
+ <guid isPermaLink="false">2026-09-01:Launch a 3D collection without a studio</guid>
+ <pubDate>Tue, 01 Sep 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>3D Drops is live. Give it a base style and a few trait layers with weights, and it rolls a whole supply-capped collection in one go: up to 10,000 unique characters, each one a real rigged, animation-ready model rather than a flat picture. The roll is instant and free at any size because the art is generated per item when you reveal it, not rendered in bulk up front. Rarity is computed from the supply that actually came out, ranked, and sorted into common, rare, epic and legendary. Every collection publishes a fingerprint of its own recipe and, once launched, the seed behind it, so anyone can recompute the entire supply and check it against what the site served them. There is a Verify button on every collection page that does exactly that.</description>
+ </item>
<item>
<title>Living Stages: the live feed connects in production, so the host actually performs</title>
<link>https://three.ws/stage</link>
diff --git a/public/features.json b/public/features.json
index 16f117e92..e3c41b7e0 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-01T03:33:57.354Z",
+ "generated_at": "2026-09-01T04:36:08.842Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -1636,6 +1636,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/drops",
+ "title": "3D Drops",
+ "description": "Launch a supply-capped collection of AI-forged 3D characters. Pick a style, define weighted trait layers, and three.ws rolls the whole supply from a published seed: verifiable rarity, rigged animation-ready art, forged on reveal.",
+ "added": "2026-09-01",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/minted",
"title": "Minted 3D Assets",
@@ -3447,6 +3457,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/docs/drops",
+ "title": "3D Drops",
+ "description": "How generative 3D collections work on three.ws: weighted trait layers, a supply rolled from a published seed, rarity scored from the actual distribution, art forged per item on reveal, and a verify endpoint anyone can recompute the roll with.",
+ "added": "2026-09-01",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/docs/forge",
"title": "Docs · Forge (text & image to 3D)",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 61fc1672d..a889580f7 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -992,6 +992,12 @@ URL: https://three.ws/launches
Live public feed of every coin launched by a three.ws agent: market caps, graduation status, and the agent behind each launch.
+### 3D Drops
+
+URL: https://three.ws/drops
+
+Launch a supply-capped collection of AI-forged 3D characters. Pick a style, define weighted trait layers, and three.ws rolls the whole supply from a published seed: verifiable rarity, rigged animation-ready art, forged on reveal.
+
### Minted 3D Assets
URL: https://three.ws/minted
@@ -2097,6 +2103,12 @@ URL: https://three.ws/docs/news-rights
What three.ws shows from a publisher's article and what it never shows: the enforced lead-excerpt limit, how a withdrawn story is removed (410, deindex, purge), and how publishers can ask us to take something down.
+### 3D Drops
+
+URL: https://three.ws/docs/drops
+
+How generative 3D collections work on three.ws: weighted trait layers, a supply rolled from a published seed, rarity scored from the actual distribution, art forged per item on reveal, and a verify endpoint anyone can recompute the roll with.
+
### Docs · Forge (text & image to 3D)
URL: https://three.ws/docs/forge
diff --git a/public/llms.txt b/public/llms.txt
index 0aeeb547f..f687aef20 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -200,6 +200,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Launch a Coin](https://three.ws/launch): Mint a coin for your 3D AI agent in one flow: pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.
- [Launch Studio: 50 ways to mint a coin](https://three.ws/launch-studio): A catalog of 50 coin-launch use cases: reward coins for trending GitHub repos and creators, and coins riding live cultural, news, and onchain narratives. Preview what each would mint right now from live data, then launch on pump.fun in one click.
- [Agent Launches](https://three.ws/launches): Live public feed of every coin launched by a three.ws agent: market caps, graduation status, and the agent behind each launch.
+- [3D Drops](https://three.ws/drops): Launch a supply-capped collection of AI-forged 3D characters. Pick a style, define weighted trait layers, and three.ws rolls the whole supply from a published seed: verifiable rarity, rigged animation-ready art, forged on reveal.
- [Minted 3D Assets](https://three.ws/minted): Live public gallery of every generated 3D avatar minted as a Metaplex Core NFT through three.ws: interactive viewer, baked provenance, and enforced creator royalties on every card.
- [Creator Gallery](https://three.ws/creations): Search, filter, and live-preview the remix bazaar: remix any published 3D creation for a real on-chain USDC royalty, view parent → child lineage, and see the trending assets and top-creator leaderboard. Every model links to its own /m/:id detail page with an interactive viewer, live geometry stats, likes, comments, and suggested models.
- [Live Trading Theater](https://three.ws/theater): Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation: when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.
@@ -385,6 +386,7 @@ Docs, tutorials, and reference.
- [3D API](https://three.ws/3d): Free, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.
- [Crypto API](https://three.ws/crypto-api): One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution: CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.
- [Docs · Publisher rights in the news reader](https://three.ws/docs/news-rights): What three.ws shows from a publisher's article and what it never shows: the enforced lead-excerpt limit, how a withdrawn story is removed (410, deindex, purge), and how publishers can ask us to take something down.
+- [3D Drops](https://three.ws/docs/drops): How generative 3D collections work on three.ws: weighted trait layers, a supply rolled from a published seed, rarity scored from the actual distribution, art forged per item on reveal, and a verify endpoint anyone can recompute the roll with.
- [Docs · Forge (text & image to 3D)](https://three.ws/docs/forge): How the Forge turns a text prompt, photos, or a sketch into a downloadable textured 3D model (GLB): the free-first engine grid with live health status, input modes, output formats, job resume, and background generation.
- [Docs · The Forge pipeline (architecture deep dive)](https://three.ws/docs/forge-pipeline): The engineering guide to the Forge: every entry point, the declared engine grid, free-first health-aware routing, the job lifecycle with two-layer failover, persistence and storage, GPU workers, post-processing, payments, and how to extend the pipeline.
- [Docs · How the Forge works, in plain language](https://three.ws/docs/how-forge-works): The five steps between typing a prompt and downloading a 3D model: reference image, reconstruction, engine selection, self-healing failover, and permanent storage. Plus what the quality tiers mean and what a finished model can do next.
diff --git a/src/drop-collection.js b/src/drop-collection.js
new file mode 100644
index 000000000..60751e11a
--- /dev/null
+++ b/src/drop-collection.js
@@ -0,0 +1,566 @@
+/**
+ * /drops/:slug - one generative 3D collection.
+ *
+ * Three things share this page and stay in sync through one `state` object:
+ * the stage (a model-viewer for the selected item, or its sealed placeholder),
+ * the item grid (paginated, filterable by rarity tier), and the provenance
+ * panel (which re-derives the roll through /api/drops/verify rather than
+ * asserting it).
+ *
+ * Reveal is a claim-then-poll job, so selecting a sealed item and pressing
+ * Reveal starts a real forge job and this module polls /api/drops/reveal until
+ * the GLB lands. Polling stops the moment the item leaves `revealing`, and on
+ * page hide, so a backgrounded tab never holds an open loop.
+ */
+
+const PAGE_SIZE = 48;
+const POLL_MS = 4000;
+const TIERS = ['legendary', 'epic', 'rare', 'common'];
+
+const el = {
+ page: document.getElementById('dr-page'),
+ pageState: document.getElementById('dr-page-state'),
+ name: document.getElementById('dr-name'),
+ symbol: document.getElementById('dr-symbol'),
+ status: document.getElementById('dr-status'),
+ description: document.getElementById('dr-description'),
+ stage: document.getElementById('dr-stage'),
+ itemActions: document.getElementById('dr-item-actions'),
+ itemTraits: document.getElementById('dr-item-traits'),
+ itemNote: document.getElementById('dr-item-note'),
+ supplyMeter: document.getElementById('dr-supply-meter'),
+ supplyFill: document.getElementById('dr-supply-fill'),
+ supplyLabel: document.getElementById('dr-supply-label'),
+ distribution: document.getElementById('dr-distribution'),
+ hash: document.getElementById('dr-hash'),
+ seed: document.getElementById('dr-seed'),
+ verify: document.getElementById('dr-verify'),
+ verifyNote: document.getElementById('dr-verify-note'),
+ filters: document.getElementById('dr-filters'),
+ items: document.getElementById('dr-items'),
+ itemsCount: document.getElementById('dr-items-count'),
+ more: document.getElementById('dr-more'),
+};
+
+const state = {
+ slug: slugFromPath(),
+ drop: null,
+ distribution: [],
+ items: [],
+ total: 0,
+ offset: 0,
+ tier: null,
+ selected: null,
+ pollTimer: null,
+};
+
+function slugFromPath() {
+ const parts = window.location.pathname.split('/').filter(Boolean);
+ const i = parts.indexOf('drops');
+ const raw = i >= 0 ? parts[i + 1] : parts[parts.length - 1];
+ return raw ? decodeURIComponent(raw) : '';
+}
+
+/* ── load ─────────────────────────────────────────────────────────────── */
+
+async function load() {
+ if (!state.slug) return fail('No collection was named in the URL.');
+ try {
+ const res = await fetch(`/api/drops/get?slug=${encodeURIComponent(state.slug)}`, {
+ headers: { accept: 'application/json' },
+ credentials: 'same-origin',
+ });
+ if (res.status === 404) return fail('That collection does not exist, or is private.');
+ if (res.status === 503) return fail('Drops are not enabled on this deployment.');
+ if (!res.ok) throw new Error(`the collection returned ${res.status}`);
+
+ const data = await res.json();
+ state.drop = data.drop;
+ state.distribution = data.distribution || [];
+ state.items = data.items || [];
+ state.offset = state.items.length;
+ state.total = state.drop.supply;
+
+ renderHeader();
+ renderSupply(data.stats);
+ renderDistribution();
+ renderFilters();
+ renderItems();
+ select(state.items[0] || null);
+
+ el.page.hidden = false;
+ document.title = `${state.drop.name} · three.ws Drops`;
+ } catch (err) {
+ fail(err?.message || 'Could not load this collection.');
+ } finally {
+ el.items.setAttribute('aria-busy', 'false');
+ }
+}
+
+function fail(message) {
+ el.pageState.innerHTML = '';
+ const box = document.createElement('div');
+ box.className = 'dr-error';
+ const h = document.createElement('h3');
+ h.textContent = 'Collection unavailable';
+ const p = document.createElement('p');
+ p.textContent = message;
+ const back = document.createElement('a');
+ back.className = 'dr-btn';
+ back.href = '/drops';
+ back.textContent = 'Browse all collections';
+ box.append(h, p, back);
+ el.pageState.appendChild(box);
+}
+
+/* ── header and panels ────────────────────────────────────────────────── */
+
+function renderHeader() {
+ el.name.textContent = state.drop.name;
+ el.symbol.textContent = state.drop.symbol;
+ el.description.textContent = state.drop.description || state.drop.style;
+ el.status.textContent = state.drop.status === 'live' ? '' : state.drop.status;
+ el.hash.textContent = `provenance ${state.drop.provenance_hash}`;
+ el.seed.textContent = state.drop.seed ? `seed ${state.drop.seed}` : 'seed sealed until launch';
+}
+
+function renderSupply(stats) {
+ const revealed = stats?.by_status?.revealed || 0;
+ const supply = state.drop.supply;
+ const pct = supply ? Math.round((revealed / supply) * 100) : 0;
+ el.supplyFill.style.width = `${pct}%`;
+ el.supplyMeter.setAttribute('aria-valuemax', String(supply));
+ el.supplyMeter.setAttribute('aria-valuenow', String(revealed));
+ el.supplyMeter.setAttribute('aria-label', `${revealed} of ${supply} revealed`);
+ el.supplyLabel.textContent = `${revealed.toLocaleString()} of ${supply.toLocaleString()} revealed`;
+}
+
+function renderDistribution() {
+ el.distribution.innerHTML = '';
+ if (!state.distribution.length) {
+ const p = document.createElement('p');
+ p.className = 'dr-hint';
+ p.textContent = 'No trait layers on this collection.';
+ el.distribution.appendChild(p);
+ return;
+ }
+ for (const layer of state.distribution) {
+ const box = document.createElement('div');
+ box.className = 'dr-dist-layer';
+ const h = document.createElement('h4');
+ h.textContent = layer.layer_name;
+ box.appendChild(h);
+ for (const v of layer.values) {
+ const row = document.createElement('div');
+ row.className = 'dr-dist-row';
+ const name = document.createElement('span');
+ name.textContent = v.value;
+ const share = document.createElement('span');
+ share.textContent = `${(v.share * 100).toFixed(1)}%`;
+ share.title = `${v.count} of ${state.drop.supply}`;
+ row.append(name, share);
+ box.appendChild(row);
+ }
+ el.distribution.appendChild(box);
+ }
+}
+
+function renderFilters() {
+ el.filters.innerHTML = '';
+ const all = chip('All', state.tier === null, () => applyTier(null));
+ el.filters.appendChild(all);
+ for (const tier of TIERS) {
+ el.filters.appendChild(
+ chip(tier[0].toUpperCase() + tier.slice(1), state.tier === tier, () => applyTier(tier)),
+ );
+ }
+}
+
+function chip(label, pressed, onClick) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = 'dr-chip';
+ b.textContent = label;
+ b.setAttribute('aria-pressed', String(pressed));
+ b.addEventListener('click', onClick);
+ return b;
+}
+
+async function applyTier(tier) {
+ state.tier = tier;
+ state.offset = 0;
+ state.items = [];
+ renderFilters();
+ el.items.setAttribute('aria-busy', 'true');
+ await loadMore(true);
+ el.items.setAttribute('aria-busy', 'false');
+}
+
+/* ── items ────────────────────────────────────────────────────────────── */
+
+async function loadMore(replace = false) {
+ const params = new URLSearchParams({
+ slug: state.slug,
+ limit: String(PAGE_SIZE),
+ offset: String(replace ? 0 : state.offset),
+ });
+ if (state.tier) params.set('tier', state.tier);
+
+ try {
+ const res = await fetch(`/api/drops/items?${params}`, {
+ headers: { accept: 'application/json' },
+ credentials: 'same-origin',
+ });
+ if (!res.ok) throw new Error(`items returned ${res.status}`);
+ const data = await res.json();
+ state.items = replace ? data.items : state.items.concat(data.items);
+ state.offset = state.items.length;
+ state.total = data.total;
+ renderItems();
+ if (replace) select(state.items[0] || null);
+ } catch (err) {
+ note(el.itemNote, err?.message || 'Could not load more items.', 'error');
+ }
+}
+
+function renderItems() {
+ el.items.innerHTML = '';
+ el.itemsCount.textContent = `${state.items.length.toLocaleString()} of ${state.total.toLocaleString()}`;
+ for (const item of state.items) el.items.appendChild(itemButton(item));
+ el.more.hidden = state.items.length >= state.total;
+}
+
+function itemButton(item) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = 'dr-item';
+ b.setAttribute('aria-current', String(state.selected?.index === item.index));
+ b.setAttribute('aria-label', `Item ${item.index}, ${item.rarity_tier}, rank ${item.rarity_rank}`);
+
+ const art = document.createElement('div');
+ art.className = 'dr-item-art';
+ if (item.thumbnail_url) {
+ const img = document.createElement('img');
+ img.src = item.thumbnail_url;
+ img.alt = '';
+ img.loading = 'lazy';
+ img.decoding = 'async';
+ art.appendChild(img);
+ } else {
+ art.textContent = item.status === 'revealed' ? '3D' : `#${item.index}`;
+ }
+
+ const foot = document.createElement('div');
+ foot.className = 'dr-item-foot';
+ const rank = document.createElement('span');
+ rank.textContent = `#${item.rarity_rank}`;
+ const pill = document.createElement('span');
+ pill.className = `dr-pill dr-pill--${item.rarity_tier}`;
+ pill.textContent = item.rarity_tier.slice(0, 4);
+ foot.append(rank, pill);
+
+ b.append(art, foot);
+ b.addEventListener('click', () => select(item));
+ return b;
+}
+
+/* ── stage ────────────────────────────────────────────────────────────── */
+
+function select(item) {
+ stopPolling();
+ state.selected = item;
+ renderItems();
+ renderStage();
+ renderItemTraits();
+ renderItemActions();
+ note(el.itemNote, '', '');
+ if (item?.status === 'revealing') startPolling();
+}
+
+function renderStage() {
+ el.stage.innerHTML = '';
+ const item = state.selected;
+ if (!item) {
+ el.stage.appendChild(sealedMark('No item selected', 'Pick one from the grid below.'));
+ return;
+ }
+
+ if (item.status === 'revealed' && item.glb_url) {
+ const viewer = document.createElement('model-viewer');
+ viewer.setAttribute('src', item.glb_url);
+ viewer.setAttribute('alt', `${state.drop.name} item ${item.index}`);
+ viewer.setAttribute('camera-controls', '');
+ viewer.setAttribute('auto-rotate', '');
+ viewer.setAttribute('touch-action', 'pan-y');
+ viewer.setAttribute('shadow-intensity', '1');
+ viewer.setAttribute('environment-image', 'neutral');
+ viewer.setAttribute('loading', 'lazy');
+ el.stage.appendChild(viewer);
+ return;
+ }
+
+ if (item.status === 'revealing') {
+ el.stage.appendChild(sealedMark('Forging', `Item #${item.index} is being generated. This takes a minute or two.`));
+ return;
+ }
+
+ if (item.status === 'failed') {
+ el.stage.appendChild(
+ sealedMark('Reveal failed', item.reveal_error || 'The generator could not finish this item. Try again.'),
+ );
+ return;
+ }
+
+ el.stage.appendChild(
+ sealedMark(`#${item.index}`, 'Sealed. Its traits are already rolled and public; only the art is unforged.'),
+ );
+}
+
+function sealedMark(title, body) {
+ const wrap = document.createElement('div');
+ wrap.className = 'dr-sealed';
+ const mark = document.createElement('div');
+ mark.className = 'dr-sealed-mark';
+ mark.textContent = title;
+ const p = document.createElement('p');
+ p.style.margin = '0';
+ p.style.maxWidth = '34ch';
+ p.textContent = body;
+ wrap.append(mark, p);
+ return wrap;
+}
+
+function renderItemTraits() {
+ el.itemTraits.innerHTML = '';
+ const item = state.selected;
+ if (!item) return;
+
+ const shareOf = (layerKey, value) => {
+ const layer = state.distribution.find((l) => l.layer === layerKey);
+ const hit = layer?.values.find((v) => v.value === value);
+ return hit ? `${(hit.share * 100).toFixed(1)}%` : '';
+ };
+
+ const rank = document.createElement('div');
+ rank.className = 'dr-trait';
+ rank.innerHTML = `<dt>Rarity</dt>`;
+ const rankDd = document.createElement('dd');
+ rankDd.append(document.createTextNode(`Rank ${item.rarity_rank} `));
+ const pill = document.createElement('span');
+ pill.className = `dr-pill dr-pill--${item.rarity_tier}`;
+ pill.textContent = item.rarity_tier;
+ rankDd.appendChild(pill);
+ rank.appendChild(rankDd);
+ el.itemTraits.appendChild(rank);
+
+ for (const t of item.traits) {
+ const box = document.createElement('div');
+ box.className = 'dr-trait';
+ const dt = document.createElement('dt');
+ dt.textContent = t.layer_name || t.layer;
+ const dd = document.createElement('dd');
+ dd.textContent = t.value;
+ const share = document.createElement('div');
+ share.className = 'dr-trait-share';
+ share.textContent = shareOf(t.layer, t.value);
+ box.append(dt, dd, share);
+ el.itemTraits.appendChild(box);
+ }
+}
+
+function renderItemActions() {
+ el.itemActions.innerHTML = '';
+ const item = state.selected;
+ if (!item) return;
+
+ if (item.status === 'revealed' && item.glb_url) {
+ el.itemActions.appendChild(
+ link('Open in viewer', `/viewer?src=${encodeURIComponent(item.glb_url)}`),
+ );
+ el.itemActions.appendChild(link('Download GLB', item.glb_url, true));
+ return;
+ }
+
+ if (item.status === 'sealed' || item.status === 'failed') {
+ const reveal = document.createElement('button');
+ reveal.type = 'button';
+ reveal.className = 'dr-btn dr-btn-primary';
+ reveal.textContent = item.status === 'failed' ? 'Retry reveal' : 'Reveal this item';
+ reveal.addEventListener('click', () => startReveal(item, reveal));
+ el.itemActions.appendChild(reveal);
+ }
+}
+
+function link(label, href, download = false) {
+ const a = document.createElement('a');
+ a.className = 'dr-btn';
+ a.href = href;
+ a.textContent = label;
+ if (download) a.setAttribute('download', '');
+ else if (href.startsWith('http')) a.rel = 'noopener';
+ return a;
+}
+
+/* ── reveal ───────────────────────────────────────────────────────────── */
+
+async function startReveal(item, button) {
+ button.disabled = true;
+ note(el.itemNote, 'Starting the forge...', '');
+ try {
+ const res = await fetch('/api/drops/reveal', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'same-origin',
+ body: JSON.stringify({ slug: state.slug, index: item.index }),
+ });
+ const data = await res.json().catch(() => ({}));
+
+ if (res.status === 401) {
+ note(el.itemNote, 'Sign in to reveal an item.', 'error');
+ button.disabled = false;
+ return;
+ }
+ if (!res.ok && res.status !== 202) {
+ note(el.itemNote, data?.message || `The forge returned ${res.status}.`, 'error');
+ button.disabled = false;
+ return;
+ }
+
+ patchItem(data.item);
+ if (data.item?.status === 'revealed') {
+ note(el.itemNote, 'Revealed.', 'ok');
+ } else {
+ note(el.itemNote, 'Generating. This page updates itself when the model lands.', '');
+ startPolling();
+ }
+ } catch (err) {
+ note(el.itemNote, err?.message || 'Could not reach the forge.', 'error');
+ button.disabled = false;
+ }
+}
+
+function startPolling() {
+ stopPolling();
+ state.pollTimer = window.setInterval(pollSelected, POLL_MS);
+}
+
+function stopPolling() {
+ if (state.pollTimer) {
+ window.clearInterval(state.pollTimer);
+ state.pollTimer = null;
+ }
+}
+
+async function pollSelected() {
+ const item = state.selected;
+ if (!item) return stopPolling();
+ try {
+ const res = await fetch(
+ `/api/drops/reveal?slug=${encodeURIComponent(state.slug)}&index=${item.index}`,
+ { headers: { accept: 'application/json' }, credentials: 'same-origin' },
+ );
+ if (!res.ok) return;
+ const data = await res.json();
+ if (!data.item) return;
+ patchItem(data.item);
+ if (data.item.status !== 'revealing') {
+ stopPolling();
+ note(
+ el.itemNote,
+ data.item.status === 'revealed' ? 'Revealed.' : data.item.reveal_error || 'Reveal stopped.',
+ data.item.status === 'revealed' ? 'ok' : 'error',
+ );
+ }
+ } catch {
+ // A dropped poll is not a failed reveal; the next tick tries again.
+ }
+}
+
+function patchItem(next) {
+ if (!next) return;
+ const i = state.items.findIndex((x) => x.index === next.index);
+ if (i >= 0) state.items[i] = { ...state.items[i], ...next };
+ if (state.selected?.index === next.index) state.selected = { ...state.selected, ...next };
+ renderItems();
+ renderStage();
+ renderItemActions();
+ refreshSupply();
+}
+
+async function refreshSupply() {
+ try {
+ const res = await fetch(`/api/drops/get?slug=${encodeURIComponent(state.slug)}`, {
+ headers: { accept: 'application/json' },
+ credentials: 'same-origin',
+ });
+ if (!res.ok) return;
+ const data = await res.json();
+ renderSupply(data.stats);
+ } catch {
+ // The meter is a readout, not a gate. A failed refresh leaves the last
+ // good number on screen rather than blanking it.
+ }
+}
+
+/* ── verify ───────────────────────────────────────────────────────────── */
+
+async function verify() {
+ el.verify.disabled = true;
+ note(el.verifyNote, 'Recomputing the roll from the published spec...', '');
+ try {
+ const params = new URLSearchParams({ slug: state.slug });
+ if (state.selected) params.set('index', String(state.selected.index));
+ const res = await fetch(`/api/drops/verify?${params}`, {
+ headers: { accept: 'application/json' },
+ credentials: 'same-origin',
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ note(el.verifyNote, data?.message || `Verification returned ${res.status}.`, 'error');
+ return;
+ }
+
+ const hashOk = data.hash_matches;
+ const itemOk = data.item ? data.item.traits_match : true;
+ if (hashOk && itemOk) {
+ note(
+ el.verifyNote,
+ data.item
+ ? `Verified. The provenance hash matches the spec, and item #${data.item.index} re-rolls to exactly the traits served.`
+ : 'Verified. The provenance hash matches the published spec.',
+ 'ok',
+ );
+ } else {
+ note(
+ el.verifyNote,
+ hashOk
+ ? 'The provenance hash matches, but the selected item does not re-roll to the traits served. Report this collection.'
+ : 'The provenance hash does not match the published spec. Report this collection.',
+ 'error',
+ );
+ }
+ } catch (err) {
+ note(el.verifyNote, err?.message || 'Could not run verification.', 'error');
+ } finally {
+ el.verify.disabled = false;
+ }
+}
+
+/* ── wire ─────────────────────────────────────────────────────────────── */
+
+function note(target, message, kind) {
+ target.textContent = message || '';
+ target.className = `dr-note${kind ? ` dr-note--${kind}` : ''}`;
+}
+
+el.more?.addEventListener('click', () => loadMore(false));
+el.verify?.addEventListener('click', verify);
+
+// A backgrounded tab must not keep an open poll loop running.
+document.addEventListener('visibilitychange', () => {
+ if (document.hidden) stopPolling();
+ else if (state.selected?.status === 'revealing') startPolling();
+});
+window.addEventListener('pagehide', stopPolling);
+
+load();
diff --git a/src/drops.css b/src/drops.css
new file mode 100644
index 000000000..626e8449d
--- /dev/null
+++ b/src/drops.css
@@ -0,0 +1,673 @@
+/* Generative 3D drops: /drops (index + launcher) and /drops/:slug (collection).
+ Both surfaces share this sheet so a drop card looks identical wherever it
+ appears. Every value comes from public/tokens.css. */
+
+.dr-shell {
+ max-width: 1180px;
+ margin: 0 auto;
+ padding: var(--space-xl, 32px) var(--space-lg, 24px) var(--space-3xl, 96px);
+}
+
+/* ── hero ─────────────────────────────────────────────────────────────── */
+
+.dr-hero {
+ padding: var(--space-2xl, 56px) 0 var(--space-xl, 32px);
+ border-bottom: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
+}
+
+.dr-kicker {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0 0 var(--space-sm, 12px);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs, 11px);
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: var(--text-muted, rgba(255, 255, 255, 0.55));
+}
+
+.dr-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--success, #34d399);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--success, #34d399) 22%, transparent);
+}
+
+.dr-title {
+ margin: 0 0 var(--space-md, 16px);
+ font-family: var(--font-display);
+ font-size: var(--text-2xl, 41.9px);
+ line-height: var(--leading-tight, 1.382);
+ letter-spacing: -0.02em;
+ font-weight: var(--weight-bold, 700);
+}
+
+.dr-title em {
+ font-style: normal;
+ background: linear-gradient(100deg, var(--text-1, #fff), var(--text-muted, rgba(255, 255, 255, 0.5)));
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+}
+
+.dr-sub {
+ max-width: 62ch;
+ margin: 0 0 var(--space-lg, 24px);
+ font-size: var(--text-base, 16px);
+ line-height: var(--leading-normal, 1.618);
+ color: var(--text-muted, rgba(255, 255, 255, 0.62));
+}
+
+.dr-ctas {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-sm, 12px);
+}
+
+/* ── buttons ──────────────────────────────────────────────────────────── */
+
+.dr-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 40px;
+ padding: 0 var(--space-md, 16px);
+ border: 1px solid var(--border-strong, rgba(255, 255, 255, 0.16));
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ color: var(--text-1, #fff);
+ font: inherit;
+ font-size: var(--text-ui, 14px);
+ font-weight: var(--weight-medium, 500);
+ text-decoration: none;
+ cursor: pointer;
+ transition: background 140ms ease, border-color 140ms ease, transform 140ms ease;
+}
+
+.dr-btn:hover:not(:disabled) {
+ background: var(--surface-2, rgba(255, 255, 255, 0.07));
+ border-color: var(--border-hover, rgba(255, 255, 255, 0.28));
+}
+
+.dr-btn:active:not(:disabled) {
+ transform: translateY(1px);
+}
+
+.dr-btn:focus-visible {
+ outline: 2px solid var(--focus-ring-color, var(--accent));
+ outline-offset: 2px;
+}
+
+.dr-btn:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.dr-btn-primary {
+ background: var(--accent, #fff);
+ border-color: var(--accent, #fff);
+ color: var(--accent-contrast, #0a0a0a);
+}
+
+.dr-btn-primary:hover:not(:disabled) {
+ background: color-mix(in srgb, var(--accent, #fff) 88%, transparent);
+ border-color: color-mix(in srgb, var(--accent, #fff) 88%, transparent);
+}
+
+.dr-btn-sm {
+ min-height: 32px;
+ padding: 0 var(--space-sm, 12px);
+ font-size: var(--text-md, 13px);
+}
+
+/* ── grid of collections ──────────────────────────────────────────────── */
+
+.dr-section-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: var(--space-md, 16px);
+ margin: var(--space-xl, 32px) 0 var(--space-md, 16px);
+}
+
+.dr-h2 {
+ margin: 0;
+ font-family: var(--font-display);
+ font-size: var(--text-xl, 25.9px);
+ letter-spacing: -0.015em;
+ font-weight: var(--weight-semibold, 600);
+}
+
+.dr-count {
+ font-family: var(--font-mono);
+ font-size: var(--text-sm, 12.2px);
+ color: var(--text-muted, rgba(255, 255, 255, 0.5));
+}
+
+.dr-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
+ gap: var(--space-md, 16px);
+}
+
+.dr-card {
+ display: flex;
+ flex-direction: column;
+ border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
+ border-radius: var(--radius-lg, 14px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ overflow: hidden;
+ text-decoration: none;
+ color: inherit;
+ transition: border-color 160ms ease, transform 160ms ease, background 160ms ease;
+}
+
+.dr-card:hover {
+ border-color: var(--border-hover, rgba(255, 255, 255, 0.24));
+ background: var(--surface-2, rgba(255, 255, 255, 0.055));
+ transform: translateY(-2px);
+}
+
+.dr-card:focus-visible {
+ outline: 2px solid var(--focus-ring-color, var(--accent));
+ outline-offset: 2px;
+}
+
+.dr-card-art {
+ position: relative;
+ aspect-ratio: 4 / 3;
+ background:
+ radial-gradient(circle at 50% 38%, color-mix(in srgb, var(--accent, #fff) 9%, transparent), transparent 62%),
+ var(--surface-0, rgba(255, 255, 255, 0.02));
+ display: grid;
+ place-items: center;
+ overflow: hidden;
+}
+
+.dr-card-art img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+
+.dr-card-body {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: var(--space-md, 16px);
+}
+
+.dr-card-name {
+ font-family: var(--font-display);
+ font-size: var(--text-lg, 19.8px);
+ font-weight: var(--weight-semibold, 600);
+ letter-spacing: -0.01em;
+}
+
+.dr-card-meta {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs, 11px);
+ color: var(--text-muted, rgba(255, 255, 255, 0.5));
+}
+
+.dr-card-desc {
+ font-size: var(--text-md, 13px);
+ line-height: var(--leading-normal, 1.618);
+ color: var(--text-muted, rgba(255, 255, 255, 0.6));
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+
+/* ── supply meter ─────────────────────────────────────────────────────── */
+
+.dr-meter {
+ height: 4px;
+ border-radius: 2px;
+ background: var(--surface-3, rgba(255, 255, 255, 0.1));
+ overflow: hidden;
+}
+
+.dr-meter-fill {
+ height: 100%;
+ border-radius: inherit;
+ background: linear-gradient(90deg, var(--accent, #fff), color-mix(in srgb, var(--accent, #fff) 45%, transparent));
+ transition: width 320ms ease;
+}
+
+/* ── rarity pills ─────────────────────────────────────────────────────── */
+
+.dr-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 2px 8px;
+ border-radius: 999px;
+ border: 1px solid currentColor;
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs, 11px);
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ background: color-mix(in srgb, currentColor 12%, transparent);
+}
+
+.dr-pill--common { color: var(--text-muted, #9aa4b2); }
+.dr-pill--rare { color: #56a3f0; }
+.dr-pill--epic { color: #a97bf5; }
+.dr-pill--legendary { color: #f0a83c; }
+
+.dr-status {
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs, 11px);
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--text-muted, rgba(255, 255, 255, 0.5));
+}
+
+/* ── states ───────────────────────────────────────────────────────────── */
+
+.dr-empty,
+.dr-error {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: var(--space-sm, 12px);
+ padding: var(--space-2xl, 56px) var(--space-lg, 24px);
+ border: 1px dashed var(--border-subtle, rgba(255, 255, 255, 0.12));
+ border-radius: var(--radius-lg, 14px);
+ text-align: center;
+ color: var(--text-muted, rgba(255, 255, 255, 0.6));
+}
+
+.dr-empty h3,
+.dr-error h3 {
+ margin: 0;
+ font-family: var(--font-display);
+ font-size: var(--text-lg, 19.8px);
+ color: var(--text-1, #fff);
+}
+
+.dr-empty p,
+.dr-error p {
+ margin: 0;
+ max-width: 46ch;
+ font-size: var(--text-md, 13px);
+ line-height: var(--leading-normal, 1.618);
+}
+
+.dr-skeleton {
+ border-radius: var(--radius-lg, 14px);
+ background: linear-gradient(
+ 100deg,
+ var(--surface-1, rgba(255, 255, 255, 0.03)) 30%,
+ var(--surface-3, rgba(255, 255, 255, 0.08)) 50%,
+ var(--surface-1, rgba(255, 255, 255, 0.03)) 70%
+ );
+ background-size: 220% 100%;
+ animation: dr-shimmer 1.35s ease-in-out infinite;
+ min-height: 260px;
+}
+
+@keyframes dr-shimmer {
+ from { background-position: 180% 0; }
+ to { background-position: -60% 0; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .dr-skeleton { animation: none; }
+ .dr-card:hover { transform: none; }
+ .dr-meter-fill { transition: none; }
+}
+
+/* ── launcher form ────────────────────────────────────────────────────── */
+
+.dr-panel {
+ margin-top: var(--space-lg, 24px);
+ border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.09));
+ border-radius: var(--radius-lg, 14px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.028));
+ padding: var(--space-lg, 24px);
+}
+
+.dr-field {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin-bottom: var(--space-md, 16px);
+}
+
+.dr-field label {
+ font-size: var(--text-md, 13px);
+ font-weight: var(--weight-medium, 500);
+}
+
+.dr-field .dr-hint {
+ font-size: var(--text-sm, 12.2px);
+ color: var(--text-muted, rgba(255, 255, 255, 0.5));
+ line-height: var(--leading-normal, 1.618);
+}
+
+.dr-input,
+.dr-textarea,
+.dr-select {
+ width: 100%;
+ min-height: 40px;
+ padding: 9px var(--space-sm, 12px);
+ border: 1px solid var(--border-strong, rgba(255, 255, 255, 0.14));
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-0, rgba(0, 0, 0, 0.24));
+ color: var(--text-1, #fff);
+ font: inherit;
+ font-size: var(--text-ui, 14px);
+}
+
+.dr-textarea {
+ min-height: 82px;
+ resize: vertical;
+ line-height: var(--leading-normal, 1.618);
+}
+
+.dr-input:focus-visible,
+.dr-textarea:focus-visible,
+.dr-select:focus-visible {
+ outline: 2px solid var(--focus-ring-color, var(--accent));
+ outline-offset: 1px;
+ border-color: transparent;
+}
+
+.dr-row {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+ gap: var(--space-md, 16px);
+}
+
+.dr-layer {
+ border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
+ border-radius: var(--radius-md, 10px);
+ padding: var(--space-md, 16px);
+ margin-bottom: var(--space-sm, 12px);
+ background: var(--surface-0, rgba(0, 0, 0, 0.16));
+}
+
+.dr-layer-head {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm, 12px);
+ margin-bottom: var(--space-sm, 12px);
+}
+
+.dr-layer-head .dr-input {
+ flex: 1;
+ min-width: 0;
+}
+
+.dr-option {
+ display: grid;
+ grid-template-columns: 1fr 88px 32px;
+ gap: 8px;
+ margin-bottom: 8px;
+ align-items: center;
+}
+
+.dr-icon-btn {
+ width: 32px;
+ height: 32px;
+ display: grid;
+ place-items: center;
+ border: 1px solid var(--border-strong, rgba(255, 255, 255, 0.14));
+ border-radius: var(--radius-sm, 8px);
+ background: transparent;
+ color: var(--text-muted, rgba(255, 255, 255, 0.6));
+ cursor: pointer;
+ font: inherit;
+ line-height: 1;
+ transition: color 140ms ease, border-color 140ms ease;
+}
+
+.dr-icon-btn:hover {
+ color: var(--danger, #f87171);
+ border-color: currentColor;
+}
+
+.dr-icon-btn:focus-visible {
+ outline: 2px solid var(--focus-ring-color, var(--accent));
+ outline-offset: 2px;
+}
+
+.dr-note {
+ margin-top: var(--space-sm, 12px);
+ font-size: var(--text-md, 13px);
+ line-height: var(--leading-normal, 1.618);
+ color: var(--text-muted, rgba(255, 255, 255, 0.6));
+}
+
+.dr-note--error { color: var(--danger, #f87171); }
+.dr-note--ok { color: var(--success, #34d399); }
+
+/* ── detail page ──────────────────────────────────────────────────────── */
+
+.dr-detail {
+ display: grid;
+ grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr);
+ gap: var(--space-xl, 32px);
+ align-items: start;
+ padding-top: var(--space-xl, 32px);
+}
+
+@media (max-width: 900px) {
+ .dr-detail { grid-template-columns: 1fr; }
+}
+
+.dr-stage {
+ position: relative;
+ aspect-ratio: 1 / 1;
+ border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.09));
+ border-radius: var(--radius-lg, 14px);
+ overflow: hidden;
+ background:
+ radial-gradient(circle at 50% 40%, color-mix(in srgb, var(--accent, #fff) 10%, transparent), transparent 65%),
+ var(--surface-0, rgba(255, 255, 255, 0.02));
+ display: grid;
+ place-items: center;
+}
+
+.dr-stage model-viewer {
+ width: 100%;
+ height: 100%;
+ --poster-color: transparent;
+}
+
+.dr-sealed {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: var(--space-sm, 12px);
+ padding: var(--space-lg, 24px);
+ text-align: center;
+ color: var(--text-muted, rgba(255, 255, 255, 0.55));
+}
+
+.dr-sealed-mark {
+ width: 76px;
+ height: 76px;
+ border-radius: var(--radius-lg, 14px);
+ border: 1px dashed var(--border-strong, rgba(255, 255, 255, 0.22));
+ display: grid;
+ place-items: center;
+ font-family: var(--font-mono);
+ font-size: var(--text-lg, 19.8px);
+ color: var(--text-1, #fff);
+}
+
+.dr-traits {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
+ gap: var(--space-sm, 12px);
+ margin: var(--space-md, 16px) 0;
+}
+
+.dr-trait {
+ padding: 10px var(--space-sm, 12px);
+ border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+}
+
+.dr-trait dt {
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs, 11px);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--text-muted, rgba(255, 255, 255, 0.5));
+ margin-bottom: 3px;
+}
+
+.dr-trait dd {
+ margin: 0;
+ font-size: var(--text-ui, 14px);
+ font-weight: var(--weight-medium, 500);
+}
+
+.dr-trait-share {
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs, 11px);
+ color: var(--text-muted, rgba(255, 255, 255, 0.45));
+}
+
+.dr-provenance {
+ margin-top: var(--space-lg, 24px);
+ padding: var(--space-md, 16px);
+ border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-0, rgba(0, 0, 0, 0.18));
+}
+
+.dr-hash {
+ display: block;
+ overflow-wrap: anywhere;
+ font-family: var(--font-mono);
+ font-size: var(--text-sm, 12.2px);
+ color: var(--text-muted, rgba(255, 255, 255, 0.62));
+ margin: 6px 0 0;
+}
+
+.dr-item-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(132px, 1fr));
+ gap: var(--space-sm, 12px);
+}
+
+.dr-item {
+ border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ padding: 0;
+ overflow: hidden;
+ cursor: pointer;
+ text-align: left;
+ color: inherit;
+ font: inherit;
+ transition: border-color 150ms ease, transform 150ms ease;
+}
+
+.dr-item:hover { border-color: var(--border-hover, rgba(255, 255, 255, 0.26)); transform: translateY(-2px); }
+.dr-item:focus-visible { outline: 2px solid var(--focus-ring-color, var(--accent)); outline-offset: 2px; }
+.dr-item[aria-current='true'] { border-color: var(--accent, #fff); }
+
+.dr-item-art {
+ aspect-ratio: 1 / 1;
+ display: grid;
+ place-items: center;
+ background: var(--surface-0, rgba(255, 255, 255, 0.02));
+ font-family: var(--font-mono);
+ font-size: var(--text-md, 13px);
+ color: var(--text-muted, rgba(255, 255, 255, 0.4));
+}
+
+.dr-item-art img { width: 100%; height: 100%; object-fit: cover; }
+
+.dr-item-foot {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px;
+ padding: 7px 9px;
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs, 11px);
+ color: var(--text-muted, rgba(255, 255, 255, 0.55));
+}
+
+.dr-filters {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-bottom: var(--space-md, 16px);
+}
+
+.dr-chip {
+ padding: 5px 11px;
+ border-radius: 999px;
+ border: 1px solid var(--border-strong, rgba(255, 255, 255, 0.14));
+ background: transparent;
+ color: var(--text-muted, rgba(255, 255, 255, 0.65));
+ font: inherit;
+ font-size: var(--text-md, 13px);
+ cursor: pointer;
+ transition: color 140ms ease, border-color 140ms ease, background 140ms ease;
+}
+
+.dr-chip:hover { color: var(--text-1, #fff); border-color: var(--border-hover, rgba(255, 255, 255, 0.3)); }
+.dr-chip:focus-visible { outline: 2px solid var(--focus-ring-color, var(--accent)); outline-offset: 2px; }
+.dr-chip[aria-pressed='true'] {
+ color: var(--accent-contrast, #0a0a0a);
+ background: var(--accent, #fff);
+ border-color: var(--accent, #fff);
+}
+
+.dr-dist-layer { margin-bottom: var(--space-md, 16px); }
+
+.dr-dist-layer h4 {
+ margin: 0 0 6px;
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs, 11px);
+ letter-spacing: 0.09em;
+ text-transform: uppercase;
+ color: var(--text-muted, rgba(255, 255, 255, 0.5));
+}
+
+.dr-dist-row {
+ display: grid;
+ grid-template-columns: 1fr 56px;
+ gap: 8px;
+ align-items: center;
+ padding: 4px 0;
+ font-size: var(--text-md, 13px);
+ border-bottom: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.05));
+}
+
+.dr-dist-row span:last-child {
+ text-align: right;
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs, 11px);
+ color: var(--text-muted, rgba(255, 255, 255, 0.5));
+}
+
+.dr-sr {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border: 0;
+}
diff --git a/src/drops.js b/src/drops.js
new file mode 100644
index 000000000..04676227c
--- /dev/null
+++ b/src/drops.js
@@ -0,0 +1,374 @@
+/**
+ * /drops - the generative 3D collection index and launcher.
+ *
+ * Two jobs on one page: list the live collections, and let a signed-in creator
+ * define and roll a new one. The launcher is a real form over
+ * POST /api/drops/create; the trait-layer builder below is the only part with
+ * meaningful state, and it is kept as a plain array of {name, options[]} that is
+ * serialized on submit rather than a reactive model, because the server
+ * normalizes and validates the same shape anyway.
+ */
+
+const grid = document.getElementById('dr-grid');
+const stateEl = document.getElementById('dr-state');
+const countEl = document.getElementById('dr-count');
+const form = document.getElementById('dr-launcher');
+const toggle = document.getElementById('dr-launch-toggle');
+const layersEl = document.getElementById('dr-layers');
+const noteEl = document.getElementById('dr-form-note');
+
+// A first-run layer set, so the builder opens on something a creator can edit
+// rather than an empty box that gives no hint of the shape expected.
+const STARTER_LAYERS = [
+ { name: 'Species', options: [{ value: 'Fox', weight: 60 }, { value: 'Wolf', weight: 30 }, { value: 'Dragon', weight: 10 }] },
+ { name: 'Outfit', options: [{ value: 'Bomber jacket', weight: 50 }, { value: 'Lab coat', weight: 50 }] },
+ { name: 'Aura', options: [{ value: 'None', weight: 70 }, { value: 'Ember', weight: 20 }, { value: 'Frost', weight: 10 }] },
+];
+
+let layers = STARTER_LAYERS.map((l) => ({ name: l.name, options: l.options.map((o) => ({ ...o })) }));
+
+/* ── list ─────────────────────────────────────────────────────────────── */
+
+function skeletons(n = 6) {
+ grid.innerHTML = '';
+ for (let i = 0; i < n; i++) {
+ const div = document.createElement('div');
+ div.className = 'dr-skeleton';
+ grid.appendChild(div);
+ }
+}
+
+async function loadDrops() {
+ skeletons();
+ stateEl.innerHTML = '';
+ try {
+ const res = await fetch('/api/drops/list?limit=24', { headers: { accept: 'application/json' } });
+ if (res.status === 503) return renderUnavailable();
+ if (!res.ok) throw new Error(`the collection index returned ${res.status}`);
+ const data = await res.json();
+ renderDrops(Array.isArray(data.drops) ? data.drops : []);
+ } catch (err) {
+ renderError(err?.message || 'could not reach the collection index');
+ } finally {
+ grid.setAttribute('aria-busy', 'false');
+ }
+}
+
+function renderDrops(drops) {
+ grid.innerHTML = '';
+ countEl.textContent = drops.length ? `${drops.length} collection${drops.length === 1 ? '' : 's'}` : '';
+
+ if (!drops.length) {
+ stateEl.innerHTML = '';
+ const empty = document.createElement('div');
+ empty.className = 'dr-empty';
+ empty.innerHTML = `
+ <h3>No collections launched yet</h3>
+ <p>
+ Be the first. Pick a style, define a few trait layers, and roll a supply.
+ The whole collection exists the moment you submit; art is forged per item as it reveals.
+ </p>`;
+ const cta = document.createElement('button');
+ cta.type = 'button';
+ cta.className = 'dr-btn dr-btn-primary';
+ cta.textContent = 'Launch a collection';
+ cta.addEventListener('click', () => openLauncher(true));
+ empty.appendChild(cta);
+ stateEl.appendChild(empty);
+ return;
+ }
+
+ for (const drop of drops) grid.appendChild(cardFor(drop));
+}
+
+function cardFor(drop) {
+ const revealed = Number(drop.revealed_count) || 0;
+ const supply = Number(drop.supply) || 0;
+ const pct = supply ? Math.round((revealed / supply) * 100) : 0;
+
+ const a = document.createElement('a');
+ a.className = 'dr-card';
+ a.href = `/drops/${encodeURIComponent(drop.slug)}`;
+
+ const art = document.createElement('div');
+ art.className = 'dr-card-art';
+ art.setAttribute('aria-hidden', 'true');
+ art.textContent = drop.symbol || '3D';
+ art.style.fontFamily = 'var(--font-mono)';
+ art.style.letterSpacing = '0.12em';
+ art.style.color = 'var(--text-muted, rgba(255,255,255,0.4))';
+
+ const body = document.createElement('div');
+ body.className = 'dr-card-body';
+
+ const name = document.createElement('div');
+ name.className = 'dr-card-name';
+ name.textContent = drop.name;
+
+ const meta = document.createElement('div');
+ meta.className = 'dr-card-meta';
+ meta.innerHTML = `<span>${drop.symbol}</span><span aria-hidden="true">·</span><span>${supply.toLocaleString()} supply</span>`;
+ if (drop.status !== 'live') {
+ const status = document.createElement('span');
+ status.className = 'dr-status';
+ status.textContent = drop.status;
+ meta.append(document.createTextNode(' '), status);
+ }
+
+ const desc = document.createElement('p');
+ desc.className = 'dr-card-desc';
+ desc.textContent = drop.description || drop.style;
+
+ const meter = document.createElement('div');
+ meter.className = 'dr-meter';
+ meter.setAttribute('role', 'progressbar');
+ meter.setAttribute('aria-valuemin', '0');
+ meter.setAttribute('aria-valuemax', String(supply));
+ meter.setAttribute('aria-valuenow', String(revealed));
+ meter.setAttribute('aria-label', `${revealed} of ${supply} revealed`);
+ const fill = document.createElement('div');
+ fill.className = 'dr-meter-fill';
+ fill.style.width = `${pct}%`;
+ meter.appendChild(fill);
+
+ const foot = document.createElement('div');
+ foot.className = 'dr-card-meta';
+ foot.textContent = `${revealed.toLocaleString()} of ${supply.toLocaleString()} revealed`;
+
+ body.append(name, meta, desc, meter, foot);
+ a.append(art, body);
+ return a;
+}
+
+function renderError(message) {
+ grid.innerHTML = '';
+ countEl.textContent = '';
+ stateEl.innerHTML = '';
+ const box = document.createElement('div');
+ box.className = 'dr-error';
+ const h = document.createElement('h3');
+ h.textContent = 'Could not load collections';
+ const p = document.createElement('p');
+ p.textContent = message;
+ const retry = document.createElement('button');
+ retry.type = 'button';
+ retry.className = 'dr-btn';
+ retry.textContent = 'Try again';
+ retry.addEventListener('click', loadDrops);
+ box.append(h, p, retry);
+ stateEl.appendChild(box);
+}
+
+function renderUnavailable() {
+ grid.innerHTML = '';
+ stateEl.innerHTML = '';
+ const box = document.createElement('div');
+ box.className = 'dr-empty';
+ box.innerHTML = `
+ <h3>Drops are not enabled here</h3>
+ <p>This deployment has no database configured, so collections cannot be stored. The rest of the platform is unaffected.</p>`;
+ stateEl.appendChild(box);
+}
+
+/* ── launcher ─────────────────────────────────────────────────────────── */
+
+function openLauncher(open) {
+ form.hidden = !open;
+ toggle.setAttribute('aria-expanded', String(open));
+ if (open) {
+ renderLayers();
+ document.getElementById('dr-name')?.focus();
+ form.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+ }
+}
+
+function renderLayers() {
+ layersEl.innerHTML = '';
+ layers.forEach((layer, li) => layersEl.appendChild(layerRow(layer, li)));
+}
+
+function layerRow(layer, li) {
+ const wrap = document.createElement('div');
+ wrap.className = 'dr-layer';
+
+ const head = document.createElement('div');
+ head.className = 'dr-layer-head';
+
+ const nameInput = document.createElement('input');
+ nameInput.className = 'dr-input';
+ nameInput.value = layer.name;
+ nameInput.maxLength = 40;
+ nameInput.placeholder = 'Layer name (Species, Outfit, Aura)';
+ nameInput.setAttribute('aria-label', `Name of trait layer ${li + 1}`);
+ nameInput.addEventListener('input', () => {
+ layer.name = nameInput.value;
+ });
+
+ const remove = document.createElement('button');
+ remove.type = 'button';
+ remove.className = 'dr-icon-btn';
+ remove.textContent = '×';
+ remove.title = 'Remove this layer';
+ remove.setAttribute('aria-label', `Remove trait layer ${li + 1}`);
+ remove.addEventListener('click', () => {
+ layers.splice(li, 1);
+ renderLayers();
+ });
+
+ head.append(nameInput, remove);
+ wrap.appendChild(head);
+
+ layer.options.forEach((option, oi) => wrap.appendChild(optionRow(layer, option, oi, li)));
+
+ const add = document.createElement('button');
+ add.type = 'button';
+ add.className = 'dr-btn dr-btn-sm';
+ add.textContent = 'Add option';
+ add.addEventListener('click', () => {
+ layer.options.push({ value: '', weight: 10 });
+ renderLayers();
+ });
+ wrap.appendChild(add);
+
+ const total = layer.options.reduce((n, o) => n + (Number(o.weight) || 0), 0);
+ const hint = document.createElement('p');
+ hint.className = 'dr-hint';
+ hint.style.marginTop = '8px';
+ hint.textContent = total
+ ? `Weights are relative. ${layer.options
+ .filter((o) => o.value)
+ .map((o) => `${o.value} ${Math.round(((Number(o.weight) || 0) / total) * 100)}%`)
+ .join(', ')}`
+ : 'Add at least one option with a weight above zero.';
+ wrap.appendChild(hint);
+
+ return wrap;
+}
+
+function optionRow(layer, option, oi, li) {
+ const row = document.createElement('div');
+ row.className = 'dr-option';
+
+ const value = document.createElement('input');
+ value.className = 'dr-input';
+ value.value = option.value;
+ value.maxLength = 60;
+ value.placeholder = 'Trait value';
+ value.setAttribute('aria-label', `Value of option ${oi + 1} in layer ${li + 1}`);
+ value.addEventListener('input', () => {
+ option.value = value.value;
+ });
+
+ const weight = document.createElement('input');
+ weight.className = 'dr-input';
+ weight.type = 'number';
+ weight.min = '1';
+ weight.step = '1';
+ weight.value = String(option.weight);
+ weight.setAttribute('aria-label', `Weight of option ${oi + 1} in layer ${li + 1}`);
+ weight.addEventListener('input', () => {
+ option.weight = Number(weight.value) || 0;
+ });
+ weight.addEventListener('change', renderLayers);
+
+ const remove = document.createElement('button');
+ remove.type = 'button';
+ remove.className = 'dr-icon-btn';
+ remove.textContent = '×';
+ remove.title = 'Remove this option';
+ remove.setAttribute('aria-label', `Remove option ${oi + 1} from layer ${li + 1}`);
+ remove.addEventListener('click', () => {
+ layer.options.splice(oi, 1);
+ renderLayers();
+ });
+
+ row.append(value, weight, remove);
+ return row;
+}
+
+function setNote(message, kind) {
+ noteEl.textContent = message || '';
+ noteEl.className = `dr-note${kind ? ` dr-note--${kind}` : ''}`;
+}
+
+async function submitDrop(event) {
+ event.preventDefault();
+ const submit = document.getElementById('dr-submit');
+
+ const cleaned = layers
+ .map((l) => ({
+ name: String(l.name || '').trim(),
+ options: l.options
+ .filter((o) => String(o.value || '').trim())
+ .map((o) => ({ value: String(o.value).trim(), weight: Number(o.weight) || 1 })),
+ }))
+ .filter((l) => l.name && l.options.length);
+
+ if (!cleaned.length) {
+ setNote('Add at least one trait layer with a named option before rolling.', 'error');
+ return;
+ }
+
+ const payload = {
+ name: document.getElementById('dr-name').value.trim(),
+ symbol: document.getElementById('dr-symbol').value.trim().toUpperCase(),
+ style: document.getElementById('dr-style').value.trim(),
+ description: document.getElementById('dr-description').value.trim() || undefined,
+ supply: Number(document.getElementById('dr-supply').value),
+ layers: cleaned,
+ };
+
+ const combos = cleaned.reduce((n, l) => n * l.options.length, 1);
+ if (combos < payload.supply) {
+ setNote(
+ `These layers can only produce ${combos.toLocaleString()} distinct combinations for a supply of ${payload.supply.toLocaleString()}. Duplicates are allowed, but adding options or layers gives the rarity curve more to work with.`,
+ '',
+ );
+ } else {
+ setNote('Rolling the supply...', '');
+ }
+
+ submit.disabled = true;
+ try {
+ const res = await fetch('/api/drops/create', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'same-origin',
+ body: JSON.stringify(payload),
+ });
+ const data = await res.json().catch(() => ({}));
+
+ if (res.status === 401) {
+ setNote('Sign in to launch a collection.', 'error');
+ return;
+ }
+ if (!res.ok) {
+ setNote(data?.message || `The launcher returned ${res.status}.`, 'error');
+ return;
+ }
+
+ setNote(`Rolled ${data.drop.supply.toLocaleString()} items. Opening the collection...`, 'ok');
+ window.location.href = `/drops/${encodeURIComponent(data.drop.slug)}`;
+ } catch (err) {
+ setNote(err?.message || 'Could not reach the launcher.', 'error');
+ } finally {
+ submit.disabled = false;
+ }
+}
+
+/* ── wire ─────────────────────────────────────────────────────────────── */
+
+toggle?.addEventListener('click', () => openLauncher(form.hidden));
+document.getElementById('dr-cancel')?.addEventListener('click', () => openLauncher(false));
+document.getElementById('dr-add-layer')?.addEventListener('click', () => {
+ layers.push({ name: '', options: [{ value: '', weight: 10 }] });
+ renderLayers();
+});
+form?.addEventListener('submit', submitDrop);
+
+// Escape closes the launcher, matching every other overlay on the platform.
+document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && !form.hidden) openLauncher(false);
+});
+
+loadDrops();
diff --git a/tests/drops-engine.test.js b/tests/drops-engine.test.js
new file mode 100644
index 000000000..c11284faf
--- /dev/null
+++ b/tests/drops-engine.test.js
@@ -0,0 +1,395 @@
+/**
+ * Generative 3D drops: trait + rarity engine unit tests.
+ *
+ * The whole product claim of a drop is "this roll was not rigged", so the tests
+ * that matter most here are the determinism and independence ones: the same
+ * inputs must reproduce identical traits, and appending a layer must not
+ * disturb the values already rolled on the layers beside it. Those two
+ * properties are what make the published provenance hash worth anything.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ DropSpecError,
+ MAX_LAYERS,
+ MAX_OPTIONS_PER_LAYER,
+ MAX_SUPPLY,
+ assertSupply,
+ itemPrompt,
+ normalizeLayers,
+ pickWeighted,
+ provenanceHash,
+ rollItem,
+ rollSupply,
+ scoreRarity,
+ slugify,
+ tierForRank,
+ traitDistribution,
+ verifyItem,
+} from '../api/_lib/drops.js';
+
+const LAYERS = normalizeLayers([
+ {
+ name: 'Species',
+ options: [
+ { value: 'Fox', weight: 60 },
+ { value: 'Wolf', weight: 30 },
+ { value: 'Dragon', weight: 10 },
+ ],
+ },
+ {
+ name: 'Outfit',
+ options: [
+ { value: 'Bomber Jacket', weight: 50, prompt: 'wearing a worn leather bomber jacket' },
+ { value: 'Lab Coat', weight: 50 },
+ ],
+ },
+ { name: 'Aura', options: ['None', 'Ember', 'Frost'] },
+]);
+
+describe('normalizeLayers', () => {
+ it('derives a slug key from the layer name', () => {
+ const [species] = normalizeLayers([{ name: 'Head Wear', options: ['Cap'] }]);
+ expect(species.key).toBe('head-wear');
+ expect(species.name).toBe('Head Wear');
+ });
+
+ it('accepts a bare string option and defaults its weight and prompt', () => {
+ const [layer] = normalizeLayers([{ name: 'Aura', options: ['Ember'] }]);
+ expect(layer.options[0]).toEqual({ value: 'Ember', weight: 1, prompt: 'Ember' });
+ });
+
+ it('keeps an explicit prompt fragment distinct from the trait value', () => {
+ const outfit = LAYERS.find((l) => l.key === 'outfit');
+ const bomber = outfit.options.find((o) => o.value === 'Bomber Jacket');
+ expect(bomber.prompt).toBe('wearing a worn leather bomber jacket');
+ });
+
+ it('rejects an empty layer list', () => {
+ expect(() => normalizeLayers([])).toThrow(DropSpecError);
+ });
+
+ it('rejects duplicate layer keys', () => {
+ expect(() =>
+ normalizeLayers([
+ { name: 'Aura', options: ['A'] },
+ { name: 'aura', options: ['B'] },
+ ]),
+ ).toThrow(/duplicate trait layer key/);
+ });
+
+ it('rejects a repeated option value within one layer', () => {
+ expect(() => normalizeLayers([{ name: 'Aura', options: ['Ember', 'ember'] }])).toThrow(
+ /repeats the option/,
+ );
+ });
+
+ it('rejects a zero or negative weight', () => {
+ expect(() => normalizeLayers([{ name: 'Aura', options: [{ value: 'X', weight: 0 }] }])).toThrow(
+ /weight above zero/,
+ );
+ });
+
+ it('rejects a layer with no options', () => {
+ expect(() => normalizeLayers([{ name: 'Aura', options: [] }])).toThrow(/at least one option/);
+ });
+
+ it('enforces the layer and option ceilings', () => {
+ const tooManyLayers = Array.from({ length: MAX_LAYERS + 1 }, (_, i) => ({
+ name: `L${i}`,
+ options: ['x'],
+ }));
+ expect(() => normalizeLayers(tooManyLayers)).toThrow(/at most/);
+
+ const tooManyOptions = Array.from({ length: MAX_OPTIONS_PER_LAYER + 1 }, (_, i) => `opt${i}`);
+ expect(() => normalizeLayers([{ name: 'Aura', options: tooManyOptions }])).toThrow(/max/);
+ });
+});
+
+describe('rollItem determinism', () => {
+ it('is reproducible for the same seed and index', () => {
+ const a = rollItem({ seed: 'seed-alpha', index: 7, layers: LAYERS });
+ const b = rollItem({ seed: 'seed-alpha', index: 7, layers: LAYERS });
+ expect(a).toEqual(b);
+ });
+
+ it('produces different traits for different indexes', () => {
+ const rolls = new Set();
+ for (let i = 0; i < 40; i++) {
+ rolls.add(JSON.stringify(rollItem({ seed: 'seed-alpha', index: i, layers: LAYERS }).traits));
+ }
+ expect(rolls.size).toBeGreaterThan(1);
+ });
+
+ it('produces different traits for a different seed', () => {
+ const a = rollItem({ seed: 'seed-alpha', index: 3, layers: LAYERS });
+ const b = rollItem({ seed: 'seed-beta', index: 3, layers: LAYERS });
+ expect(a.traits).not.toEqual(b.traits);
+ });
+
+ it('emits one trait per layer, in layer order', () => {
+ const { traits } = rollItem({ seed: 's', index: 0, layers: LAYERS });
+ expect(traits.map((t) => t.layer)).toEqual(['species', 'outfit', 'aura']);
+ });
+
+ it('is unaffected by the order the layers are passed in', () => {
+ const reordered = [LAYERS[2], LAYERS[0], LAYERS[1]];
+ const straight = rollItem({ seed: 's', index: 11, layers: LAYERS }).traits;
+ const shuffled = rollItem({ seed: 's', index: 11, layers: reordered }).traits;
+ for (const t of straight) {
+ expect(shuffled.find((x) => x.layer === t.layer).value).toBe(t.value);
+ }
+ });
+
+ it('leaves existing layers untouched when a new layer is appended', () => {
+ const before = rollItem({ seed: 's', index: 5, layers: LAYERS }).traits;
+ const extended = [...LAYERS, ...normalizeLayers([{ name: 'Backdrop', options: ['Void', 'Sun'] }])];
+ const after = rollItem({ seed: 's', index: 5, layers: extended }).traits;
+ expect(after.slice(0, LAYERS.length)).toEqual(before);
+ expect(after).toHaveLength(LAYERS.length + 1);
+ });
+});
+
+describe('pickWeighted', () => {
+ const options = [
+ { value: 'A', weight: 1 },
+ { value: 'B', weight: 3 },
+ ];
+
+ it('splits the interval by cumulative weight', () => {
+ expect(pickWeighted(options, 0).value).toBe('A');
+ expect(pickWeighted(options, 0.2).value).toBe('A');
+ expect(pickWeighted(options, 0.3).value).toBe('B');
+ expect(pickWeighted(options, 0.99).value).toBe('B');
+ });
+
+ it('never falls off the end of the option list', () => {
+ expect(pickWeighted(options, 1).value).toBe('B');
+ expect(pickWeighted(options, 1.5).value).toBe('B');
+ expect(pickWeighted(options, -1).value).toBe('A');
+ });
+
+ it('honours the declared weights across a large sample', () => {
+ let b = 0;
+ const n = 4000;
+ for (let i = 0; i < n; i++) if (pickWeighted(options, i / n).value === 'B') b++;
+ expect(b / n).toBeCloseTo(0.75, 2);
+ });
+});
+
+describe('rollSupply and rarity', () => {
+ const supply = 500;
+ const items = rollSupply({ seed: 'provenance-1', supply, layers: LAYERS });
+
+ it('rolls exactly the requested supply, indexed from zero', () => {
+ expect(items).toHaveLength(supply);
+ expect(items[0].index).toBe(0);
+ expect(items[supply - 1].index).toBe(supply - 1);
+ });
+
+ it('ranks every item uniquely from 1..supply', () => {
+ const ranks = items.map((i) => i.rarity_rank).sort((a, b) => a - b);
+ expect(ranks[0]).toBe(1);
+ expect(ranks[supply - 1]).toBe(supply);
+ expect(new Set(ranks).size).toBe(supply);
+ });
+
+ it('scores a rarer trait combination above a common one', () => {
+ const dragon = items.find((i) => i.traits.some((t) => t.value === 'Dragon'));
+ const fox = items.find((i) => i.traits.some((t) => t.value === 'Fox'));
+ expect(dragon.rarity_score).toBeGreaterThan(fox.rarity_score);
+ });
+
+ it('assigns tiers by percentile, with legendary the scarcest', () => {
+ const tiers = new Set(items.map((i) => i.rarity_tier));
+ expect(tiers.has('legendary')).toBe(true);
+ expect(tiers.has('common')).toBe(true);
+ const legendary = items.filter((i) => i.rarity_tier === 'legendary');
+ expect(legendary.length).toBeLessThanOrEqual(Math.ceil(supply * 0.01));
+ for (const item of legendary) expect(item.rarity_rank).toBeLessThanOrEqual(supply * 0.01);
+ });
+
+ it('respects the declared weights in the rolled distribution', () => {
+ const species = items.map((i) => i.traits.find((t) => t.layer === 'species').value);
+ const share = (v) => species.filter((s) => s === v).length / supply;
+ expect(share('Fox')).toBeCloseTo(0.6, 1);
+ expect(share('Dragon')).toBeCloseTo(0.1, 1);
+ });
+
+ it('reproduces the identical supply on a second run', () => {
+ const again = rollSupply({ seed: 'provenance-1', supply, layers: LAYERS });
+ expect(again).toEqual(items);
+ });
+
+ it('accepts raw un-normalized layers', () => {
+ const raw = rollSupply({
+ seed: 's',
+ supply: 4,
+ layers: [{ name: 'Aura', options: ['Ember', 'Frost'] }],
+ });
+ expect(raw).toHaveLength(4);
+ expect(raw[0].traits[0].layer).toBe('aura');
+ });
+});
+
+describe('tierForRank', () => {
+ it('maps the percentile bands', () => {
+ expect(tierForRank(1, 1000)).toBe('legendary');
+ expect(tierForRank(10, 1000)).toBe('legendary');
+ expect(tierForRank(11, 1000)).toBe('epic');
+ expect(tierForRank(100, 1000)).toBe('epic');
+ expect(tierForRank(350, 1000)).toBe('rare');
+ expect(tierForRank(351, 1000)).toBe('common');
+ expect(tierForRank(1000, 1000)).toBe('common');
+ });
+
+ it('degrades safely on an empty supply', () => {
+ expect(tierForRank(1, 0)).toBe('common');
+ });
+});
+
+describe('scoreRarity', () => {
+ it('breaks ties by index so the ranking is total', () => {
+ const flat = [
+ { index: 2, traits: [{ layer: 'a', value: 'x' }] },
+ { index: 0, traits: [{ layer: 'a', value: 'x' }] },
+ { index: 1, traits: [{ layer: 'a', value: 'x' }] },
+ ];
+ const scored = scoreRarity(flat);
+ expect(scored.find((i) => i.index === 0).rarity_rank).toBe(1);
+ expect(scored.find((i) => i.index === 1).rarity_rank).toBe(2);
+ expect(scored.find((i) => i.index === 2).rarity_rank).toBe(3);
+ });
+});
+
+describe('traitDistribution', () => {
+ const items = rollSupply({ seed: 'dist', supply: 200, layers: LAYERS });
+ const dist = traitDistribution(items, LAYERS);
+
+ it('reports one bucket per layer', () => {
+ expect(dist.map((d) => d.layer)).toEqual(['species', 'outfit', 'aura']);
+ });
+
+ it('sums each layer to the full supply', () => {
+ for (const layer of dist) {
+ expect(layer.values.reduce((n, v) => n + v.count, 0)).toBe(200);
+ }
+ });
+
+ it('sorts scarcest first', () => {
+ const species = dist.find((d) => d.layer === 'species');
+ expect(species.values[0].value).toBe('Dragon');
+ });
+
+ it('reports share as a fraction of supply', () => {
+ const species = dist.find((d) => d.layer === 'species');
+ for (const v of species.values) expect(v.share).toBeCloseTo(v.count / 200, 4);
+ });
+});
+
+describe('provenanceHash', () => {
+ const spec = { seed: 'abc', supply: 100, style: 'clay dinosaur', layers: LAYERS };
+
+ it('is stable across calls', () => {
+ expect(provenanceHash(spec)).toBe(provenanceHash(spec));
+ });
+
+ it('is a sha256 hex digest', () => {
+ expect(provenanceHash(spec)).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ it('changes when the seed changes', () => {
+ expect(provenanceHash({ ...spec, seed: 'abd' })).not.toBe(provenanceHash(spec));
+ });
+
+ it('changes when a weight changes', () => {
+ const tweaked = normalizeLayers([{ name: 'Species', options: [{ value: 'Fox', weight: 61 }] }]);
+ expect(provenanceHash({ ...spec, layers: tweaked })).not.toBe(provenanceHash(spec));
+ });
+
+ it('does not depend on key insertion order', () => {
+ const reordered = { layers: LAYERS, style: spec.style, supply: spec.supply, seed: spec.seed };
+ expect(provenanceHash(reordered)).toBe(provenanceHash(spec));
+ });
+});
+
+describe('verifyItem', () => {
+ it('confirms an untampered item', () => {
+ const item = rollItem({ seed: 'v', index: 9, layers: LAYERS });
+ expect(verifyItem({ seed: 'v', index: 9, layers: LAYERS, traits: item.traits }).ok).toBe(true);
+ });
+
+ it('catches a dropped trait', () => {
+ const item = rollItem({ seed: 'v', index: 9, layers: LAYERS });
+ expect(
+ verifyItem({ seed: 'v', index: 9, layers: LAYERS, traits: item.traits.slice(1) }).ok,
+ ).toBe(false);
+ });
+
+ it('catches a swapped trait value', () => {
+ const item = rollItem({ seed: 'v', index: 9, layers: LAYERS });
+ const other = ['Fox', 'Wolf', 'Dragon'].find((v) => v !== item.traits[0].value);
+ const tampered = item.traits.map((t, i) => (i === 0 ? { ...t, value: other } : t));
+ expect(verifyItem({ seed: 'v', index: 9, layers: LAYERS, traits: tampered }).ok).toBe(false);
+ });
+
+ it('treats a missing trait array as a failed verification', () => {
+ expect(verifyItem({ seed: 'v', index: 0, layers: LAYERS, traits: null }).ok).toBe(false);
+ });
+});
+
+describe('itemPrompt', () => {
+ const traits = [
+ { layer: 'aura', value: 'Ember' },
+ { layer: 'species', value: 'Fox' },
+ { layer: 'outfit', value: 'Bomber Jacket' },
+ ];
+
+ it('leads with the base style and follows in layer order', () => {
+ const prompt = itemPrompt({ style: 'stylized clay creature', traits, layers: LAYERS });
+ expect(prompt.startsWith('stylized clay creature, ')).toBe(true);
+ expect(prompt.indexOf('Fox')).toBeLessThan(prompt.indexOf('bomber jacket'));
+ expect(prompt.indexOf('bomber jacket')).toBeLessThan(prompt.indexOf('Ember'));
+ });
+
+ it('substitutes an option prompt fragment for the raw value', () => {
+ const prompt = itemPrompt({ style: 'x', traits, layers: LAYERS });
+ expect(prompt).toContain('wearing a worn leather bomber jacket');
+ expect(prompt).not.toContain('Bomber Jacket');
+ });
+
+ it('appends the riggability hints every item needs', () => {
+ const prompt = itemPrompt({ style: 'x', traits, layers: LAYERS });
+ expect(prompt).toContain('full body character');
+ expect(prompt).toContain('neutral A-pose');
+ });
+
+ it('stays within the generator prompt ceiling', () => {
+ const long = 'a'.repeat(2000);
+ expect(itemPrompt({ style: long, traits, layers: LAYERS }).length).toBeLessThanOrEqual(900);
+ });
+});
+
+describe('assertSupply', () => {
+ it('accepts the boundaries', () => {
+ expect(assertSupply(1)).toBe(1);
+ expect(assertSupply(MAX_SUPPLY)).toBe(MAX_SUPPLY);
+ });
+
+ it('rejects zero, fractions, and anything over the ceiling', () => {
+ expect(() => assertSupply(0)).toThrow(DropSpecError);
+ expect(() => assertSupply(1.5)).toThrow(DropSpecError);
+ expect(() => assertSupply(MAX_SUPPLY + 1)).toThrow(DropSpecError);
+ expect(() => assertSupply('many')).toThrow(DropSpecError);
+ });
+});
+
+describe('slugify', () => {
+ it('lowercases, collapses separators, and trims', () => {
+ expect(slugify(' Clay Dinos!! 2026 ')).toBe('clay-dinos-2026');
+ });
+
+ it('returns an empty string when nothing survives', () => {
+ expect(slugify('!!!')).toBe('');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 715dff3e0..97e8ab7cc 100644
--- a/vercel.json
+++ b/vercel.json
@@ -933,6 +933,14 @@
"src": "/launches/?",
"dest": "/launches.html"
},
+ {
+ "src": "/drops/?$",
+ "dest": "/drops.html"
+ },
+ {
+ "src": "/drops/([a-z0-9][a-z0-9-]*)/?$",
+ "dest": "/drop-collection.html"
+ },
{
"src": "/minted/?",
"dest": "/minted.html"
diff --git a/vite.config.js b/vite.config.js
index 95fdd6c50..62a971195 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -539,6 +539,8 @@ const appConfig = {
herald: resolve(__dirname, 'src/herald-embed.js'),
'nav-tier-badge': resolve(__dirname, 'src/nav-tier-badge.js'),
i18n: resolve(__dirname, 'src/i18n.js'),
+ drops: resolve(__dirname, 'pages/drops.html'),
+ 'drop-collection': resolve(__dirname, 'pages/drop-collection.html'),
app: resolve(__dirname, 'pages/app.html'),
proof: resolve(__dirname, 'pages/proof.html'),
stream: resolve(__dirname, 'pages/stream.html'),
@@ -1434,6 +1436,8 @@ const appConfig = {
'/pill/': resolve(root, 'pages/pill.html'),
'/portfolio': resolve(root, 'pages/portfolio.html'),
'/portfolio/': resolve(root, 'pages/portfolio.html'),
+ '/drops': resolve(root, 'pages/drops.html'),
+ '/drops/': resolve(root, 'pages/drops.html'),
'/airdrops': resolve(root, 'pages/airdrops.html'),
'/airdrops/': resolve(root, 'pages/airdrops.html'),
'/launcher': resolve(root, 'pages/launcher.html'),
@@ -2142,6 +2146,11 @@ const appConfig = {
/^\/markets\/robinhood\/coin\/0x[0-9a-fA-F]{40}\/?$/.test(path)
)
filePath = resolve(root, 'pages/robinhood-coin.html');
+ // /drops/:slug → one generative 3D collection. Declared ahead of the
+ // /drop/:id rule below so the singular sealed-gift route and this
+ // plural collection route can never shadow each other.
+ else if (!filePath && /^\/drops\/[a-z0-9][a-z0-9-]{1,47}\/?$/.test(path))
+ filePath = resolve(root, 'pages/drop-collection.html');
// /drop/:id → sealed wallet gift claim page (24 lowercase hex chars,
// matching api/vanity/drops.js's id format)
else if (!filePath && /^\/drop\/[0-9a-f]{24}\/?$/.test(path))