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(launch): rebuild /launch on a tested launch model, replace the X announcement pipeline with the @trythreews content queue, and drop Granite production claims from partner docs

Nicholasc619228be112
diff --git a/.env.example b/.env.example
index 7697bb26c..d174d73e0 100644
--- a/.env.example
+++ b/.env.example
@@ -1490,11 +1490,12 @@ X_API_SECRET=
X_ACCESS_TOKEN=
X_ACCESS_SECRET=
-# Autonomous @trythreews announcement queue. Keep the switch false until the
-# review queue, X media upload, and R2 state have passed a production dry run.
-X_ANNOUNCEMENT_AUTO_PUBLISH=false
-X_ANNOUNCEMENT_STATE_BUCKET=
-X_ANNOUNCEMENT_STATE_KEY=state/x-announcements.json
+# @trythreews content queue (data/x-content/queue.json, /api/cron/x-content).
+# Unset or false: every cron tick previews the next item without posting. Set
+# true on the Cloud Run service only after the owner approves auto-publishing.
+# Posting uses the X_API_KEY / X_API_SECRET / X_ACCESS_TOKEN / X_ACCESS_SECRET
+# app credentials; the publish ledger lives in the app_settings table.
+X_CONTENT_AUTO_PUBLISH=false
# Telegram bot — used by /api/pump/deliver-telegram to push pump.fun signals
# to subscriber chats. Without it the endpoint 500s.
diff --git a/.github/workflows/x-announcements.yml b/.github/workflows/x-announcements.yml
deleted file mode 100644
index 795e8079a..000000000
--- a/.github/workflows/x-announcements.yml
+++ /dev/null
@@ -1,65 +0,0 @@
-name: X announcements
-
-on:
- workflow_dispatch:
- inputs:
- dry_run:
- description: Preview the next approved item without posting
- required: true
- default: true
- type: boolean
- schedule:
- - cron: '7 14 * * *'
- - cron: '13 19 * * *'
- - cron: '19 0 * * *'
-
-concurrency:
- group: x-announcements-trythreews
- cancel-in-progress: false
-
-permissions:
- contents: read
-
-jobs:
- validate:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-node@v4
- with:
- node-version-file: .nvmrc
- cache: npm
- - run: npm ci --ignore-scripts
- - run: npm run x:announce:check
-
- publish:
- needs: validate
- if: >-
- (github.event_name == 'workflow_dispatch' && inputs.dry_run) ||
- (github.event_name == 'schedule' && vars.X_ANNOUNCEMENT_AUTO_PUBLISH == 'true') ||
- (github.event_name == 'workflow_dispatch' && !inputs.dry_run && vars.X_ANNOUNCEMENT_AUTO_PUBLISH == 'true')
- runs-on: ubuntu-latest
- environment: x-production
- steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-node@v4
- with:
- node-version-file: .nvmrc
- cache: npm
- - run: npm ci --ignore-scripts
- - name: Preview next approved announcement
- if: github.event_name == 'workflow_dispatch' && inputs.dry_run
- run: npm run x:announce:run -- --dry-run
- - name: Publish one due announcement
- if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && !inputs.dry_run)
- run: npm run x:announce:run
- env:
- X_API_KEY: ${{ secrets.X_API_KEY }}
- X_API_SECRET: ${{ secrets.X_API_SECRET }}
- X_ACCESS_TOKEN: ${{ secrets.X_ACCESS_TOKEN }}
- X_ACCESS_SECRET: ${{ secrets.X_ACCESS_SECRET }}
- R2_ACCOUNT_ID: ${{ secrets.R2_ACCOUNT_ID }}
- R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
- R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
- X_ANNOUNCEMENT_STATE_BUCKET: ${{ secrets.X_ANNOUNCEMENT_STATE_BUCKET }}
- X_ANNOUNCEMENT_STATE_KEY: state/x-announcements.json
diff --git a/.gitignore b/.gitignore
index 1063dd281..424d0b9c8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -644,5 +644,3 @@ docs/ops/npm-publish-status.md
# Packaged VS Code extensions belong on GitHub Releases, not in Git history.
*.vsix
HSO6cvibUAATRw9.jpg
-# Local X announcement publish ledger (production uses R2).
-.x-announcement-state.json
diff --git a/api/_lib/pump-launch-tx.js b/api/_lib/pump-launch-tx.js
index 4b3df2bce..38c4388cd 100644
--- a/api/_lib/pump-launch-tx.js
+++ b/api/_lib/pump-launch-tx.js
@@ -42,11 +42,12 @@ export const PUMP_LOOKUP_TABLES = Object.freeze({
devnet: '7y3623xaVQzsLxHRyp1wQD4Pmer5JjgbaagGFAEqCjua',
});
-// A simulated createV2 + dev buy + fee transfer consumed ~205k CU and loaded
-// 14.4 MB of account data on mainnet. v1 carries these as hard caps (an unset
-// cap is zero, not a default), so leave real headroom on both.
+// Simulated on mainnet: a SOL createV2 + dev buy + fee transfer consumed ~189k CU,
+// a USDC-quoted one ~346k, and a launch loaded ~14.4 MB of account data. v1
+// carries these as hard caps (an unset cap is zero, not a default) and the
+// priority fee is a flat total, so generous caps cost nothing extra.
export const LAUNCH_V1_CONFIG = Object.freeze({
- computeUnitLimit: 400_000,
+ computeUnitLimit: 800_000,
loadedAccountsDataSizeLimit: 32 * 1024 * 1024,
priorityFeeLamports: 10_000n,
});
diff --git a/api/_lib/three-brand.js b/api/_lib/three-brand.js
index 4b29c14e5..e84a1dfe6 100644
--- a/api/_lib/three-brand.js
+++ b/api/_lib/three-brand.js
@@ -394,6 +394,13 @@ export function buildTokenMetadata(t) {
{ trait_type: 'Platform', value: THREE_WS.name },
{ trait_type: 'Launchpad', value: 'pump.fun' },
{ trait_type: '$THREE', value: tok.mint },
+ ...(t.agentUrl ? [{ trait_type: '3D Agent', value: t.agentUrl }] : []),
+ ];
+ // The coin's 3D agent travels with it: the agent page, plus the avatar GLB as
+ // the standard `animation_url` (wallets and explorers that render 3D read it).
+ const files = [
+ ...(t.image ? [{ uri: t.image, type: 'image/png' }] : []),
+ ...(t.agentModelUrl ? [{ uri: t.agentModelUrl, type: 'model/gltf-binary' }] : []),
];
const json = {
@@ -408,12 +415,14 @@ export function buildTokenMetadata(t) {
telegram,
// Standard + brand extras (explorers/wallets read these; pump ignores them)
external_url: website,
+ ...(t.agentModelUrl ? { animation_url: t.agentModelUrl } : {}),
attributes,
properties: {
category: 'image',
- ...(t.image ? { files: [{ uri: t.image, type: 'image/png' }] } : {}),
+ ...(files.length ? { files } : {}),
creators: creators(t.creatorAddress),
},
+ ...(t.agentUrl ? { agent: { url: t.agentUrl, ...(t.agentModelUrl ? { model: t.agentModelUrl } : {}) } } : {}),
platform: {
name: THREE_WS.name,
url: THREE_WS.website,
diff --git a/api/_lib/x-content/articles.js b/api/_lib/x-content/articles.js
new file mode 100644
index 000000000..ce02ab04f
--- /dev/null
+++ b/api/_lib/x-content/articles.js
@@ -0,0 +1,272 @@
+// Markdown to X Article content_state.
+//
+// X's Articles API (POST /2/articles/draft) takes a DraftJS-style body: an
+// ordered list of blocks (paragraphs, headings, list items, quotes, atomic
+// embeds) plus an entities array those blocks point into. Articles are authored
+// as Markdown in data/x-content/articles/, so they diff cleanly in review and
+// the same file can be rendered anywhere else; this module is the one place
+// that turns that Markdown into the wire format.
+//
+// Mapping:
+// # / ## / ###+ header-one / header-two / header-three
+// paragraph unstyled, with bold / italic / strikethrough ranges
+// [text](url) link entity over the range
+// - item / 1. item unordered-list-item / ordered-list-item
+// > quote blockquote
+// ![caption](path) atomic block + image entity (uploaded at publish)
+// --- atomic block + divider entity
+// ```code``` and tables atomic block + markdown entity (X renders both)
+//
+// Offsets are JavaScript string indexes, matching the DraftJS composer.
+
+import { dirname, normalize } from 'node:path';
+import { marked } from 'marked';
+import { parse as parseHtml } from 'node-html-parser';
+
+export const MARKDOWN_ENTITY_BUDGET = 10_000;
+
+// Decode character references (&, ') without letting the parser eat
+// literal angle-bracket text such as `<agent-3d>`.
+const decode = (value) => parseHtml(`<p>${String(value || '').replace(/</g, '&lt;')}</p>`).textContent;
+
+const HEADER = { 1: 'header-one', 2: 'header-two' };
+
+class ContentStateBuilder {
+ constructor(resolveImage) {
+ this.blocks = [];
+ this.entities = [];
+ this.images = [];
+ this.markdownWeight = 0;
+ this.warnings = [];
+ this.resolveImage = resolveImage;
+ }
+
+ entity(type, mutability, data) {
+ this.entities.push({ key: String(this.entities.length), value: { type, mutability, data } });
+ return this.entities.length - 1;
+ }
+
+ text(type, runs) {
+ let text = '';
+ const inline_style_ranges = [];
+ const entity_ranges = [];
+ let link = null;
+ const closeLink = () => {
+ if (!link) return;
+ const key = this.entity('link', 'mutable', { url: link.url });
+ entity_ranges.push({ key, offset: link.offset, length: text.length - link.offset });
+ link = null;
+ };
+ for (const run of runs) {
+ if (!run.text) continue;
+ if (link && link.url !== run.href) closeLink();
+ if (run.href && !link) link = { url: run.href, offset: text.length };
+ const offset = text.length;
+ text += run.text;
+ for (const style of ['bold', 'italic', 'strikethrough']) {
+ if (run[style]) inline_style_ranges.push({ offset, length: run.text.length, style });
+ }
+ }
+ closeLink();
+ const trimmed = text.replace(/\s+$/, '');
+ if (!trimmed.trim()) return;
+ const block = { type, text: trimmed };
+ if (inline_style_ranges.length) block.inline_style_ranges = mergeRanges(inline_style_ranges, trimmed.length);
+ const ranges = entity_ranges
+ .map((range) => ({ ...range, length: Math.min(range.length, trimmed.length - range.offset) }))
+ .filter((range) => range.length > 0);
+ if (ranges.length) block.entity_ranges = ranges;
+ this.blocks.push(block);
+ }
+
+ atomic(type, mutability, data, text = ' ') {
+ const key = this.entity(type, mutability, data);
+ this.blocks.push({ type: 'atomic', text, entity_ranges: [{ key, offset: 0, length: text.length }] });
+ return key;
+ }
+
+ image(href, caption) {
+ const path = this.resolveImage(href);
+ if (!path) {
+ this.warnings.push(`image ${href} is not a local file under public/ or data/; it was left out`);
+ return;
+ }
+ const data = { media_items: [] };
+ if (caption) data.caption = caption;
+ const entityIndex = this.atomic('image', 'immutable', data);
+ this.images.push({ entityIndex, path, caption });
+ }
+
+ markdown(source) {
+ this.markdownWeight += source.length;
+ this.atomic('markdown', 'mutable', { markdown: source });
+ }
+}
+
+// DraftJS stores one range per styled span; collapse adjacent spans of the same
+// style that the tokenizer split across text nodes.
+function mergeRanges(ranges, limit) {
+ const sorted = [...ranges].sort((a, b) => a.style.localeCompare(b.style) || a.offset - b.offset);
+ const merged = [];
+ for (const range of sorted) {
+ const previous = merged[merged.length - 1];
+ if (previous && previous.style === range.style && previous.offset + previous.length === range.offset) previous.length += range.length;
+ else merged.push({ ...range });
+ }
+ return merged
+ .map((range) => ({ ...range, length: Math.min(range.length, limit - range.offset) }))
+ .filter((range) => range.length > 0);
+}
+
+function inlineRuns(tokens, style = {}) {
+ const runs = [];
+ for (const token of tokens || []) {
+ switch (token.type) {
+ case 'strong':
+ runs.push(...inlineRuns(token.tokens, { ...style, bold: true }));
+ break;
+ case 'em':
+ runs.push(...inlineRuns(token.tokens, { ...style, italic: true }));
+ break;
+ case 'del':
+ runs.push(...inlineRuns(token.tokens, { ...style, strikethrough: true }));
+ break;
+ case 'link':
+ runs.push(...inlineRuns(token.tokens, { ...style, href: token.href }));
+ break;
+ case 'br':
+ runs.push({ ...style, text: '\n' });
+ break;
+ case 'codespan':
+ runs.push({ ...style, text: decode(token.text) });
+ break;
+ case 'html':
+ // Articles have no HTML. A line break tag is a break; anything else
+ // (an element name written in prose, like <agent-3d>) is literal text.
+ runs.push({ ...style, text: /^<br\s*\/?>$/i.test(token.text.trim()) ? '\n' : token.text });
+ break;
+ case 'text':
+ if (token.tokens?.length) runs.push(...inlineRuns(token.tokens, style));
+ else runs.push({ ...style, text: decode(token.text) });
+ break;
+ case 'escape':
+ runs.push({ ...style, text: token.text });
+ break;
+ default:
+ if (token.tokens) runs.push(...inlineRuns(token.tokens, style));
+ else if (token.text) runs.push({ ...style, text: decode(token.text) });
+ }
+ }
+ return runs;
+}
+
+// A paragraph may mix prose with images. Images become their own atomic blocks
+// in reading order; the prose around them stays a paragraph.
+function paragraph(builder, tokens, type = 'unstyled') {
+ let pending = [];
+ const flush = () => {
+ builder.text(type, inlineRuns(pending));
+ pending = [];
+ };
+ for (const token of tokens || []) {
+ if (token.type === 'image') {
+ flush();
+ builder.image(token.href, decode(token.text));
+ } else {
+ pending.push(token);
+ }
+ }
+ flush();
+}
+
+function list(builder, token) {
+ const type = token.ordered ? 'ordered-list-item' : 'unordered-list-item';
+ for (const item of token.items) {
+ const inline = [];
+ for (const child of item.tokens || []) {
+ if (child.type === 'list') {
+ if (inline.length) builder.text(type, inlineRuns(inline.splice(0)));
+ list(builder, child);
+ } else if (child.type === 'text' || child.type === 'paragraph') {
+ if (inline.length) inline.push({ type: 'br' });
+ inline.push(...(child.tokens || [{ type: 'text', text: child.text }]));
+ }
+ }
+ if (inline.length) builder.text(type, inlineRuns(inline));
+ }
+}
+
+function walk(builder, tokens, context = null) {
+ for (const token of tokens) {
+ switch (token.type) {
+ case 'space':
+ break;
+ case 'heading':
+ builder.text(HEADER[token.depth] || 'header-three', inlineRuns(token.tokens));
+ break;
+ case 'paragraph':
+ paragraph(builder, token.tokens, context || 'unstyled');
+ break;
+ case 'text':
+ paragraph(builder, token.tokens || [{ type: 'text', text: token.text }], context || 'unstyled');
+ break;
+ case 'blockquote':
+ walk(builder, token.tokens, 'blockquote');
+ break;
+ case 'list':
+ list(builder, token);
+ break;
+ case 'hr':
+ builder.atomic('divider', 'immutable', {});
+ break;
+ case 'code':
+ builder.markdown(`\`\`\`${token.lang || ''}\n${token.text}\n\`\`\``);
+ break;
+ case 'table':
+ builder.markdown(token.raw.trim());
+ break;
+ case 'html': {
+ const text = token.text.trim();
+ if (text) builder.text(context || 'unstyled', [{ text }]);
+ break;
+ }
+ default:
+ builder.warnings.push(`unsupported markdown token ${token.type} was left out`);
+ }
+ }
+}
+
+// Image references resolve to repo paths the publisher can upload. `articlePath`
+// is the Markdown file's repo-relative path.
+export function imageResolver(articlePath) {
+ const base = dirname(articlePath);
+ return (href) => {
+ const ref = decodeURI(String(href || '').trim());
+ if (!ref || /^[a-z]+:/i.test(ref)) return null;
+ let path;
+ if (ref.startsWith('public/') || ref.startsWith('data/')) path = ref;
+ else if (ref.startsWith('/')) path = `public${ref}`;
+ else path = normalize(`${base}/${ref}`);
+ return path.startsWith('public/') || path.startsWith('data/') ? path : null;
+ };
+}
+
+export function markdownToContentState(markdown, { articlePath = 'data/x-content/articles/article.md' } = {}) {
+ const builder = new ContentStateBuilder(imageResolver(articlePath));
+ walk(builder, marked.lexer(String(markdown || '')));
+ return {
+ content_state: { blocks: builder.blocks, entities: builder.entities },
+ images: builder.images,
+ markdownWeight: builder.markdownWeight,
+ warnings: builder.warnings,
+ };
+}
+
+// Fill each image entity with its uploaded media id.
+export function attachArticleMedia(contentState, images, mediaIds) {
+ const entities = contentState.entities.map((entity) => structuredClone(entity));
+ images.forEach((image, index) => {
+ entities[image.entityIndex].value.data.media_items = [{ media_category: 'tweet_image', media_id: mediaIds[index] }];
+ });
+ return { blocks: contentState.blocks, entities };
+}
diff --git a/api/_lib/x-content/media.js b/api/_lib/x-content/media.js
new file mode 100644
index 000000000..b1f373e93
--- /dev/null
+++ b/api/_lib/x-content/media.js
@@ -0,0 +1,127 @@
+// Native media rules for X posts and Articles.
+//
+// Native uploads are the whole point: a bare link card reads as automation and
+// X ranks it below an image or clip that plays in the feed. Every attachment is
+// a file that ships inside the Cloud Run image (public/ or data/), so the cron
+// publishes exactly the bytes that were reviewed.
+//
+// Limits follow X's media upload documentation. Video is transcoded ahead of
+// time by `npm run x:content -- prepare-video`, which records the probe this
+// module validates, because the production image carries no ffmpeg.
+
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import { extname, resolve } from 'node:path';
+
+const MB = 1024 * 1024;
+
+export const MEDIA_ROOTS = ['public/', 'data/'];
+
+export const MEDIA_TYPES = {
+ '.jpg': { kind: 'image', mime: 'image/jpeg', maxBytes: 5 * MB },
+ '.jpeg': { kind: 'image', mime: 'image/jpeg', maxBytes: 5 * MB },
+ '.png': { kind: 'image', mime: 'image/png', maxBytes: 5 * MB },
+ '.webp': { kind: 'image', mime: 'image/webp', maxBytes: 5 * MB },
+ '.gif': { kind: 'gif', mime: 'image/gif', maxBytes: 15 * MB },
+ '.mp4': { kind: 'video', mime: 'video/mp4', maxBytes: 512 * MB },
+ '.mov': { kind: 'video', mime: 'video/quicktime', maxBytes: 512 * MB },
+};
+
+export const VIDEO_LIMITS = {
+ minDurationSec: 0.5,
+ maxDurationSec: 140,
+ minSide: 32,
+ maxWidth: 1920,
+ maxHeight: 1200,
+ maxFps: 60,
+ minAspect: 1 / 3,
+ maxAspect: 3,
+};
+
+export const MAX_ALT_TEXT = 1000;
+
+export const CATEGORY = { image: 'tweet_image', gif: 'tweet_gif', video: 'tweet_video' };
+
+export function mediaType(path) {
+ return MEDIA_TYPES[extname(String(path || '')).toLowerCase()] || null;
+}
+
+// Problems with a single attachment. `root` is the repo (or image) root.
+export function mediaProblems(media, root) {
+ const problems = [];
+ const path = String(media?.path || '');
+ if (!path) return ['media entry has no path'];
+ if (path.includes('..') || !MEDIA_ROOTS.some((prefix) => path.startsWith(prefix))) {
+ problems.push(`${path}: media must live under ${MEDIA_ROOTS.join(' or ')} so it ships in the production image`);
+ }
+ const type = mediaType(path);
+ if (!type) return [...problems, `${path}: unsupported format (use jpg, png, webp, gif, mp4, or mov)`];
+ const absolute = resolve(root, path);
+ if (!existsSync(absolute)) return [...problems, `${path}: file is missing`];
+
+ const bytes = statSync(absolute).size;
+ if (bytes > type.maxBytes) problems.push(`${path}: ${(bytes / MB).toFixed(1)} MB exceeds the ${type.maxBytes / MB} MB ${type.kind} limit`);
+
+ if (type.kind !== 'video') {
+ const alt = String(media.alt || '').trim();
+ if (!alt) problems.push(`${path}: needs alt text`);
+ if (alt.length > MAX_ALT_TEXT) problems.push(`${path}: alt text is ${alt.length} characters; X allows ${MAX_ALT_TEXT}`);
+ return problems;
+ }
+
+ const probe = media.probe;
+ if (!probe) {
+ problems.push(`${path}: video has no probe; run \`npm run x:content -- prepare-video\` so its duration and encoding are checked`);
+ return problems;
+ }
+ const L = VIDEO_LIMITS;
+ if (!(probe.durationSec >= L.minDurationSec && probe.durationSec <= L.maxDurationSec)) {
+ problems.push(`${path}: duration ${probe.durationSec}s is outside ${L.minDurationSec}-${L.maxDurationSec}s`);
+ }
+ if (probe.width < L.minSide || probe.height < L.minSide || probe.width > L.maxWidth || probe.height > L.maxHeight) {
+ problems.push(`${path}: ${probe.width}x${probe.height} is outside ${L.minSide}px to ${L.maxWidth}x${L.maxHeight}`);
+ }
+ const aspect = probe.width / probe.height;
+ if (!(aspect >= L.minAspect && aspect <= L.maxAspect)) problems.push(`${path}: aspect ratio ${aspect.toFixed(2)} is outside 1:3 to 3:1`);
+ if (probe.fps > L.maxFps) problems.push(`${path}: ${probe.fps} fps exceeds ${L.maxFps}`);
+ if (probe.videoCodec !== 'h264') problems.push(`${path}: video codec ${probe.videoCodec} must be h264`);
+ if (probe.pixFmt && probe.pixFmt !== 'yuv420p') problems.push(`${path}: pixel format ${probe.pixFmt} must be yuv420p`);
+ if (probe.audioCodec && probe.audioCodec !== 'aac') problems.push(`${path}: audio codec ${probe.audioCodec} must be aac`);
+ return problems;
+}
+
+// Attachment-set rules for one post: up to four images, or exactly one GIF or
+// one video.
+export function attachmentProblems(mediaList) {
+ const list = mediaList || [];
+ const kinds = list.map((media) => mediaType(media.path)?.kind).filter(Boolean);
+ const problems = [];
+ if (list.length > 4) problems.push('a post carries at most four images');
+ for (const kind of ['video', 'gif']) {
+ if (kinds.includes(kind) && list.length !== 1) problems.push(`a ${kind} must be the only attachment on its post`);
+ }
+ return problems;
+}
+
+export function readMedia(media, root) {
+ const type = mediaType(media.path);
+ return { buffer: readFileSync(resolve(root, media.path)), mime: type.mime, kind: type.kind, category: CATEGORY[type.kind] };
+}
+
+// Reads the probe fields mediaProblems checks out of `ffmpeg -i <file>` stderr.
+// The authoring CLI runs this right after encoding; production never does.
+export function parseFfmpegProbe(stderr) {
+ const duration = stderr.match(/Duration: (\d+):(\d+):([\d.]+)/);
+ const video = stderr.match(/Stream #\S+.*?: Video: (\w+)[^\n]*?, (\w+)(?:\([^)]*\))?, (\d+)x(\d+)[^\n]*?([\d.]+) fps/);
+ const audio = stderr.match(/Stream #\S+.*?: Audio: (\w+)/);
+ if (!duration || !video) return null;
+ const probe = {
+ durationSec: Math.round((Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3])) * 100) / 100,
+ width: Number(video[3]),
+ height: Number(video[4]),
+ fps: Number(video[5]),
+ videoCodec: video[1],
+ pixFmt: video[2],
+ };
+ if (audio) probe.audioCodec = audio[1];
+ return probe;
+}
diff --git a/api/_lib/x-content/publisher.js b/api/_lib/x-content/publisher.js
new file mode 100644
index 000000000..e7d8ab66c
--- /dev/null
+++ b/api/_lib/x-content/publisher.js
@@ -0,0 +1,135 @@
+// Publishes one queue item to X: a post or thread with native media, or an X
+// Article followed by posts that quote it.
+//
+// The client is a twitter-api-v2 `TwitterApi` authenticated as @trythreews with
+// OAuth 1.0a user context (X_API_KEY, X_API_SECRET, X_ACCESS_TOKEN,
+// X_ACCESS_SECRET). Only its v2 surface is used: chunked media upload, media
+// metadata for alt text, POST /2/tweets, and POST /2/articles/draft plus
+// /2/articles/:id/publish.
+//
+// `previewClient` records the exact calls a publish would make without touching
+// X, which is what `--dry-run` and the cron's preview mode print.
+
+import { loadArticle } from './queue.js';
+import { readMedia } from './media.js';
+import { attachArticleMedia } from './articles.js';
+
+// X expires an uploaded media id after 24 hours; re-upload past this age.
+const MEDIA_ID_TTL_MS = 23 * 60 * 60 * 1000;
+
+export async function xClientFromEnv(env = process.env) {
+ const creds = {
+ appKey: env.X_API_KEY,
+ appSecret: env.X_API_SECRET,
+ accessToken: env.X_ACCESS_TOKEN,
+ accessSecret: env.X_ACCESS_SECRET,
+ };
+ if (!(creds.appKey && creds.appSecret && creds.accessToken && creds.accessSecret)) return null;
+ const { TwitterApi } = await import('twitter-api-v2');
+ return new TwitterApi(creds).readWrite.v2;
+}
+
+export function previewClient() {
+ const calls = [];
+ let counter = 0;
+ const id = (label) => `preview-${label}-${++counter}`;
+ return {
+ calls,
+ async uploadMedia(buffer, options) {
+ calls.push({ call: 'media.upload', bytes: buffer.length, ...options });
+ return id('media');
+ },
+ async createMediaMetadata(mediaId, metadata) {
+ calls.push({ call: 'media.metadata', mediaId, alt: metadata.alt_text?.text });
+ },
+ async tweet(payload) {
+ calls.push({ call: 'tweets.create', ...payload });
+ return { data: { id: id('post'), text: payload.text } };
+ },
+ async post(path, body) {
+ calls.push({ call: `POST /2/${path}`, ...(body ? { body } : {}) });
+ if (path === 'articles/draft') return { data: { id: id('article'), title: body.title } };
+ return { data: { post_id: id('article-post') } };
+ },
+ };
+}
+
+async function uploadOnce({ client, root, media, progress, persist }) {
+ const cached = progress.media[media.path];
+ if (cached && Date.now() - cached.at < MEDIA_ID_TTL_MS) return cached.id;
+ const { buffer, mime, kind, category } = readMedia(media, root);
+ const mediaId = await client.uploadMedia(buffer, { media_type: mime, media_category: category });
+ const alt = String(media.alt || '').trim();
+ if (alt && kind !== 'video') await client.createMediaMetadata(mediaId, { alt_text: { text: alt } });
+ progress.media[media.path] = { id: mediaId, at: Date.now() };
+ await persist();
+ return mediaId;
+}
+
+async function publishPosts({ client, root, posts, progress, persist, quoteId = null }) {
+ for (let index = 0; index < posts.length; index++) {
+ if (progress.postIds[index]) continue;
+ const post = posts[index];
+ const mediaIds = [];
+ for (const media of post.media || []) mediaIds.push(await uploadOnce({ client, root, media, progress, persist }));
+ const payload = { text: post.text.trim() };
+ if (mediaIds.length) payload.media = { media_ids: mediaIds };
+ const replyTo = index === 0 ? null : progress.postIds[index - 1];
+ if (replyTo) payload.reply = { in_reply_to_tweet_id: replyTo };
+ if (index === 0 && quoteId) payload.quote_tweet_id = quoteId;
+ const { data } = await client.tweet(payload);
+ progress.postIds[index] = data.id;
+ await persist();
+ }
+}
+
+async function publishArticle({ client, root, item, progress, persist }) {
+ if (!progress.articlePostId) {
+ if (!progress.articleDraftId) {
+ const { content_state, images } = loadArticle(root, item.article);
+ const coverId = await uploadOnce({ client, root, media: { alt: item.article.title, ...item.article.cover }, progress, persist });
+ const imageIds = [];
+ for (const image of images) {
+ imageIds.push(await uploadOnce({ client, root, media: { path: image.path, alt: image.caption || item.article.title }, progress, persist }));
+ }
+ const { data } = await client.post('articles/draft', {
+ title: item.article.title.trim(),
+ content_state: attachArticleMedia(content_state, images, imageIds),
+ cover_media: { media_category: 'tweet_image', media_id: coverId },
+ });
+ progress.articleDraftId = data.id;
+ await persist();
+ }
+ const { data } = await client.post(`articles/${progress.articleDraftId}/publish`);
+ progress.articlePostId = data.post_id;
+ await persist();
+ }
+ if (item.posts?.length) await publishPosts({ client, root, posts: item.posts, progress, persist, quoteId: progress.articlePostId });
+}
+
+// Publishes `item`, resuming from state.inflight. Returns the ledger row.
+export async function publishItem({ item, client, root, state, store, account = 'trythreews' }) {
+ state.inflight ||= {};
+ const progress = (state.inflight[item.id] ||= { media: {}, postIds: [] });
+ const persist = () => store.save(state);
+
+ if (item.kind === 'article') await publishArticle({ client, root, item, progress, persist });
+ else await publishPosts({ client, root, posts: item.posts, progress, persist });
+
+ const leadId = progress.articlePostId || progress.postIds[0];
+ const row = {
+ id: item.id,
+ kind: item.kind,
+ lane: item.lane,
+ pattern: item.pattern,
+ publishedAt: new Date().toISOString(),
+ text: item.kind === 'article' ? item.article.title : item.posts[0].text,
+ postIds: progress.postIds,
+ url: `https://x.com/${account}/status/${leadId}`,
+ };
+ if (progress.articlePostId) row.articlePostId = progress.articlePostId;
+ state.published = [...(state.published || []), row];
+ delete state.inflight[item.id];
+ await persist();
+ return row;
+}
diff --git a/api/_lib/x-content/quality.js b/api/_lib/x-content/quality.js
index 5768b38f8..60e74d163 100644
--- a/api/_lib/x-content/quality.js
+++ b/api/_lib/x-content/quality.js
@@ -1,7 +1,17 @@
-const URL_RE = /(?:https?:\/\/|\b(?:www\.)?three\.ws\/)[^\s]+/gi;
+// Copy lint for @trythreews posts. The account should read like the people who
+// build three.ws wrote it, so the checks reject the tells that make a feed look
+// machine-generated: launch-deck openers, hype vocabulary, hashtags, emoji,
+// shouting, and a post that repeats an earlier one.
+const URL_PATTERN = String.raw`(?:https?:\/\/|\b(?:www\.)?three\.ws\/)[^\s]+`;
+const urlRe = (flags = '') => new RegExp(URL_PATTERN, flags);
+
+export const hasUrl = (value) => urlRe('i').test(String(value || ''));
+
+// X counts every URL as 23 characters (t.co wrapping) and each astral code
+// point (emoji, some CJK) as 2.
export const weightedLength = (value) =>
- [...String(value || '').replace(URL_RE, 'x'.repeat(23))].reduce(
+ [...String(value || '').replace(urlRe('gi'), 'x'.repeat(23))].reduce(
(total, char) => total + (char.codePointAt(0) > 0xffff ? 2 : 1),
0,
);
@@ -9,7 +19,7 @@ export const weightedLength = (value) =>
export function normalizeCopy(value) {
return String(value || '')
.toLowerCase()
- .replace(URL_RE, ' url ')
+ .replace(urlRe('gi'), ' url ')
.replace(/\$([a-z0-9]+)/g, '$1')
.replace(/[^a-z0-9@]+/g, ' ')
.trim();
@@ -46,6 +56,8 @@ export const BANNED_OPENINGS = [
/^ever wondered\b/i,
/^what if you could\b/i,
/^imagine a world\b/i,
+ /^a thread\b/i,
+ /^thread\b/i,
];
export const BANNED_PHRASES = [
@@ -59,22 +71,34 @@ export const BANNED_PHRASES = [
/\blet that sink in\b/i,
/\bhere'?s the kicker\b/i,
/\bsupercharge\b/i,
+ /\bdelve\b/i,
+ /\bin today'?s fast[- ]paced\b/i,
+ /\bbuckle up\b/i,
+ /\bstay tuned\b/i,
];
-export function copyProblems(text, { minimum = 100, maximum = 280 } = {}) {
+// Acronyms and tickers that are legitimately written in capitals.
+const ALLCAPS_TERMS = new Set(['THREE', 'HTTP', 'HTTPS', 'JSON', 'GLTF', 'USDC', 'HTML', 'WEBP', 'NVIDIA', 'OAUTH', 'MCP', 'GPU', 'GPUS']);
+
+// `minimum` applies to the head of a post; replies may be short. `requireUrl`
+// is false for parts whose item carries its link somewhere else (a reply, or a
+// quoted Article).
+export function copyProblems(text, { minimum = 100, maximum = 280, requireUrl = true } = {}) {
const problems = [];
const copy = String(text || '').trim();
const weight = weightedLength(copy);
if (!copy) problems.push('copy is empty');
if (weight < minimum) problems.push(`copy is ${weight} weighted characters; minimum is ${minimum}`);
if (weight > maximum) problems.push(`copy is ${weight} weighted characters; maximum is ${maximum}`);
- if (/#\w/.test(copy)) problems.push('hashtags are outside the @trythreews voice');
+ if (/(^|\s)#\w/.test(copy)) problems.push('hashtags are outside the @trythreews voice');
if (/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(copy)) problems.push('emoji are outside the @trythreews voice');
- if (/[\u2013\u2014]/.test(copy)) problems.push('en-dashes and em-dashes are banned');
- if (!URL_RE.test(copy)) problems.push('copy must link to its evidence or product surface');
- URL_RE.lastIndex = 0;
+ if (/[–—]/.test(copy)) problems.push('en-dashes and em-dashes are banned');
+ if (/!{2,}|(?:!.*){3,}/s.test(copy)) problems.push('stacked exclamation marks read as automated hype');
+ if ((copy.match(/\b[A-Z]{4,}\b/g) || []).filter((word) => !ALLCAPS_TERMS.has(word)).length > 1) {
+ problems.push('more than one all-caps word reads as shouting');
+ }
+ if (requireUrl && !hasUrl(copy)) problems.push('copy must link to its evidence or product surface');
for (const pattern of BANNED_OPENINGS) if (pattern.test(copy)) problems.push(`banned opening: ${pattern.source}`);
for (const pattern of BANNED_PHRASES) if (pattern.test(copy)) problems.push(`banned phrase: ${pattern.source}`);
return problems;
}
-
diff --git a/api/_lib/x-content/queue.js b/api/_lib/x-content/queue.js
new file mode 100644
index 000000000..6ba29eacf
--- /dev/null
+++ b/api/_lib/x-content/queue.js
@@ -0,0 +1,161 @@
+// The reviewed @trythreews content queue (data/x-content/queue.json) and its
+// validator. The CLI and the Cloud Scheduler cron both call validateQueue, so
+// "passes check locally" and "publishable in production" are the same rule.
+//
+// Problems are reported per item: one broken draft never blocks an approved
+// item behind it.
+
+import { existsSync, readdirSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { copyProblems, copySimilarity, hasUrl, weightedLength } from './quality.js';
+import { attachmentProblems, mediaProblems, mediaType } from './media.js';
+import { MARKDOWN_ENTITY_BUDGET, markdownToContentState } from './articles.js';
+
+export const QUEUE_PATH = 'data/x-content/queue.json';
+export const STATUSES = ['draft', 'review', 'approved', 'paused', 'posted'];
+export const KINDS = ['post', 'article'];
+export const MAX_ARTICLE_TITLE = 100;
+
+export function loadQueue(root, path = QUEUE_PATH) {
+ return JSON.parse(readFileSync(resolve(root, path), 'utf8'));
+}
+
+// Every post @trythreews has published that we hold a copy of: the scraped
+// archives plus the texts this pipeline recorded when it published.
+export function loadHistory(root, state = null) {
+ const texts = [];
+ const dir = resolve(root, 'data/archives');
+ if (existsSync(dir)) {
+ for (const name of readdirSync(dir).filter((file) => /^trythreews_tweets_.*\.json$/.test(file))) {
+ const payload = JSON.parse(readFileSync(resolve(dir, name), 'utf8'));
+ const rows = Array.isArray(payload) ? payload : payload.tweets || payload.data || [];
+ for (const row of rows) {
+ const text = row.text || row.full_text || row.tweet?.full_text || row.tweet?.text;
+ if (text) texts.push(String(text));
+ }
+ }
+ }
+ for (const row of state?.published || []) if (row.text) texts.push(row.text);
+ return texts;
+}
+
+export function loadArticle(root, article) {
+ const markdown = readFileSync(resolve(root, article.body), 'utf8');
+ return markdownToContentState(markdown, { articlePath: article.body });
+}
+
+function postProblems(item, root, { headMinimum, headNeedsUrl }) {
+ const problems = [];
+ const posts = item.posts || [];
+ const itemLinks = posts.some((post) => hasUrl(post.text));
+ if (headNeedsUrl && !itemLinks) problems.push('no post in this item links to its evidence or product surface');
+
+ posts.forEach((post, index) => {
+ const label = index === 0 ? 'head' : `reply ${index}`;
+ for (const problem of copyProblems(post.text, { minimum: index === 0 ? headMinimum : 1, requireUrl: false })) {
+ problems.push(`${label}: ${problem}`);
+ }
+ for (const problem of attachmentProblems(post.media)) problems.push(`${label}: ${problem}`);
+ for (const media of post.media || []) for (const problem of mediaProblems(media, root)) problems.push(`${label}: ${problem}`);
+ });
+ return problems;
+}
+
+function articleProblems(item, root) {
+ const problems = [];
+ const article = item.article;
+ if (!article) return ['article items need an `article` block with title, body, and cover'];
+ const title = String(article.title || '').trim();
+ if (!title) problems.push('article title is empty');
+ if (title.length > MAX_ARTICLE_TITLE) problems.push(`article title is ${title.length} characters; keep it under ${MAX_ARTICLE_TITLE}`);
+ if (/[–—]/.test(title)) problems.push('article title: en-dashes and em-dashes are banned');
+
+ if (!article.cover?.path) problems.push('article needs a cover image; X shows it on the card in every feed');
+ else {
+ if (mediaType(article.cover.path)?.kind !== 'image') problems.push('article cover must be a still image');
+ problems.push(...mediaProblems({ alt: title, ...article.cover }, root).map((problem) => `cover: ${problem}`));
+ }
+
+ const body = String(article.body || '');
+ if (!body.startsWith('data/x-content/articles/') || !body.endsWith('.md')) {
+ problems.push('article body must be a Markdown file under data/x-content/articles/');
+ return problems;
+ }
+ if (!existsSync(resolve(root, body))) return [...problems, `article body ${body} is missing`];
+
+ const converted = loadArticle(root, article);
+ const { blocks } = converted.content_state;
+ if (blocks.length < 3) problems.push(`article body has ${blocks.length} blocks; that is a post, not an Article`);
+ if (/[–—]/.test(blocks.map((block) => block.text).join('\n'))) problems.push('article body: en-dashes and em-dashes are banned');
+ if (converted.markdownWeight > MARKDOWN_ENTITY_BUDGET) {
+ problems.push(`code blocks and tables total ${converted.markdownWeight} characters; X allows ${MARKDOWN_ENTITY_BUDGET} per Article`);
+ }
+ for (const warning of converted.warnings) problems.push(`article body: ${warning}`);
+ for (const image of converted.images) {
+ if (mediaType(image.path)?.kind !== 'image') problems.push(`article image ${image.path} must be a still image`);
+ problems.push(...mediaProblems({ path: image.path, alt: image.caption || title }, root).map((problem) => `article image: ${problem}`));
+ }
+ return problems;
+}
+
+export function validateItem(item, root) {
+ const problems = [];
+ if (!/^[a-z0-9][a-z0-9-]{1,80}$/.test(String(item.id || ''))) problems.push('id must be a lowercase slug');
+ if (!STATUSES.includes(item.status)) problems.push(`status must be one of ${STATUSES.join(', ')}`);
+ if (!KINDS.includes(item.kind)) problems.push(`kind must be one of ${KINDS.join(', ')}`);
+ if (!item.lane || !item.pattern) problems.push('lane and pattern are required (they drive rotation)');
+ if (!Number.isFinite(Date.parse(item.notBefore))) problems.push('notBefore must be an ISO-8601 timestamp');
+
+ if (item.kind === 'post') {
+ if (!item.posts?.length) problems.push('a post item needs at least one post');
+ else {
+ if (!item.textOnly && !item.posts[0].media?.length) {
+ problems.push('head post has no media; attach an image, GIF, or video, or set "textOnly": true on purpose');
+ }
+ problems.push(...postProblems(item, root, { headMinimum: 100, headNeedsUrl: true }));
+ }
+ }
+ if (item.kind === 'article') {
+ problems.push(...articleProblems(item, root));
+ // Follow-up posts quote the published Article, so the Article itself is
+ // the link and the head may be short.
+ if (item.posts?.length) problems.push(...postProblems(item, root, { headMinimum: 40, headNeedsUrl: false }));
+ }
+ return problems;
+}
+
+export function headText(item) {
+ return item.kind === 'article' ? `${item.article?.title || ''}\n${item.posts?.[0]?.text || ''}` : item.posts?.[0]?.text || '';
+}
+
+export function validateQueue(queue, root, { state = null } = {}) {
+ const problems = {};
+ const notes = [];
+ const ids = new Set();
+ for (const item of queue.items || []) {
+ const list = validateItem(item, root);
+ if (ids.has(item.id)) list.push('id is duplicated');
+ ids.add(item.id);
+ problems[item.id] = list;
+ }
+
+ const live = (queue.items || []).filter((item) => item.status !== 'posted');
+ const queueLimit = Number(queue.quality?.queueSimilarityLimit ?? 0.34);
+ for (let left = 0; left < live.length; left++) {
+ for (let right = left + 1; right < live.length; right++) {
+ const score = copySimilarity(headText(live[left]), headText(live[right]));
+ if (score >= queueLimit) problems[live[right].id].push(`reads like ${live[left].id} (similarity ${score.toFixed(2)} >= ${queueLimit})`);
+ }
+ }
+
+ const history = loadHistory(root, state);
+ const publishedIds = new Set((state?.published || []).map((row) => row.id));
+ const archiveLimit = Number(queue.quality?.archiveSimilarityLimit ?? 0.42);
+ for (const item of live.filter((row) => !publishedIds.has(row.id))) {
+ const head = headText(item);
+ const closest = history.reduce((best, prior) => Math.max(best, copySimilarity(head, prior)), 0);
+ if (closest >= archiveLimit) problems[item.id].push(`repeats an earlier @trythreews post (similarity ${closest.toFixed(2)} >= ${archiveLimit})`);
+ else notes.push(`${item.id}: ${item.kind}, head ${weightedLength(item.posts?.[0]?.text || '')} chars, closest earlier post ${closest.toFixed(2)}`);
+ }
+ return { problems, notes };
+}
diff --git a/api/_lib/x-content/runner.js b/api/_lib/x-content/runner.js
new file mode 100644
index 000000000..f24701fac
--- /dev/null
+++ b/api/_lib/x-content/runner.js
@@ -0,0 +1,44 @@
+// One tick of the content queue, shared by the Cloud Scheduler cron and the
+// CLI: validate, pick the due item, then either preview it or publish it.
+
+import { loadQueue, validateQueue } from './queue.js';
+import { pickDue } from './schedule.js';
+import { previewClient, publishItem, xClientFromEnv } from './publisher.js';
+
+export async function runTick({ root, store, now = Date.now(), dryRun = true, requestedId = null, env = process.env }) {
+ const queue = loadQueue(root);
+ const state = await store.load();
+ const { problems } = validateQueue(queue, root, { state });
+
+ const blocked = (queue.items || [])
+ .filter((item) => item.status === 'approved' && problems[item.id]?.length)
+ .map((item) => ({ id: item.id, problems: problems[item.id] }));
+ // A named preview shows the calls even for an item that still fails review,
+ // so the operator sees exactly what they are fixing.
+ const publishable = (queue.items || []).filter((item) => !problems[item.id]?.length || (dryRun && item.id === requestedId));
+
+ const decision = pickDue({
+ items: publishable,
+ state,
+ now,
+ cadence: queue.cadence,
+ quality: queue.quality,
+ requestedId,
+ anyStatus: dryRun,
+ });
+ if (!decision.item) return { published: null, reason: decision.reason, blocked };
+
+ const item = decision.item;
+ if (dryRun) {
+ const client = previewClient();
+ // Preview against a scratch copy: the real ledger must not change.
+ const scratch = structuredClone(state);
+ await publishItem({ item, client, root, state: scratch, store: { save: async () => {} }, account: queue.account });
+ return { preview: { id: item.id, kind: item.kind, dueAt: new Date(decision.dueAt).toISOString(), calls: client.calls }, blocked };
+ }
+
+ const client = await xClientFromEnv(env);
+ if (!client) return { published: null, skipped: 'not_configured', reason: 'X_API_KEY, X_API_SECRET, X_ACCESS_TOKEN, X_ACCESS_SECRET are required', blocked };
+ const row = await publishItem({ item, client, root, state, store, account: queue.account });
+ return { published: row, resumed: Boolean(decision.resuming), blocked };
+}
diff --git a/api/_lib/x-content/schedule.js b/api/_lib/x-content/schedule.js
new file mode 100644
index 000000000..8902f98a4
--- /dev/null
+++ b/api/_lib/x-content/schedule.js
@@ -0,0 +1,103 @@
+// Picks the one item a tick should publish, or explains why nothing is due.
+//
+// Human cadence, not cron cadence. An account that posts at 14:00:00 every day
+// in lane order is obviously a bot. So:
+// - each item lands at a stable jittered moment inside its window after
+// `notBefore` (hashed from its id, so a preview and the real tick agree);
+// - posts keep a minimum gap and a rolling 24h cap;
+// - quiet hours are respected;
+// - the same lane or format never runs more times in a row than the config
+// allows, unless the item has waited a full day past its moment (so a
+// one-lane queue still drains).
+// Pure: no I/O, so the rules are unit-tested and the CLI shows the same
+// decision the cron will make.
+
+import { createHash } from 'node:crypto';
+
+const MINUTE = 60_000;
+const DAY = 24 * 60 * MINUTE;
+
+export const DEFAULT_CADENCE = {
+ windowMinutes: 90,
+ minimumMinutesApart: 240,
+ dailyCap: 3,
+ quietHoursUtc: null,
+};
+
+export function jitterMinutes(id, windowMinutes) {
+ const digest = createHash('sha256').update(String(id)).digest();
+ return digest.readUInt32BE(0) % Math.max(1, windowMinutes);
+}
+
+export function dueAt(item, cadence = DEFAULT_CADENCE) {
+ const window = Number(item.windowMinutes ?? cadence.windowMinutes ?? DEFAULT_CADENCE.windowMinutes);
+ return Date.parse(item.notBefore) + jitterMinutes(item.id, window) * MINUTE;
+}
+
+export function inQuietHours(now, quiet) {
+ if (!Array.isArray(quiet) || quiet.length !== 2) return false;
+ const minutes = new Date(now).getUTCHours() * 60 + new Date(now).getUTCMinutes();
+ const [start, end] = quiet.map((value) => {
+ const [h, m] = String(value).split(':').map(Number);
+ return h * 60 + (m || 0);
+ });
+ return start <= end ? minutes >= start && minutes < end : minutes >= start || minutes < end;
+}
+
+function trailingRun(published, field, value) {
+ let run = 0;
+ for (let index = published.length - 1; index >= 0; index--) {
+ if (published[index][field] !== value) break;
+ run++;
+ }
+ return run;
+}
+
+// `requestedId` names one item and skips pacing; `anyStatus` lets a preview of
+// that item run before it is approved.
+export function pickDue({ items, state, now = Date.now(), cadence: rawCadence = {}, quality = {}, requestedId = null, anyStatus = false }) {
+ const cadence = { ...DEFAULT_CADENCE, ...rawCadence };
+ const published = [...(state?.published || [])].sort((a, b) => a.publishedAt.localeCompare(b.publishedAt));
+ const publishedIds = new Set(published.map((row) => row.id));
+ const inflight = state?.inflight || {};
+
+ const candidates = items
+ .filter((item) => (item.status === 'approved' || (anyStatus && requestedId)) && !publishedIds.has(item.id))
+ .filter((item) => !requestedId || item.id === requestedId)
+ .map((item) => ({ item, at: dueAt(item, cadence) }))
+ .sort((a, b) => a.at - b.at);
+
+ if (requestedId) {
+ return candidates[0] ? { item: candidates[0].item, dueAt: candidates[0].at, forced: true } : { item: null, reason: `no ${anyStatus ? '' : 'approved '}unpublished item named ${requestedId}` };
+ }
+
+ // A half-published item (thread cut off mid-way, Article drafted but not
+ // yet published) always resumes first, ahead of every pacing rule.
+ const resuming = candidates.find(({ item }) => inflight[item.id]);
+ if (resuming) return { item: resuming.item, dueAt: resuming.at, resuming: true };
+
+ if (inQuietHours(now, cadence.quietHoursUtc)) return { item: null, reason: 'quiet hours' };
+
+ const last = published[published.length - 1];
+ if (last) {
+ const nextAllowed = Date.parse(last.publishedAt) + cadence.minimumMinutesApart * MINUTE;
+ if (now < nextAllowed) return { item: null, reason: `spacing: next post allowed at ${new Date(nextAllowed).toISOString()}` };
+ }
+ const lastDay = published.filter((row) => now - Date.parse(row.publishedAt) < DAY).length;
+ if (lastDay >= cadence.dailyCap) return { item: null, reason: `daily cap of ${cadence.dailyCap} reached` };
+
+ const maxLane = Number(quality.maximumSameLaneInARow ?? Infinity);
+ const maxPattern = Number(quality.maximumSamePatternInARow ?? Infinity);
+ const due = candidates.filter(({ at }) => at <= now);
+ if (!due.length) {
+ const next = candidates[0];
+ return { item: null, reason: next ? `next item ${next.item.id} is due at ${new Date(next.at).toISOString()}` : 'queue has no approved unpublished items' };
+ }
+ for (const candidate of due) {
+ const starved = now - candidate.at >= DAY;
+ const laneRun = trailingRun(published, 'lane', candidate.item.lane);
+ const patternRun = trailingRun(published, 'pattern', candidate.item.pattern);
+ if (starved || (laneRun < maxLane && patternRun < maxPattern)) return { item: candidate.item, dueAt: candidate.at };
+ }
+ return { item: null, reason: 'every due item would repeat the previous lane or pattern; waiting for variety' };
+}
diff --git a/api/_lib/x-content/state.js b/api/_lib/x-content/state.js
new file mode 100644
index 000000000..4fdbbd2e9
--- /dev/null
+++ b/api/_lib/x-content/state.js
@@ -0,0 +1,70 @@
+// Publish ledger for the content queue, stored in app_settings so the Cloud
+// Scheduler cron and a local `npm run x:content -- run` share one record and
+// can never double-post.
+//
+// Shape:
+// { published: [{ id, kind, lane, pattern, publishedAt, text, postIds, articleId?, url }],
+// inflight: { [id]: { media: { [path]: { id, at } }, postIds: [], articleDraftId?, articlePostId? } } }
+//
+// `inflight` is written after every API call that creates something on X, so a
+// crash mid-thread resumes where it stopped instead of reposting.
+
+export const STATE_KEY = 'x_content';
+const LOCK_KEY = 'x_content_lock';
+// Video processing can take minutes; the lock outlives the slowest publish.
+const LOCK_TTL_S = 900;
+
+const emptyState = () => ({ published: [], inflight: {} });
+
+export function dbStore() {
+ const db = () => import('../db.js').then((module) => module.sql);
+ return {
+ label: 'database',
+ async load() {
+ const sql = await db();
+ const [row] = await sql`SELECT value FROM app_settings WHERE key = ${STATE_KEY}`;
+ return { ...emptyState(), ...(row?.value || {}) };
+ },
+ async save(state) {
+ const sql = await db();
+ await sql`
+ INSERT INTO app_settings (key, value) VALUES (${STATE_KEY}, ${JSON.stringify(state)}::jsonb)
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = now()
+ `;
+ },
+ async acquireLock() {
+ const sql = await db();
+ const rows = await sql`
+ INSERT INTO app_settings (key, value)
+ VALUES (${LOCK_KEY}, jsonb_build_object('until', extract(epoch from now()) + ${LOCK_TTL_S}))
+ ON CONFLICT (key) DO UPDATE
+ SET value = excluded.value, updated_at = now()
+ WHERE (app_settings.value->>'until')::numeric < extract(epoch from now())
+ RETURNING key
+ `;
+ return rows.length > 0;
+ },
+ async releaseLock() {
+ const sql = await db();
+ await sql`UPDATE app_settings SET value = '{"until":0}'::jsonb, updated_at = now() WHERE key = ${LOCK_KEY}`;
+ },
+ };
+}
+
+// For previews on a machine without DATABASE_URL: starts empty, keeps nothing.
+export function memoryStore(initial = emptyState()) {
+ let state = structuredClone(initial);
+ return {
+ label: 'memory (no DATABASE_URL, so published history is not considered)',
+ async load() {
+ return structuredClone(state);
+ },
+ async save(next) {
+ state = structuredClone(next);
+ },
+ async acquireLock() {
+ return true;
+ },
+ async releaseLock() {},
+ };
+}
diff --git a/api/cron/x-content.js b/api/cron/x-content.js
new file mode 100644
index 000000000..31237106b
--- /dev/null
+++ b/api/cron/x-content.js
@@ -0,0 +1,43 @@
+// @ts-check
+// GET /api/cron/x-content - the reviewed @trythreews content queue.
+//
+// Runs every 15 minutes on Cloud Scheduler. Each tick publishes at most one
+// approved item from data/x-content/queue.json (baked into the image by the
+// deploy that shipped it): a post or thread with native images, GIF, or video,
+// or an X Article followed by posts that quote it. Pacing, jitter, rotation,
+// and the publish ledger live in api/_lib/x-content/.
+//
+// Posting is off until the owner turns it on. With X_CONTENT_AUTO_PUBLISH unset
+// the tick runs in preview mode and returns the exact X API calls it would make,
+// so the queue can be verified in production before a single post goes out.
+//
+// Credentials: X_API_KEY, X_API_SECRET, X_ACCESS_TOKEN, X_ACCESS_SECRET
+// (OAuth 1.0a user context for @trythreews). Articles also need the account on
+// X Premium.
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { runTick } from '../_lib/x-content/runner.js';
+import { dbStore } from '../_lib/x-content/state.js';
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET'])) return;
+ if (!requireCron(req, res)) return;
+
+ const store = dbStore();
+ if (!(await store.acquireLock())) {
+ json(res, 200, { ok: true, skipped: 'locked' });
+ return;
+ }
+ const live = process.env.X_CONTENT_AUTO_PUBLISH === 'true';
+ try {
+ const result = await runTick({ root: process.cwd(), store, dryRun: !live });
+ if (result.blocked.length) console.warn('[cron] x-content approved items failing validation', result.blocked);
+ json(res, 200, { ok: true, mode: live ? 'publish' : 'preview', ...result });
+ } catch (err) {
+ console.error('[cron] x-content publish failed; progress is saved and the next tick resumes', err);
+ json(res, 502, { ok: false, mode: live ? 'publish' : 'preview', error: String(/** @type {any} */ (err)?.message || err) });
+ } finally {
+ await store.releaseLock().catch(() => {});
+ }
+});
diff --git a/api/pump/[action].js b/api/pump/[action].js
index fd6176b6e..898937638 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -89,7 +89,7 @@ import { grindVanityNode, GrindExhaustedError } from '../../src/solana/vanity/gr
import { logger } from '../_lib/usage.js';
import { cacheGet, cacheSet } from '../_lib/cache.js';
import { pumpFetchJson } from '../_lib/pump-feed-fetch.js';
-import { staleEnvelope } from '../_lib/rpc-degrade.js';
+import { isRpcOutageError, staleEnvelope } from '../_lib/rpc-degrade.js';
const log = logger('pump.launch');
import {
@@ -265,6 +265,10 @@ const wrapped = wrap(async (req, res) => {
return handleSearch(req, res);
case 'collect-creator-fee-prep':
return handleCollectCreatorFeePrep(req, res);
+ case 'launch-config':
+ return handleLaunchConfig(req, res);
+ case 'my-coins':
+ return handleMyCoins(req, res);
case 'distribute-creator-fees-prep':
return handleDistributeCreatorFeesPrep(req, res);
case 'create-fee-sharing-prep':
@@ -1081,13 +1085,34 @@ async function handleBuildMetadata(req, res) {
// ── Build metadata JSON via the canonical three.ws brand builder ─────────
// This stamps createdOn=https://three.ws plus the Platform/Launchpad
// attributes that explorers and launchpad aggregators read for attribution.
- const agentHomeUrl = body.agent_id ? `${env.APP_ORIGIN}/agents/${body.agent_id}` : undefined;
+ // Link the coin to its 3D agent. An avatar that has no agent identity yet gets
+ // one here (launch-prep would create it moments later anyway), so the page
+ // the coin points at is the agent that launched it, not the three.ws homepage.
+ let linkedAgentId = body.agent_id || null;
+ let agentModelUrl;
+ if (body.avatar_id) {
+ if (!linkedAgentId) {
+ const resolved = await resolveLaunchAgentId({ userId: uid, avatarId: body.avatar_id }).catch(() => null);
+ linkedAgentId = resolved?.id || null;
+ }
+ const [avRow] = await sql`
+ select storage_key, visibility from avatars
+ where id=${body.avatar_id} and owner_id=${uid} and deleted_at is null limit 1
+ `;
+ // Token metadata is permanent and public: only a model its owner already
+ // shares (public or unlisted) is written into it.
+ if (avRow?.storage_key && (avRow.visibility === 'public' || avRow.visibility === 'unlisted')) {
+ agentModelUrl = r2PublicUrl(avRow.storage_key);
+ }
+ }
+ const agentHomeUrl = linkedAgentId ? `${env.APP_ORIGIN}/agents/${linkedAgentId}` : undefined;
const metadata = buildTokenMetadata({
name: body.name,
symbol: body.symbol,
description: body.description,
image: imageUrl || '',
...(agentHomeUrl ? { agentUrl: agentHomeUrl } : {}),
+ ...(agentModelUrl ? { agentModelUrl } : {}),
...(body.twitter ? { twitter: body.twitter } : {}),
...(body.website ? { website: body.website } : {}),
...(body.telegram ? { telegram: body.telegram } : {}),
@@ -1109,6 +1134,9 @@ async function handleBuildMetadata(req, res) {
return json(res, 200, {
metadata_url: metadataUrl,
image_url: imageUrl,
+ agent_id: linkedAgentId,
+ agent_url: agentHomeUrl || null,
+ agent_model_url: agentModelUrl || null,
on_ipfs: Boolean(pinnedJson),
provider: pinnedJson?.provider ?? (ipfsPinningConfigured() ? 'r2-fallback' : 'r2'),
});
@@ -1978,7 +2006,6 @@ async function handleLaunchAgent(req, res) {
});
instructions.push(createIx);
}
- if (launchFee) instructions.push(...launchFee.instructions);
// Spend-policy gate: this path signs server-side with the agent's custodial
// wallet, so a stolen session could otherwise drive an arbitrarily large SOL
@@ -2004,20 +2031,44 @@ async function handleLaunchAgent(req, res) {
if (!reservation.ok) return error(res, reservation.status, reservation.code, reservation.msg);
let signature;
- try {
- // Protected send: the agent custodial wallet pays + signs, the new mint
- // co-signs. Priority fee + CU estimate, rebroadcast with blockhash refresh,
- // hard throw on an on-chain revert.
- ({ signature } = await submitProtected({
+ // Set when the fee could not ride in the launch transaction and settles in its
+ // own transaction after the launch lands: 'separate' on success, 'failed' if
+ // that follow-up transfer did not land.
+ let feeSettlement = launchFee ? 'bundled' : null;
+ const lookupTables = await getPumpLookupTables({ network: body.network });
+ const sendLaunch = (ixs) =>
+ submitProtected({
network: body.network,
connection: conn,
payer: agentKeypair,
- instructions,
- opts: {
- extraSigners: [mintKeypair],
- addressLookupTables: await getPumpLookupTables({ network: body.network }),
- },
- }));
+ instructions: ixs,
+ opts: { extraSigners: [mintKeypair], addressLookupTables: lookupTables },
+ });
+ try {
+ // Protected send: the agent custodial wallet pays + signs, the new mint
+ // co-signs. Priority fee + CU estimate, rebroadcast with blockhash refresh,
+ // hard throw on an on-chain revert. The launch fee rides along when it
+ // fits; a USDC-quoted launch plus the engine's compute-budget instructions
+ // can exceed the v0 packet, and then the coin launches first and the fee
+ // follows in its own transaction.
+ try {
+ ({ signature } = await sendLaunch(launchFee ? [...instructions, ...launchFee.instructions] : instructions));
+ } catch (err) {
+ if (!launchFee || !/too large|overruns|RangeError/i.test(`${err?.name} ${err?.message}`)) throw err;
+ ({ signature } = await sendLaunch(instructions));
+ feeSettlement = 'separate';
+ try {
+ await submitProtected({
+ network: body.network,
+ connection: conn,
+ payer: agentKeypair,
+ instructions: launchFee.instructions,
+ });
+ } catch (feeErr) {
+ feeSettlement = 'failed';
+ console.error('[pump/launch-agent] separate launch-fee transfer failed', mint.toBase58(), feeErr?.message);
+ }
+ }
} catch (err) {
await releaseSpend(reservation.reservationId);
// A message too large for Solana's packet limit now surfaces here (compile
@@ -2062,7 +2113,7 @@ async function handleLaunchAgent(req, res) {
buyback_bps: effBuyback,
coin_type: body.coin_type,
holder_reward: body.holder_reward,
- platform_fee: launchFee ? launchFee.disclosure : null,
+ platform_fee: launchFee ? { ...launchFee.disclosure, settlement: feeSettlement } : null,
source: 'studio_agent_wallet',
});
@@ -2095,7 +2146,7 @@ async function handleLaunchAgent(req, res) {
quote_mint: quote.quoteMint,
quote_currency: quote.label,
pump_agent_mint: row || null,
- platform_fee: launchFee ? launchFee.disclosure : null,
+ platform_fee: launchFee ? { ...launchFee.disclosure, settlement: feeSettlement } : null,
buyback_available: buybackAvailable,
explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
pumpfun_url: `https://pump.fun/coin/${mintAddr}`,
@@ -4153,6 +4204,167 @@ async function handleVanityKeygen(req, res) {
}
}
+// ── launch-config ──────────────────────────────────────────────────────────
+// What a launch will cost and which transaction formats it can use, read live
+// so the /launch preview never quotes a fee the transaction will not take.
+
+async function handleLaunchConfig(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const [recipient, txV1, tradeFeeBps] = await Promise.all([
+ pumpFeeRecipient(),
+ transactionV1Status({ network }),
+ effectivePumpFeeBps(),
+ ]);
+
+ res.setHeader('cache-control', 'public, max-age=60');
+ return json(res, 200, {
+ data: {
+ network,
+ launch_fee_bps: recipient ? pumpLaunchFeeBps() : 0,
+ launch_fee_basis: 'dev_buy',
+ fee_recipient: recipient ? recipient.toBase58() : null,
+ trade_fee_bps: tradeFeeBps,
+ create_cost_sol_estimate: 0.022,
+ max_sol_buy_in: 50,
+ buyback_available: pumpAgentBuybackAvailable(),
+ tx_v1: txV1,
+ },
+ });
+}
+
+// ── my-coins ───────────────────────────────────────────────────────────────
+// Every coin the signed-in user launched through three.ws, grouped by the
+// on-chain creator that earns its rewards, with the live unclaimed balance per
+// creator. pump.fun pools creator fees per creator wallet (not per coin), so a
+// claim is per wallet and sweeps every coin that wallet created.
+
+const PUMP_QUOTE_LABELS = {
+ So11111111111111111111111111111111111111112: { symbol: 'SOL', decimals: 9 },
+ EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: { symbol: 'USDC', decimals: 6 },
+ '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU': { symbol: 'USDC', decimals: 6 },
+};
+
+async function creatorRewardBalances(connection, creator) {
+ const { OnlinePumpSdk } = await import('@pump-fun/pump-sdk');
+ const rows = await new OnlinePumpSdk(connection).getCreatorVaultQuoteBalances(new PublicKey(creator));
+ return rows
+ .map((r) => {
+ const mint = r.mint.toBase58();
+ const label = PUMP_QUOTE_LABELS[mint] || { symbol: `${mint.slice(0, 4)}…`, decimals: null };
+ const total = BigInt(r.total.toString());
+ return {
+ mint,
+ symbol: label.symbol,
+ amount: total.toString(),
+ amount_ui: label.decimals == null ? null : Number(total) / 10 ** label.decimals,
+ };
+ })
+ .filter((r) => r.amount !== '0');
+}
+
+async function handleMyCoins(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+
+ const [rows, linked] = await Promise.all([
+ sql`
+ select pam.mint, pam.name, pam.symbol, pam.created_at, pam.agent_authority,
+ pam.sharing_config, pam.quote_mint,
+ ai.id as agent_id, ai.name as agent_name, ai.avatar_id,
+ ai.meta->>'solana_address' as agent_wallet,
+ a.thumbnail_key
+ from pump_agent_mints pam
+ left join agent_identities ai on ai.id = pam.agent_id and ai.deleted_at is null
+ left join avatars a on a.id = ai.avatar_id and a.deleted_at is null
+ where pam.user_id = ${user.id} and pam.network = ${network}
+ order by pam.created_at desc
+ limit 200
+ `,
+ sql`select address from user_wallets where user_id = ${user.id} and chain_type = 'solana'`,
+ ]);
+ const linkedSet = new Set(linked.map((w) => w.address));
+ const { holderRewardsPda } = await import('@pump-fun/pump-sdk');
+
+ const coins = [];
+ const creators = new Map(); // address -> wallet group
+ for (const r of rows) {
+ const creator = r.agent_authority;
+ let route;
+ const shared = r.sharing_config && Array.isArray(r.sharing_config.shareholders) && r.sharing_config.shareholders.length > 0;
+ if (shared) route = 'shared';
+ else if (!creator) route = 'unknown';
+ else if (holderRewardsPda(new PublicKey(r.mint)).toBase58() === creator) route = 'holders';
+ else if (r.agent_wallet && r.agent_wallet === creator) route = 'agent';
+ else if (linkedSet.has(creator)) route = 'wallet';
+ else route = 'external';
+
+ coins.push({
+ mint: r.mint,
+ name: r.name,
+ symbol: r.symbol,
+ created_at: r.created_at,
+ quote_mint: r.quote_mint,
+ creator,
+ reward_route: route,
+ agent: r.agent_id
+ ? {
+ id: r.agent_id,
+ name: r.agent_name,
+ avatar_id: r.avatar_id,
+ thumbnail_url: thumbnailUrl(r.thumbnail_key),
+ }
+ : null,
+ });
+
+ if (route !== 'agent' && route !== 'wallet') continue;
+ if (!creators.has(creator)) {
+ creators.set(creator, {
+ address: creator,
+ kind: route,
+ agent: route === 'agent' ? { id: r.agent_id, name: r.agent_name } : null,
+ // The agent claim endpoint authorizes through one of the agent's coins.
+ claim_mint: r.mint,
+ coins: [],
+ rewards: [],
+ balance_error: null,
+ });
+ }
+ creators.get(creator).coins.push(r.mint);
+ }
+
+ const connection = getConnection({ network });
+ await Promise.all(
+ [...creators.values()].map(async (group) => {
+ try {
+ group.rewards = await creatorRewardBalances(connection, group.address);
+ } catch (e) {
+ group.balance_error = isRpcOutageError(e) ? 'rpc_unavailable' : 'balance_read_failed';
+ console.warn('[pump/my-coins] vault read failed', group.address, e?.message);
+ }
+ }),
+ );
+
+ return json(res, 200, {
+ data: { network, coins, wallets: [...creators.values()] },
+ });
+}
+
// ── collect-creator-fee-prep ───────────────────────────────────────────────
// Builds the tx for the coin creator to collect accrued creator fees from the
// pump.fun fee vault into their own wallet.
@@ -4164,6 +4376,11 @@ const collectCreatorFeePrepSchema = z.object({
// The wallet that will sign (and receive fees). Must match creator_address.
wallet_address: z.string().min(32).max(44),
network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ // Sweep every quote mint (SOL plus USDC and any other listed quote) instead
+ // of SOL alone, so a USDC-paired coin's rewards are claimable too.
+ all_quotes: z.boolean().default(false),
+ transaction_version: z.union([z.literal('auto'), z.literal(0), z.literal(1)]).default('auto'),
+ v1_capable: z.boolean().default(false),
});
async function handleCollectCreatorFeePrep(req, res) {
@@ -4185,16 +4402,21 @@ async function handleCollectCreatorFeePrep(req, res) {
const { sdk, connection } = await getPumpSdk({ network: body.network });
const { OnlinePumpSdk } = await import('@pump-fun/pump-sdk');
const onlineSdk = new OnlinePumpSdk(connection);
- const ixs = await onlineSdk.collectCoinCreatorFeeInstructions(creatorPk, feePayer);
- const tx_base64 = await buildUnsignedTxBase64({
+ const ixs = body.all_quotes
+ ? await onlineSdk.collectCoinCreatorFeeAllQuotesInstructions(creatorPk, feePayer)
+ : await onlineSdk.collectCoinCreatorFeeInstructions(creatorPk, feePayer);
+ const built = await buildLaunchTransaction({
network: body.network,
payer: feePayer,
instructions: Array.isArray(ixs) ? ixs : [ixs],
+ transactionVersion: body.transaction_version,
+ v1Capable: body.v1_capable,
});
return json(res, 201, {
creator: body.creator_address,
network: body.network,
- tx_base64,
+ tx_base64: built.tx_base64,
+ transaction_version: built.transaction_version,
});
} catch (e) {
return error(
@@ -4863,6 +5085,7 @@ const collectFeeAgentSchema = z
avatar_id: z.string().uuid().optional(),
mint: z.string().min(32).max(44),
network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ all_quotes: z.boolean().default(false),
})
.refine((b) => b.agent_id || b.avatar_id, { message: 'agent_id or avatar_id required' });
@@ -4886,7 +5109,9 @@ async function handleCollectCreatorFeeAgent(req, res) {
// lamports the claim delivered (net of tx fee): callers (the launcher
// claimer, the studio) need the real figure, not a boolean.
const balanceBefore = await connection.getBalance(creatorPk).catch(() => null);
- const ixs = await onlineSdk.collectCoinCreatorFeeInstructions(creatorPk, creatorPk);
+ const ixs = body.all_quotes
+ ? await onlineSdk.collectCoinCreatorFeeAllQuotesInstructions(creatorPk, creatorPk)
+ : await onlineSdk.collectCoinCreatorFeeInstructions(creatorPk, creatorPk);
const signature = await signSendWithAgent({
network: body.network,
agentKeypair: ctx.loaded.keypair,
diff --git a/data/x-announcement-pipeline.json b/data/x-announcement-pipeline.json
deleted file mode 100644
index 0b9b76a67..000000000
--- a/data/x-announcement-pipeline.json
+++ /dev/null
@@ -1,63 +0,0 @@
-{
- "version": 1,
- "account": "trythreews",
- "mode": "approval",
- "cadence": {
- "timezone": "UTC",
- "slots": ["14:07", "19:13", "00:19"],
- "minimumMinutesApart": 240
- },
- "quality": {
- "archiveSimilarityLimit": 0.42,
- "queueSimilarityLimit": 0.34,
- "maximumSameLaneInARow": 2,
- "maximumSamePatternInARow": 1
- },
- "items": [
- {
- "id": "genesis",
- "status": "review",
- "notBefore": "2026-09-17T14:07:00Z",
- "lane": "community",
- "pattern": "mechanism",
- "source": "docs/announcements/genesis.md",
- "parts": ["docs/announcements/genesis.post.txt"],
- "media": [
- {
- "path": "public/announce/img/genesis-hero.webp",
- "alt": "The three.ws Genesis page signed in: describe an agent, upload a selfie, or remix a public avatar, and it becomes a rigged 3D agent with its own wallet and on-chain identity"
- }
- ]
- },
- {
- "id": "rig-doctor",
- "status": "review",
- "notBefore": "2026-09-17T19:13:00Z",
- "lane": "developer",
- "pattern": "correction",
- "source": "docs/announcements/open-source-friday.md",
- "parts": ["docs/announcements/open-source-friday.post.txt"],
- "media": [
- {
- "path": "public/announce/img/rig-doctor-hero.webp",
- "alt": "three.ws Rig Doctor: drop in any humanoid GLB and it names the skeleton convention, then lists joint by joint which bones will animate and which will not move"
- }
- ]
- },
- {
- "id": "aws-authorization-spine",
- "status": "review",
- "notBefore": "2026-09-18T00:19:00Z",
- "lane": "article",
- "pattern": "number",
- "source": "docs/announcements/aws-builder-center-authorization-spine.md",
- "parts": ["docs/announcements/aws-builder-center-authorization-spine.post.txt"],
- "media": [
- {
- "path": "public/announce/img/aws-builder-center-authorization-spine.webp",
- "alt": "The article live on the AWS Builder Center under the three.ws byline, headlined Budgets, entitlements, and the $THREE token layer: how we authorize autonomous agent spending, published 11 September 2026"
- }
- ]
- }
- ]
-}
diff --git a/data/x-content/articles/web-component-article.md b/data/x-content/articles/web-component-article.md
new file mode 100644
index 000000000..4d8f3e204
--- /dev/null
+++ b/data/x-content/articles/web-component-article.md
@@ -0,0 +1,56 @@
+**Drop one `<agent-3d>` web component on your site and give any page an AI with a body.** LLM brain with memory and emotions. Physical DOM awareness. An on-chain identity that persists forever. And it covers its eyes when you type a password.
+
+```
+<script src="https://three.ws/agent.js"></script>
+<agent-3d agent-id="your-agent-id"></agent-3d>
+```
+
+That's it. The component is a standard HTML custom element, no framework, no build step, no bundler. It renders in any browser that supports WebGL, which is all of them.
+
+## What <agent-3d> ships with
+
+### An LLM brain with memory and emotions
+
+The agent runs on the LLM you configure in the three.ws studio, Claude, GPT, and others. It has persistent memory across sessions so it remembers who it's talking to. Its emotion state, happy, curious, concerned, excited, is updated by the LLM with each response and drives the avatar's body language in real time.
+
+### Physical DOM awareness
+
+The agent knows what's on the page. It can read element content, observe DOM mutations, understand layout, and physically react to it. In demos: watch it hop from card to card as you scroll. It can point to specific UI elements when explaining them. It moves through the page's actual space, not floating in a fixed corner disconnected from the content.
+
+### Password field privacy
+
+When the browser's focus moves to an `input[type="password"]` element, the agent covers its eyes. It's a small interaction, but it immediately communicates that the agent is aware of what's happening, respects user privacy, and has social intelligence, not just chat capability.
+
+### An on-chain identity that lives
+
+Every agent is minted as a Solana NFT with an ERC-8004 cross-chain wallet. The on-chain identity is the agent's persistent self, it carries the agent's history, reputation, and accumulated interactions. The agent doesn't disappear when you close the tab. Its identity is on-chain and it persists anywhere it's embedded.
+
+## Why a web component
+
+Web components work everywhere HTML works. No React. No Next.js. No framework lock-in. You can drop `<agent-3d>` into a WordPress page, a Webflow site, a vanilla HTML file, or a React component tree, it behaves identically in all of them. The shadow DOM keeps the agent's internal structure isolated from the host page's styles, and the custom element API lets the host page communicate with the agent through standard attributes and events.
+
+This was a deliberate choice. The internet is mostly not React. The 3D layer for the internet has to work on the whole internet.
+
+## The action bridge
+
+The agent communicates bidirectionally with the host page through a secure postMessage bridge. The host page can:
+
+- Send events to the agent ("user clicked checkout", "price alert triggered", "form submitted")
+- Set the agent's emotion or animation state from page JavaScript
+- Receive events from the agent ("agent completed task", "user wants to pay", "agent needs clarification")
+
+The bridge is gated by allowed origins, you configure which domains the agent will accept messages from in the Widget Studio. This is required: add your embedding domain to the allowed origins list or the action bridge will be blocked by CORS.
+
+## CORS note for embedders
+
+Add the domain you're embedding on to the widget's allowed origins list in the three.ws studio before going live. Without it, the action bridge is blocked and the agent won't be able to communicate with your page, it will still render and chat, but page-level integrations won't work.
+
+## Get started
+
+- Widget Studio: [three.ws/widget-studio](https://three.ws/widget-studio)
+- Web component docs: [three.ws/docs](https://three.ws/docs)
+- Open source: [github.com/nirholas/three.ws](https://github.com/nirholas/three.ws)
+
+---
+
+Originally published at [three.ws/blog/agent-3d-web-component](https://three.ws/blog/agent-3d-web-component).
diff --git a/data/x-content/queue.json b/data/x-content/queue.json
new file mode 100644
index 000000000..5f1d62dfb
--- /dev/null
+++ b/data/x-content/queue.json
@@ -0,0 +1,111 @@
+{
+ "version": 2,
+ "account": "trythreews",
+ "cadence": {
+ "windowMinutes": 90,
+ "minimumMinutesApart": 240,
+ "dailyCap": 3,
+ "quietHoursUtc": [
+ "05:00",
+ "12:00"
+ ]
+ },
+ "quality": {
+ "archiveSimilarityLimit": 0.42,
+ "queueSimilarityLimit": 0.34,
+ "maximumSameLaneInARow": 2,
+ "maximumSamePatternInARow": 1
+ },
+ "items": [
+ {
+ "id": "genesis",
+ "status": "review",
+ "kind": "post",
+ "lane": "community",
+ "pattern": "mechanism",
+ "notBefore": "2026-09-17T14:07:00Z",
+ "source": {
+ "path": "docs/announcements/genesis.md"
+ },
+ "posts": [
+ {
+ "text": "A sentence or a selfie becomes a rigged 3D agent holding its own custodial @solana wallet, a persona, and a voice. It walks and emotes on arrival: three.ws/genesis",
+ "media": [
+ {
+ "path": "public/announce/img/genesis-hero.webp",
+ "alt": "The three.ws Genesis page signed in: describe an agent, upload a selfie, or remix a public avatar, and it becomes a rigged 3D agent with its own wallet and on-chain identity"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "id": "rig-doctor",
+ "status": "review",
+ "kind": "post",
+ "lane": "developer",
+ "pattern": "correction",
+ "notBefore": "2026-09-17T19:13:00Z",
+ "source": {
+ "path": "docs/announcements/open-source-friday.md"
+ },
+ "posts": [
+ {
+ "text": "Approved for GitHub's Open Source Friday. Rig Doctor knows 11 rig conventions. Teaching it the 12th is an open first issue, and we merge it live on stream: three.ws/rig-doctor",
+ "media": [
+ {
+ "path": "public/announce/img/rig-doctor-hero.webp",
+ "alt": "three.ws Rig Doctor: drop in any humanoid GLB and it names the skeleton convention, then lists joint by joint which bones will animate and which will not move"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "id": "aws-authorization-spine",
+ "status": "review",
+ "kind": "post",
+ "lane": "article",
+ "pattern": "number",
+ "notBefore": "2026-09-18T00:19:00Z",
+ "source": {
+ "path": "docs/announcements/aws-builder-center-authorization-spine.md"
+ },
+ "posts": [
+ {
+ "text": "How we authorize autonomous spend, and the $THREE layer, on @awscloud: https://builder.aws.com/content/3JAVvvItd3ZSVjYCDb4qjj5VBb9/budgets-entitlements-and-the-dollarthree-token-layer-how-we-authorize-autonomous-agent-spending-or-threews-an-aws-partner",
+ "media": [
+ {
+ "path": "public/announce/img/aws-builder-center-authorization-spine.webp",
+ "alt": "The article live on the AWS Builder Center under the three.ws byline, headlined Budgets, entitlements, and the $THREE token layer: how we authorize autonomous agent spending, published 11 September 2026"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "id": "web-component-article",
+ "status": "draft",
+ "kind": "article",
+ "lane": "article",
+ "pattern": "longform",
+ "notBefore": "2026-09-17T17:00:00.000Z",
+ "source": {
+ "url": "https://three.ws/blog/agent-3d-web-component",
+ "importedAt": "2026-09-16T16:33:45.221Z"
+ },
+ "article": {
+ "title": "We Just Shipped the 3D Layer for the Internet: <agent-3d>",
+ "body": "data/x-content/articles/web-component-article.md",
+ "cover": {
+ "path": "public/x-media/web-component-article/00-cover.png"
+ }
+ },
+ "posts": [
+ {
+ "text": "One web component. An AI with a body, memory, emotions, and DOM awareness. Covers its eyes when you type a password. Lives on-chain."
+ }
+ ]
+ }
+ ]
+}
diff --git a/docs/partners/opportunities.md b/docs/partners/opportunities.md
index c04e64d8f..2cd2a5d91 100644
--- a/docs/partners/opportunities.md
+++ b/docs/partners/opportunities.md
@@ -30,7 +30,7 @@ for a cycle, not delayed. Nothing here is on anyone's calendar yet.
| **Now** | GitHub Open Source Friday. [Issue #254](https://github.com/githubevents/open-source-friday/issues/254) is open with the `approved` label. Checked 2026-09-16: no date has been posted; the only comment is GitHub's 2026-09-01 request to pick a slot | Select a Friday at `https://gh.io/osf-booking`, then reply on issue #254 with the date | Owner |
| **Apply as soon as a venue is real** | [Hacktoberfest 2026 Fest](https://hacktoberfest.com/host/). Checked 2026-09-16: "Applications are now open and Fests are confirmed on a rolling basis", decisions typically within a week, and no application deadline is published. Apply at `https://hacktoberfest.com/my/` | Name the venue, city, capacity, and host, then submit either a one-day Hack Day or Meet Up application | Owner |
| **2026-09-26** | IBM TechXchange early-bird registration. [IBM's FAQ](https://www.ibm.com/events/techxchange/faq), checked 2026-09-16: early bird is USD 1279.20 from 13 July to **26 September** 2026 (not 29 September as previously recorded), then USD 1599. The event runs 2026-10-26 to 10-29 at the Georgia World Congress Center, Atlanta; the speaking CFP closed in May, but sponsorship, the Sandbox Expo and the colocated user-group route are open, and we moderate an IBM Community user group | Register, or decide not to attend | Owner |
-| **Not open as of 2026-09-16** | IBM Champions nomination. Checked 2026-09-16: the [programme page](https://www.ibm.com/community/champions-program/) shows no nomination window and no class-of-2027 call has been announced. The previous cycle [opened 2025-09-15](https://community.ibm.com/community/user/blogs/libby-ingrassia/2025/09/15/ibm-champions-nominations) and closed 2025-11-21. The page now also points to an IBM Rising Champions Advocacy badge route marked "new details coming soon", so the intake may change. Our record already matches all four of IBM's published criteria (spoke at an IBM event, moderate a user group, published on their community, run Granite in production). We have never entered | Check the programme page weekly; when the call opens, nominate a person (the program is for individuals, not companies) | Owner |
+| **Not open as of 2026-09-16** | IBM Champions nomination. Checked 2026-09-16: the [programme page](https://www.ibm.com/community/champions-program/) shows no nomination window and no class-of-2027 call has been announced. The previous cycle [opened 2025-09-15](https://community.ibm.com/community/user/blogs/libby-ingrassia/2025/09/15/ibm-champions-nominations) and closed 2025-11-21. The page now also points to an IBM Rising Champions Advocacy badge route marked "new details coming soon", so the intake may change. Our record already matches all four of IBM's published criteria (spoke at an IBM event, moderate a user group, published on their community, built on Granite). Caveat checked 2026-09-16: production has no `WATSONX_*` credentials and `/api/ibm/galaxy` answers `watsonx_not_configured`, so Granite is not running in production today; restore the credentials before any nomination says it is. Draft: [ibm-champions-nomination.md](../../marketing/partner-packets/ibm-champions-nomination.md). We have never entered | Check the programme page weekly; when the call opens, nominate a person (the program is for individuals, not companies) | Owner |
| **Watch weekly** | NVIDIA GTC 2027 call for speaking/poster submissions. This is separate from the Startup Pavilion, which NVIDIA confirmed is invite-only | Keep the CFP page on a weekly check; maintain the demo and profile for Pavilion consideration | Either |
| Spring 2027 | IBM TechXchange 2027 call for speakers | Submit when it opens | Owner |
@@ -95,7 +95,7 @@ The work is done or nearly done. A human on our side has to act.
| OpenAI Showcase Gallery | Eligible, open web form | Submit | Owner |
| IBM My Digital Marketing | Entitled, never used | Request access and the Build track marketing kit | Owner |
| Second IBM community event | Proposal written and costed | Pick a date | Owner |
-| IBM G2 review | Honest to write, we run Granite in production | Write it | Either |
+| IBM G2 review | Draft ready in [ibm-g2-review.md](../../marketing/partner-packets/ibm-g2-review.md), written in the past tense because production has had no `WATSONX_*` credentials since at least 2026-07-29 (checked 2026-09-16) | The actual watsonx.ai user rewrites it in their own words with their own console screenshot, or restores the credentials first | Owner |
| CoinGecko market addition for $THREE | Form researched; only one of our live venues qualifies | Submit for that venue | Owner |
| HackerNoon author page | Checked 2026-09-16: [hackernoon.com/u/three-ws](https://hackernoon.com/u/three-ws) is live but shows **no published stories** ("eagerly awaiting @three-ws's next masterpiece"). RSS import lands in the drafts queue; nothing has gone out from it | Open the HackerNoon drafts queue and submit the imported announcements for editorial review | Owner |
| Glama connector claim | Checked 2026-09-16: at least seven three.ws connectors are listed. The main `three.ws` connector is unclaimed and reports **Unhealthy** because Glama has no OAuth test credentials for `https://three.ws/api/mcp` | Claim ownership on the connector page (maintainer email `[email protected]` is already declared in `public/.well-known/glama.json`), then add a test profile under Admin | Owner |
diff --git a/marketing/partner-packets/openai-share-your-story.md b/marketing/partner-packets/openai-share-your-story.md
index ec47cd613..e2889ec94 100644
--- a/marketing/partner-packets/openai-share-your-story.md
+++ b/marketing/partner-packets/openai-share-your-story.md
@@ -40,7 +40,7 @@ The City and State fields assume a US location; the founder's location is not re
**Is this story about:** You
-**Tell us about yourself or the person this is about** (about 610 characters)
+**Tell us about yourself or the person this is about** (528 characters)
> I build three.ws, an open-source platform that gives AI a body. You type a sentence and get a
> textured, rigged 3D character you can animate, place in your room in AR, or embed on any web page
@@ -49,7 +49,7 @@ The City and State fields assume a US location; the founder's location is not re
> move it, and share it. The platform is free to try with no account or API key, and the viewer,
> runtime, and web component are open source.
-**How do you/they use OpenAI products?** (about 820 characters)
+**How do you/they use OpenAI products?** (676 characters)
> Two ways. First, as a distribution surface: we built a free 3D Studio connector for ChatGPT on the
> Apps SDK and MCP. It gives ChatGPT eleven keyless tools that generate a 3D model from a prompt,
@@ -59,7 +59,7 @@ The City and State fields assume a US location; the founder's location is not re
> Second, inside the product: OpenAI models are lanes in our model router for agent chat and
> embeddings, and OpenAI voices are one of the text-to-speech options an avatar can speak with.
-**How has using OpenAI products helped you/them?** (about 700 characters)
+**How has using OpenAI products helped you/them?** (668 characters)
> It changed who can reach 3D. Before the connector, making a model meant finding our site and
> learning an interface. Inside ChatGPT, someone describes an object in the conversation they are
@@ -69,7 +69,7 @@ The City and State fields assume a US location; the founder's location is not re
> made the product better everywhere: we wrote honest loading, error, and timeout states, removed
> anything that needed a key or a wallet from the free path, and documented every tool.
-**What makes your/their story special?** (about 640 characters)
+**What makes your/their story special?** (569 characters)
> 3D is usually the last thing people expect a chat assistant to do, and the hardest to do well:
> meshes, textures, skeletons, and animation all have to work, not just look right in a thumbnail. We
diff --git a/package-lock.json b/package-lock.json
index 5113aae24..ad982c8ed 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -227,6 +227,7 @@
},
"devDependencies": {
"@axe-core/playwright": "^4.13.0",
+ "@joplin/turndown-plugin-gfm": "^1.0.68",
"@playwright/test": "^1.63.0",
"@x402/fetch": "^2.14.0",
"adaptive-expressions": "^4.23.3",
@@ -234,6 +235,7 @@
"dotenv": "^17.4.2",
"es-module-lexer": "^2.0.0",
"fbx2gltf": "^0.9.7-p1",
+ "ffmpeg-static": "^5.3.0",
"glob": "^11.1.0",
"i18n-iso-countries": "^7.14.0",
"jsdom": "27.3.0",
@@ -242,6 +244,7 @@
"prettier": "^3.8.4",
"puppeteer": "^25.10.0",
"topojson-client": "^3.1.0",
+ "turndown": "^7.2.4",
"typescript": "^5.9.3",
"vite": "^8.3.0",
"vite-plugin-node-polyfills": "^0.28.0",
@@ -812,50 +815,6 @@
"node": ">=20"
}
},
- "mcp-bridge/node_modules/@solana/kit": {
- "version": "6.10.0",
- "resolved": "https://registry.npmjs.org/@solana/kit/-/kit-6.10.0.tgz",
- "integrity": "sha512-/WnnQp3uARh2JCFSfAakejTAqwmXVuMVTcRn5r2yDwY2yzZ4R6mt/Cl59VPimVLNSoTyN/KsEwhv9omr3ERazQ==",
- "license": "MIT",
- "dependencies": {
- "@solana/accounts": "6.10.0",
- "@solana/addresses": "6.10.0",
- "@solana/codecs": "6.10.0",
- "@solana/errors": "6.10.0",
- "@solana/functional": "6.10.0",
- "@solana/instruction-plans": "6.10.0",
- "@solana/instructions": "6.10.0",
- "@solana/keys": "6.10.0",
- "@solana/offchain-messages": "6.10.0",
- "@solana/plugin-core": "6.10.0",
- "@solana/plugin-interfaces": "6.10.0",
- "@solana/program-client-core": "6.10.0",
- "@solana/programs": "6.10.0",
- "@solana/rpc": "6.10.0",
- "@solana/rpc-api": "6.10.0",
- "@solana/rpc-parsed-types": "6.10.0",
- "@solana/rpc-spec-types": "6.10.0",
- "@solana/rpc-subscriptions": "6.10.0",
- "@solana/rpc-types": "6.10.0",
- "@solana/signers": "6.10.0",
- "@solana/subscribable": "6.10.0",
- "@solana/sysvars": "6.10.0",
- "@solana/transaction-confirmation": "6.10.0",
- "@solana/transaction-messages": "6.10.0",
- "@solana/transactions": "6.10.0"
- },
- "engines": {
- "node": ">=20.18.0"
- },
- "peerDependencies": {
- "typescript": ">=5.4.0"
- },
- "peerDependenciesMeta": {
- "typescript": {
- "optional": true
- }
- }
- },
"mcp-server": {
"name": "@three-ws/mcp-server",
"version": "1.2.3",
@@ -5732,6 +5691,22 @@
"node": ">=20.19.0"
}
},
+ "node_modules/@derhuerst/http-basic": {
+ "version": "8.2.4",
+ "resolved": "https://registry.npmjs.org/@derhuerst/http-basic/-/http-basic-8.2.4.tgz",
+ "integrity": "sha512-F9rL9k9Xjf5blCz8HsJRO4diy111cayL2vkY2XE4r4t3n0yPXVYy3KD3nJ1qbrSn9743UWSXH4IwuCa/HWlGFw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "caseless": "^0.12.0",
+ "concat-stream": "^2.0.0",
+ "http-response-object": "^3.0.1",
+ "parse-cache-control": "^1.0.1"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
"node_modules/@dimforge/rapier3d-compat": {
"version": "0.19.3",
"license": "Apache-2.0"
@@ -9353,6 +9328,13 @@
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
+ "node_modules/@joplin/turndown-plugin-gfm": {
+ "version": "1.0.68",
+ "resolved": "https://registry.npmjs.org/@joplin/turndown-plugin-gfm/-/turndown-plugin-gfm-1.0.68.tgz",
+ "integrity": "sha512-m8DfAQNC/V7g0j5H6Jv60WhekBBjodD+zTPGrU+g2m+ux/z8ZX07KQIl6kaAmbKwfvsQhC04op52g63I78sVgg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"license": "MIT",
@@ -10684,6 +10666,13 @@
"node": ">=10.3.0"
}
},
+ "node_modules/@mixmark-io/domino": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@mixmark-io/domino/-/domino-2.2.0.tgz",
+ "integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==",
+ "dev": true,
+ "license": "BSD-2-Clause"
+ },
"node_modules/@modelcontextprotocol/ext-apps": {
"version": "1.7.4",
"dev": true,
@@ -23558,6 +23547,13 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/caseless": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz",
+ "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
"node_modules/catering": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/catering/-/catering-2.1.1.tgz",
@@ -24057,6 +24053,22 @@
"version": "0.0.1",
"license": "MIT"
},
+ "node_modules/concat-stream": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
+ "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
+ "dev": true,
+ "engines": [
+ "node >= 6.0"
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "buffer-from": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.0.2",
+ "typedarray": "^0.0.6"
+ }
+ },
"node_modules/confbox": {
"version": "0.1.8",
"dev": true,
@@ -27400,6 +27412,50 @@
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"license": "MIT"
},
+ "node_modules/ffmpeg-static": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/ffmpeg-static/-/ffmpeg-static-5.3.0.tgz",
+ "integrity": "sha512-H+K6sW6TiIX6VGend0KQwthe+kaceeH/luE8dIZyOP35ik7ahYojDuqlTV1bOrtEwl01sy2HFNGQfi5IDJvotg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "GPL-3.0-or-later",
+ "dependencies": {
+ "@derhuerst/http-basic": "^8.2.0",
+ "env-paths": "^2.2.0",
+ "https-proxy-agent": "^5.0.0",
+ "progress": "^2.0.3"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/ffmpeg-static/node_modules/agent-base": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
+ "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 6.0.0"
+ }
+ },
+ "node_modules/ffmpeg-static/node_modules/https-proxy-agent": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
+ "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "6",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/file-uri-to-path": {
"version": "1.0.0",
"license": "MIT"
@@ -28913,6 +28969,23 @@
"node": ">= 14"
}
},
+ "node_modules/http-response-object": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/http-response-object/-/http-response-object-3.0.2.tgz",
+ "integrity": "sha512-bqX0XTF6fnXSQcEJ2Iuyr75yVakyjIDCqroJQ/aHfSdlM743Cwqoi2nDYMzLGWUcuTWGWy8AAvOKXTfiv6q9RA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "^10.0.3"
+ }
+ },
+ "node_modules/http-response-object/node_modules/@types/node": {
+ "version": "10.17.60",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-10.17.60.tgz",
+ "integrity": "sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/https-browserify": {
"version": "1.0.0",
"dev": true,
@@ -35893,6 +35966,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/parse-cache-control": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/parse-cache-control/-/parse-cache-control-1.0.1.tgz",
+ "integrity": "sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg==",
+ "dev": true
+ },
"node_modules/parse-css-color": {
"version": "0.2.1",
"license": "MIT",
@@ -36120,7 +36199,6 @@
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
- "dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.63.0"
@@ -36136,7 +36214,6 @@
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
- "dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
@@ -36356,6 +36433,16 @@
],
"license": "MIT"
},
+ "node_modules/progress": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
+ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
"node_modules/progress-events": {
"version": "1.1.0",
"license": "Apache-2.0 OR MIT"
@@ -41018,6 +41105,20 @@
"node": "*"
}
},
+ "node_modules/turndown": {
+ "version": "7.2.4",
+ "resolved": "https://registry.npmjs.org/turndown/-/turndown-7.2.4.tgz",
+ "integrity": "sha512-I8yFsfRzmzK0WV1pNNOA4A7y4RDfFxPRxb3t+e3ui14qSGOxGtiSP6GjeX+Y6CHb7HYaFj7ECUD7VE5kQMZWGQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@mixmark-io/domino": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=18",
+ "npm": ">=9"
+ }
+ },
"node_modules/tweetnacl": {
"version": "1.0.3",
"license": "Unlicense"
@@ -41307,6 +41408,13 @@
"version": "2.12.2",
"license": "MIT"
},
+ "node_modules/typedarray": {
+ "version": "0.0.6",
+ "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
+ "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/typescript": {
"version": "5.9.3",
"dev": true,
@@ -43107,32 +43215,6 @@
"express": "^5.2.1"
}
},
- "packages/agent-sniper/node_modules/playwright": {
- "version": "1.61.1",
- "license": "Apache-2.0",
- "dependencies": {
- "playwright-core": "1.61.1"
- },
- "bin": {
- "playwright": "cli.js"
- },
- "engines": {
- "node": ">=18"
- },
- "optionalDependencies": {
- "fsevents": "2.3.2"
- }
- },
- "packages/agent-sniper/node_modules/playwright-core": {
- "version": "1.61.1",
- "license": "Apache-2.0",
- "bin": {
- "playwright-core": "cli.js"
- },
- "engines": {
- "node": ">=18"
- }
- },
"packages/agentcore-payments-mcp": {
"name": "@three-ws/agentcore-payments-mcp",
"version": "0.1.5",
@@ -43971,50 +44053,6 @@
"node": ">=20"
}
},
- "packages/x402-mcp/node_modules/@solana/kit": {
- "version": "6.10.0",
- "resolved": "https://registry.npmjs.org/@solana/kit/-/kit-6.10.0.tgz",
- "integrity": "sha512-/WnnQp3uARh2JCFSfAakejTAqwmXVuMVTcRn5r2yDwY2yzZ4R6mt/Cl59VPimVLNSoTyN/KsEwhv9omr3ERazQ==",
- "license": "MIT",
- "dependencies": {
- "@solana/accounts": "6.10.0",
- "@solana/addresses": "6.10.0",
- "@solana/codecs": "6.10.0",
- "@solana/errors": "6.10.0",
- "@solana/functional": "6.10.0",
- "@solana/instruction-plans": "6.10.0",
- "@solana/instructions": "6.10.0",
- "@solana/keys": "6.10.0",
- "@solana/offchain-messages": "6.10.0",
- "@solana/plugin-core": "6.10.0",
- "@solana/plugin-interfaces": "6.10.0",
- "@solana/program-client-core": "6.10.0",
- "@solana/programs": "6.10.0",
- "@solana/rpc": "6.10.0",
- "@solana/rpc-api": "6.10.0",
- "@solana/rpc-parsed-types": "6.10.0",
- "@solana/rpc-spec-types": "6.10.0",
- "@solana/rpc-subscriptions": "6.10.0",
- "@solana/rpc-types": "6.10.0",
- "@solana/signers": "6.10.0",
- "@solana/subscribable": "6.10.0",
- "@solana/sysvars": "6.10.0",
- "@solana/transaction-confirmation": "6.10.0",
- "@solana/transaction-messages": "6.10.0",
- "@solana/transactions": "6.10.0"
- },
- "engines": {
- "node": ">=20.18.0"
- },
- "peerDependencies": {
- "typescript": ">=5.4.0"
- },
- "peerDependenciesMeta": {
- "typescript": {
- "optional": true
- }
- }
- },
"page-agent-sdk": {
"name": "@three-ws/page-agent",
"version": "0.2.1",
diff --git a/package.json b/package.json
index a92504460..ffbc40cd7 100644
--- a/package.json
+++ b/package.json
@@ -196,9 +196,9 @@
"announce:rank": "node scripts/announce-rank.mjs",
"announce:media": "node scripts/capture-doc-media.mjs --spec data/announce-media.json --out public/announce/img --manifest public/announce/media-manifest.json",
"check:announce": "node scripts/check-announce.mjs",
- "x:announce:check": "node scripts/x-announcement-pipeline.mjs check",
- "x:announce:plan": "node scripts/x-announcement-pipeline.mjs plan",
- "x:announce:run": "node scripts/x-announcement-pipeline.mjs run",
+ "x:content": "node scripts/x-content.mjs",
+ "x:content:check": "node scripts/x-content.mjs check",
+ "x:content:plan": "node scripts/x-content.mjs plan",
"changelog:push": "node scripts/changelog-telegram.mjs",
"changelog:push:x": "node scripts/changelog-x.mjs",
"tweet": "node scripts/post-tweet.mjs",
@@ -641,6 +641,7 @@
},
"devDependencies": {
"@axe-core/playwright": "^4.13.0",
+ "@joplin/turndown-plugin-gfm": "^1.0.68",
"@playwright/test": "^1.63.0",
"@x402/fetch": "^2.14.0",
"adaptive-expressions": "^4.23.3",
@@ -648,6 +649,7 @@
"dotenv": "^17.4.2",
"es-module-lexer": "^2.0.0",
"fbx2gltf": "^0.9.7-p1",
+ "ffmpeg-static": "^5.3.0",
"glob": "^11.1.0",
"i18n-iso-countries": "^7.14.0",
"jsdom": "27.3.0",
@@ -656,6 +658,7 @@
"prettier": "^3.8.4",
"puppeteer": "^25.10.0",
"topojson-client": "^3.1.0",
+ "turndown": "^7.2.4",
"typescript": "^5.9.3",
"vite": "^8.3.0",
"vite-plugin-node-polyfills": "^0.28.0",
diff --git a/pages/launch.html b/pages/launch.html
index 31e3df589..b20bff78c 100644
--- a/pages/launch.html
+++ b/pages/launch.html
@@ -1,35 +1,32 @@
<!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>
+ <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 data-i18n="launch.meta_title">Launch a Coin — mint a token for your 3D agent · three.ws</title>
+ <title>Launch a Coin for Your 3D AI Agent · three.ws</title>
<meta
name="description"
- content="Launch a coin for your 3D AI agent in one flow. Pick an agent, set the name, symbol, and image, then mint on pump.fun straight from your wallet — with an optional three.ws-branded vanity mint."
- data-i18n-attr="content:launch.meta_description"/>
- <meta name="robots" content="index, follow" />
+ content="The pump.fun launchpad for 3D AI agents. Pick your agent, name the coin and launch it from your wallet or your agent's wallet, then claim creator rewards on three.ws."
+ />
+ <meta name="robots" content="index, follow, max-image-preview:large" />
<link rel="canonical" href="https://three.ws/launch" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="three.ws" />
- <meta property="og:title" content="Launch a Coin — mint a token for your 3D agent" data-i18n-attr="content:launch.meta_og_title"/>
- <meta
- property="og:description"
- content="Pick an agent, set name + symbol + image, and mint a coin on pump.fun straight from your wallet."
- data-i18n-attr="content:launch.meta_og_description"/>
+ <meta property="og:title" content="Launch a coin for your 3D AI agent" />
+ <meta property="og:description" content="Pick an agent, name the coin, launch on pump.fun and claim creator rewards, all on three.ws." />
<meta property="og:url" content="https://three.ws/launch" />
- <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Launch+a+Coin&amp;d=Mint+a+coin+for+your+3D+AI+agent+in+one+flow%3A+pick+an+agent%2C+set+the+name%2C+symbol%2C+and+image%2C+then+launch+on+pump.fun+straight+from+your+wallet+with+an&amp;p=%2Flaunch" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Launch+a+Coin&amp;d=The+pump.fun+launchpad+for+3D+AI+agents.+Pick+your+agent%2C+launch+the+coin%2C+claim+creator+rewards+on+three.ws.&amp;p=%2Flaunch" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
+ <meta property="og:image:alt" content="Launch a Coin on three.ws" />
+ <meta property="og:locale" content="en_US" />
<meta name="twitter:card" content="summary_large_image" />
- <meta name="twitter:title" content="Launch a Coin — mint a token for your 3D agent" data-i18n-attr="content:launch.meta_twitter_title"/>
- <meta
- name="twitter:description"
- content="Pick an agent, set name + symbol + image, and mint a coin on pump.fun straight from your wallet."
- data-i18n-attr="content:launch.meta_twitter_description"/>
- <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Launch+a+Coin&amp;d=Mint+a+coin+for+your+3D+AI+agent+in+one+flow%3A+pick+an+agent%2C+set+the+name%2C+symbol%2C+and+image%2C+then+launch+on+pump.fun+straight+from+your+wallet+with+an&amp;p=%2Flaunch" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Launch a coin for your 3D AI agent" />
+ <meta name="twitter:description" content="Pick an agent, name the coin, launch on pump.fun and claim creator rewards, all on three.ws." />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Launch+a+Coin&amp;d=The+pump.fun+launchpad+for+3D+AI+agents.+Pick+your+agent%2C+launch+the+coin%2C+claim+creator+rewards+on+three.ws.&amp;p=%2Flaunch" />
<link rel="icon" href="/favicon.ico" sizes="any" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
@@ -42,124 +39,31 @@
<link rel="stylesheet" href="/fonts/fonts.css" />
<link rel="stylesheet" href="/mobile.css" />
- <style>
- .lc-page {
- min-height: 100vh;
- display: flex;
- flex-direction: column;
- }
- .lc-main {
- flex: 1;
- width: 100%;
- max-width: 880px;
- margin: 0 auto;
- padding: 1.5rem 1rem 4rem;
- box-sizing: border-box;
- }
- .lc-breadcrumb {
- font-size: 0.78rem;
- color: rgba(255, 255, 255, 0.4);
- margin-bottom: 1.4rem;
- display: flex;
- gap: 0.45rem;
- align-items: center;
- flex-wrap: wrap;
- }
- .lc-breadcrumb a {
- color: rgba(255, 255, 255, 0.55);
- text-decoration: none;
- }
- .lc-breadcrumb a:hover {
- color: #a4f0bc;
- }
- .lc-hero {
- text-align: center;
- margin-bottom: 1.8rem;
- }
- .lc-hero h1 {
- font-size: clamp(1.7rem, 4.5vw, 2.5rem);
- font-weight: 700;
- letter-spacing: -0.02em;
- margin: 0 0 0.6rem;
- background: linear-gradient(180deg, #fff, rgba(255, 255, 255, 0.62));
- -webkit-background-clip: text;
- background-clip: text;
- -webkit-text-fill-color: transparent;
- }
- .lc-hero p {
- font-size: clamp(0.92rem, 2vw, 1.05rem);
- color: rgba(255, 255, 255, 0.55);
- line-height: 1.6;
- max-width: 38ch;
- margin: 0 auto;
- }
- .lc-hero .lc-pill {
- display: inline-flex;
- align-items: center;
- gap: 0.4rem;
- font-size: 0.72rem;
- font-weight: 600;
- letter-spacing: 0.04em;
- color: #c8f0d8;
- background: rgba(164, 240, 188, 0.08);
- border: 1px solid rgba(164, 240, 188, 0.22);
- border-radius: 999px;
- padding: 0.3rem 0.7rem;
- margin-bottom: 1rem;
- }
- .lc-pill-dot {
- width: 6px;
- height: 6px;
- border-radius: 50%;
- background: #a4f0bc;
- box-shadow: 0 0 6px rgba(164, 240, 188, 0.6);
- }
- </style>
-
- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Launch a Coin","description":"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.","url":"https://three.ws/launch","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
-
- <meta property="og:locale" content="en_US">
- <meta property="og:image:alt" content="Launch a Coin — three.ws">
- <meta name="twitter:site" content="@trythreews">
-</head>
- <body class="lc-page">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Launch a Coin","description":"The pump.fun launchpad for 3D AI agents: pick your agent, launch the coin from your wallet or your agent's wallet, and claim creator rewards on three.ws.","url":"https://three.ws/launch","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="lc-main" id="main-content">
- <nav class="lc-breadcrumb" aria-label="Breadcrumb">
- <a href="/" data-i18n="launch.three_ws">three.ws</a>
- <span aria-hidden="true">/</span>
- <a href="/launches" data-i18n="launch.launches">Launches</a>
- <span aria-hidden="true">/</span>
- <span data-i18n="launch.launch_a_coin">Launch a Coin</span>
- </nav>
-
- <section class="lc-hero">
- <span class="lc-pill" data-i18n-html="launch.powered_by_pump_fun"><span class="lc-pill-dot"></span> Powered by pump.fun</span>
- <h1 data-i18n="launch.launch_a_coin_2">Launch a Coin</h1>
- <p data-i18n="launch.pick_your_agent_set_the_name_symbol">Pick your agent, set the name, symbol, and image — then mint on-chain straight from your wallet.</p>
- </section>
-
- <div id="launch-root"></div>
+ <main class="lx" id="main-content">
+ <div class="lx-head">
+ <div>
+ <p class="lx-eyebrow"><span class="lx-dot" aria-hidden="true"></span>pump.fun launchpad for 3D agents</p>
+ <h1>Launch a coin for your agent</h1>
+ <p class="lx-sub">Pick one of your 3D AI agents, name the coin and launch it on pump.fun. Creator rewards stay claimable right here.</p>
+ </div>
+ <div class="lx-tabs" id="lx-tabs" role="tablist" aria-label="Launchpad">
+ <button type="button" class="lx-tab" role="tab" id="tab-create" data-tab="create" aria-controls="panel-create" aria-selected="true">Create</button>
+ <button type="button" class="lx-tab" role="tab" id="tab-coins" data-tab="coins" aria-controls="panel-coins" aria-selected="false" tabindex="-1">My coins <span class="lx-tab-badge" id="coins-badge" hidden></span></button>
+ </div>
+ </div>
+ <div id="launch-app"></div>
</main>
<div id="footer-container"></div>
<script src="/footer.js"></script>
-
- <script type="module">
- // launch.js and its dependency chain (/studio/launch-panel.js,
- // /studio/fees-panel.js) live in public/ and are loaded by URL at
- // runtime. The specifier is kept in a var so Vite's import-analysis
- // leaves it as a browser-resolved runtime import instead of trying
- // to resolve a public-dir asset (which it refuses, aborting the dev
- // server / build:app).
- const spec = '/launch/launch.js';
- const { mountLaunchCoin } = await import(/* @vite-ignore */ spec);
- mountLaunchCoin(document.getElementById('launch-root'));
- </script>
+ <script type="module" src="/src/launch/launch-page.js"></script>
<script src="/brand.js" defer></script>
- <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
- <script type="module" src="/i18n.js"></script>
-</body>
+ <script type="module" src="/i18n.js"></script>
+ </body>
</html>
diff --git a/public/x-media/web-component-article/00-cover.png b/public/x-media/web-component-article/00-cover.png
new file mode 100644
index 000000000..fd935a083
Binary files /dev/null and b/public/x-media/web-component-article/00-cover.png differ
diff --git a/scripts/x-announcement-pipeline.mjs b/scripts/x-announcement-pipeline.mjs
deleted file mode 100644
index 82dc3a8f6..000000000
--- a/scripts/x-announcement-pipeline.mjs
+++ /dev/null
@@ -1,240 +0,0 @@
-#!/usr/bin/env node
-
-import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
-import { existsSync, readFileSync, writeFileSync } from 'node:fs';
-import { extname, resolve } from 'node:path';
-import { spawnSync } from 'node:child_process';
-import { fileURLToPath } from 'node:url';
-import { copyProblems, copySimilarity, weightedLength } from './lib/x-announcement-quality.mjs';
-
-const root = resolve(fileURLToPath(new URL('..', import.meta.url)));
-const args = process.argv.slice(2);
-const command = args.find((arg) => !arg.startsWith('--')) || 'check';
-const has = (flag) => args.includes(`--${flag}`);
-const value = (name, fallback = null) => {
- const inline = args.find((arg) => arg.startsWith(`--${name}=`));
- if (inline) return inline.slice(name.length + 3);
- const index = args.indexOf(`--${name}`);
- return index >= 0 && args[index + 1] && !args[index + 1].startsWith('--') ? args[index + 1] : fallback;
-};
-
-const configPath = resolve(root, value('config', 'data/x-announcement-pipeline.json'));
-const localStatePath = resolve(root, value('state', '.x-announcement-state.json'));
-const config = JSON.parse(readFileSync(configPath, 'utf8'));
-
-function textAt(path) {
- return readFileSync(resolve(root, path), 'utf8').trim();
-}
-
-function loadArchivePosts() {
- const paths = [
- 'data/archives/trythreews_tweets_2026-06-03.json',
- 'data/archives/trythreews_tweets_2026-05-16.json',
- ];
- const posts = [];
- for (const path of paths) {
- if (!existsSync(resolve(root, path))) continue;
- const payload = JSON.parse(readFileSync(resolve(root, path), 'utf8'));
- const rows = Array.isArray(payload) ? payload : payload.tweets || payload.data || [];
- for (const row of rows) {
- const text = row.text || row.full_text || row.tweet?.full_text || row.tweet?.text;
- if (text) posts.push(String(text));
- }
- }
- return posts;
-}
-
-function validate() {
- const errors = [];
- const notes = [];
- const heads = [];
- const ids = new Set();
- const allowedStatuses = new Set(['draft', 'review', 'approved', 'paused', 'posted']);
-
- for (const item of config.items || []) {
- const prefix = item.id || '<missing id>';
- if (!item.id || ids.has(item.id)) errors.push(`${prefix}: id is missing or duplicated`);
- ids.add(item.id);
- if (!allowedStatuses.has(item.status)) errors.push(`${prefix}: invalid status ${item.status}`);
- if (!item.lane || !item.pattern) errors.push(`${prefix}: lane and pattern are required`);
- if (!item.notBefore || !Number.isFinite(Date.parse(item.notBefore))) errors.push(`${prefix}: notBefore must be ISO-8601`);
- if (!Array.isArray(item.parts) || !item.parts.length) errors.push(`${prefix}: at least one post part is required`);
- if (!Array.isArray(item.media) || !item.media.length) errors.push(`${prefix}: every announcement requires media`);
- if ((item.media || []).length > 4) errors.push(`${prefix}: X accepts at most four images`);
-
- const mediaKinds = new Set();
- for (const media of item.media || []) {
- const path = resolve(root, media.path || '');
- if (!media.path || !existsSync(path)) errors.push(`${prefix}: missing media ${media.path || '<path>'}`);
- const extension = extname(media.path || '').toLowerCase();
- const kind = ['.mp4', '.mov'].includes(extension) ? 'video' : extension === '.gif' ? 'gif' : 'image';
- mediaKinds.add(kind);
- if (kind === 'image' && !String(media.alt || '').trim()) errors.push(`${prefix}: image ${media.path} needs alt text`);
- }
- if (mediaKinds.has('video') && (item.media.length !== 1 || mediaKinds.size !== 1)) errors.push(`${prefix}: video must be the only attachment`);
- if (mediaKinds.has('gif') && (item.media.length !== 1 || mediaKinds.size !== 1)) errors.push(`${prefix}: GIF must be the only attachment`);
-
- const parts = [];
- for (const partPath of item.parts || []) {
- if (!existsSync(resolve(root, partPath))) {
- errors.push(`${prefix}: missing post part ${partPath}`);
- continue;
- }
- parts.push(textAt(partPath));
- }
- for (let index = 0; index < parts.length; index++) {
- for (const problem of copyProblems(parts[index], { minimum: index === 0 ? 100 : 1 })) {
- errors.push(`${prefix} part ${index + 1}: ${problem}`);
- }
- }
- if (parts[0]) heads.push({ id: prefix, text: parts[0] });
- }
-
- const queueLimit = Number(config.quality?.queueSimilarityLimit ?? 0.34);
- for (let left = 0; left < heads.length; left++) {
- for (let right = left + 1; right < heads.length; right++) {
- const score = copySimilarity(heads[left].text, heads[right].text);
- if (score >= queueLimit) errors.push(`${heads[left].id} and ${heads[right].id}: queue similarity ${score.toFixed(2)} exceeds ${queueLimit}`);
- }
- }
-
- const archive = loadArchivePosts();
- const archiveLimit = Number(config.quality?.archiveSimilarityLimit ?? 0.42);
- for (const head of heads) {
- let closest = { score: 0, text: '' };
- for (const prior of archive) {
- const score = copySimilarity(head.text, prior);
- if (score > closest.score) closest = { score, text: prior };
- }
- if (closest.score >= archiveLimit) errors.push(`${head.id}: archive similarity ${closest.score.toFixed(2)} exceeds ${archiveLimit}`);
- else notes.push(`${head.id}: ${weightedLength(head.text)} chars, closest archive similarity ${closest.score.toFixed(2)}`);
- }
-
- return { errors, notes };
-}
-
-function printValidation(result) {
- for (const note of result.notes) console.log(`note ${note}`);
- if (result.errors.length) {
- for (const error of result.errors) console.error(`error ${error}`);
- return false;
- }
- console.log(`x-announcement-pipeline: ${config.items.length} item(s) passed`);
- return true;
-}
-
-function r2Settings() {
- const accountId = process.env.R2_ACCOUNT_ID;
- const accessKeyId = process.env.R2_ACCESS_KEY_ID;
- const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY;
- const bucket = process.env.X_ANNOUNCEMENT_STATE_BUCKET;
- if (!(accountId && accessKeyId && secretAccessKey && bucket)) return null;
- return {
- bucket,
- key: process.env.X_ANNOUNCEMENT_STATE_KEY || 'state/x-announcements.json',
- client: new S3Client({
- region: 'auto',
- endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
- credentials: { accessKeyId, secretAccessKey },
- }),
- };
-}
-
-async function bodyText(body) {
- if (!body) return '';
- if (typeof body.transformToString === 'function') return body.transformToString();
- const chunks = [];
- for await (const chunk of body) chunks.push(chunk);
- return Buffer.concat(chunks).toString('utf8');
-}
-
-async function loadState() {
- const remote = r2Settings();
- if (remote) {
- try {
- const object = await remote.client.send(new GetObjectCommand({ Bucket: remote.bucket, Key: remote.key }));
- return JSON.parse(await bodyText(object.Body));
- } catch (error) {
- if (error?.name !== 'NoSuchKey' && error?.$metadata?.httpStatusCode !== 404) throw error;
- return { version: 1, published: [] };
- }
- }
- if (!existsSync(localStatePath)) return { version: 1, published: [] };
- return JSON.parse(readFileSync(localStatePath, 'utf8'));
-}
-
-async function saveState(state) {
- const serialized = `${JSON.stringify(state, null, '\t')}\n`;
- const remote = r2Settings();
- if (remote) {
- await remote.client.send(new PutObjectCommand({
- Bucket: remote.bucket,
- Key: remote.key,
- Body: serialized,
- ContentType: 'application/json',
- }));
- return;
- }
- writeFileSync(localStatePath, serialized);
-}
-
-function publisherArgs(item, dryRun) {
- const publishArgs = ['scripts/post-tweet.mjs'];
- if (item.parts.length === 1) publishArgs.push('--file', item.parts[0]);
- else publishArgs.push('--thread', JSON.stringify(item.parts));
- for (const media of item.media) {
- publishArgs.push('--media', media.path);
- if (media.alt) publishArgs.push('--alt', media.alt);
- }
- if (dryRun) publishArgs.push('--dry-run');
- return publishArgs;
-}
-
-function showPlan() {
- for (const item of [...config.items].sort((a, b) => a.notBefore.localeCompare(b.notBefore))) {
- console.log(`${item.notBefore} ${item.status.padEnd(8)} ${item.lane.padEnd(10)} ${item.pattern.padEnd(10)} ${item.id}`);
- }
-}
-
-async function run() {
- const check = validate();
- if (!printValidation(check)) process.exit(1);
- const state = await loadState();
- const published = new Set((state.published || []).map((row) => row.id));
- const requested = value('id');
- const now = Date.parse(value('now', new Date().toISOString()));
- const item = [...config.items]
- .filter((row) => row.status === 'approved')
- .filter((row) => !published.has(row.id))
- .filter((row) => !requested || row.id === requested)
- .filter((row) => requested || Date.parse(row.notBefore) <= now)
- .sort((a, b) => a.notBefore.localeCompare(b.notBefore))[0];
- if (!item) {
- console.log(requested ? `No approved unpublished item named ${requested}.` : 'No approved announcement is due.');
- return;
- }
-
- const dryRun = has('dry-run');
- console.log(`${dryRun ? 'Previewing' : 'Publishing'} ${item.id} (${item.lane}/${item.pattern})`);
- const result = spawnSync(process.execPath, publisherArgs(item, dryRun), { cwd: root, encoding: 'utf8', stdio: 'inherit' });
- if (result.status !== 0) process.exit(result.status || 1);
- if (dryRun) return;
- state.published = [
- ...(state.published || []),
- { id: item.id, publishedAt: new Date().toISOString(), lane: item.lane, pattern: item.pattern },
- ];
- await saveState(state);
- console.log(`Recorded ${item.id} in ${r2Settings() ? 'R2' : localStatePath}`);
-}
-
-if (command === 'check') {
- if (!printValidation(validate())) process.exit(1);
-} else if (command === 'plan') {
- showPlan();
-} else if (command === 'run') {
- await run();
-} else {
- console.error('Usage: node scripts/x-announcement-pipeline.mjs <check|plan|run> [--dry-run] [--id slug]');
- process.exit(1);
-}
-
diff --git a/scripts/x-content.mjs b/scripts/x-content.mjs
new file mode 100644
index 000000000..da35627e9
--- /dev/null
+++ b/scripts/x-content.mjs
@@ -0,0 +1,333 @@
+#!/usr/bin/env node
+// Operator CLI for the @trythreews content queue (data/x-content/queue.json).
+// The same engine runs in production as /api/cron/x-content.
+//
+// npm run x:content -- check validate every item
+// npm run x:content -- plan when each item lands, and what is blocking it
+// npm run x:content -- run --dry-run [--id slug] print the exact X API calls for the next due item
+// npm run x:content -- run --id slug publish one item now (owner-approved posts only)
+// npm run x:content -- import <blog-slug|url> --as post|article --id slug [--lane l] [--pattern p]
+// npm run x:content -- prepare-video <input> --out public/x-media/<id>/clip.mp4 [--captions file.srt] [--item slug]
+//
+// Env: reads .env.local then .env. DATABASE_URL gives plan/run the shared
+// publish ledger; X_API_KEY, X_API_SECRET, X_ACCESS_TOKEN, X_ACCESS_SECRET are
+// needed only to publish.
+
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { dirname, extname, relative, resolve } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+import { QUEUE_PATH, loadQueue, validateQueue } from '../api/_lib/x-content/queue.js';
+import { dueAt, pickDue } from '../api/_lib/x-content/schedule.js';
+import { runTick } from '../api/_lib/x-content/runner.js';
+import { dbStore, memoryStore } from '../api/_lib/x-content/state.js';
+import { VIDEO_LIMITS, mediaType, parseFfmpegProbe } from '../api/_lib/x-content/media.js';
+import { weightedLength } from '../api/_lib/x-content/quality.js';
+
+const root = resolve(fileURLToPath(new URL('..', import.meta.url)));
+
+function loadEnvFile(path) {
+ if (!existsSync(path)) return;
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
+ const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/i);
+ if (match && !process.env[match[1]]) process.env[match[1]] = match[2].replace(/^["']|["']$/g, '');
+ }
+}
+loadEnvFile(resolve(root, '.env.local'));
+loadEnvFile(resolve(root, '.env'));
+
+const args = process.argv.slice(2);
+const VALUE_FLAGS = new Set(['--id', '--as', '--lane', '--pattern', '--out', '--captions', '--item', '--now']);
+const positional = args.filter((arg, index) => !arg.startsWith('--') && !VALUE_FLAGS.has(args[index - 1]));
+const has = (flag) => args.includes(`--${flag}`);
+const option = (name, fallback = null) => {
+ const inline = args.find((arg) => arg.startsWith(`--${name}=`));
+ if (inline) return inline.slice(name.length + 3);
+ const index = args.indexOf(`--${name}`);
+ return index >= 0 && args[index + 1] && !args[index + 1].startsWith('--') ? args[index + 1] : fallback;
+};
+const command = positional[0] || 'check';
+
+function fail(message) {
+ console.error(message);
+ process.exit(1);
+}
+
+const store = () => (process.env.DATABASE_URL ? dbStore() : memoryStore());
+
+async function check() {
+ const queue = loadQueue(root);
+ const state = await store().load();
+ const { problems, notes } = validateQueue(queue, root, { state });
+ for (const note of notes) console.log(`note ${note}`);
+ let blocking = 0;
+ for (const item of queue.items) {
+ for (const problem of problems[item.id]) {
+ // Drafts are allowed to be unfinished; anything headed for X is not.
+ const severe = ['review', 'approved'].includes(item.status);
+ if (severe) blocking++;
+ console[severe ? 'error' : 'log'](`${severe ? 'error' : 'draft'} ${item.id}: ${problem}`);
+ }
+ }
+ if (blocking) fail(`x-content: ${blocking} problem(s) in items under review or approved`);
+ console.log(`x-content: ${queue.items.length} item(s) checked`);
+}
+
+async function plan() {
+ const queue = loadQueue(root);
+ const s = store();
+ const state = await s.load();
+ const { problems } = validateQueue(queue, root, { state });
+ const published = new Map((state.published || []).map((row) => [row.id, row]));
+ console.log(`ledger: ${s.label}\n`);
+ for (const item of [...queue.items].sort((a, b) => dueAt(a, queue.cadence) - dueAt(b, queue.cadence))) {
+ const row = published.get(item.id);
+ const when = row ? `posted ${row.publishedAt}` : `lands ${new Date(dueAt(item, queue.cadence)).toISOString()}`;
+ const flag = problems[item.id].length ? ` (${problems[item.id].length} problem(s))` : '';
+ console.log(`${when.padEnd(33)} ${item.status.padEnd(8)} ${item.kind.padEnd(7)} ${item.lane.padEnd(10)} ${item.pattern.padEnd(10)} ${item.id}${flag}${row ? ` ${row.url}` : ''}`);
+ }
+ const publishable = queue.items.filter((item) => !problems[item.id].length);
+ const next = pickDue({ items: publishable, state, cadence: queue.cadence, quality: queue.quality });
+ console.log(`\nnow: ${next.item ? `${next.item.id} is due` : next.reason}`);
+}
+
+async function run() {
+ const dryRun = has('dry-run');
+ if (!dryRun && !process.env.DATABASE_URL) fail('Publishing needs DATABASE_URL so the shared ledger prevents a double post. Use --dry-run to preview.');
+ const s = store();
+ if (!dryRun && !(await s.acquireLock())) fail('Another publish (the cron or another operator) holds the lock. Try again in a few minutes.');
+ try {
+ const now = option('now') ? Date.parse(option('now')) : Date.now();
+ const result = await runTick({ root, store: s, now, dryRun, requestedId: option('id') });
+ for (const row of result.blocked) console.error(`blocked ${row.id}:\n ${row.problems.join('\n ')}`);
+ if (result.preview) {
+ console.log(`Preview of ${result.preview.id} (${result.preview.kind}), lands ${result.preview.dueAt}:\n`);
+ for (const call of result.preview.calls) console.log(JSON.stringify(call, null, 2));
+ } else if (result.published) {
+ console.log(`Published ${result.published.id}: ${result.published.url}`);
+ } else {
+ console.log(result.reason);
+ if (result.skipped) process.exit(1);
+ }
+ } finally {
+ if (!dryRun) await s.releaseLock();
+ }
+}
+
+// --- import --------------------------------------------------------------
+
+function slugOk(value) {
+ return /^[a-z0-9][a-z0-9-]{1,80}$/.test(String(value || ''));
+}
+
+async function fetchBytes(url) {
+ const response = await fetch(url, { headers: { 'user-agent': 'three.ws content importer (+https://three.ws)' }, redirect: 'follow' });
+ if (!response.ok) throw new Error(`${url} answered HTTP ${response.status}`);
+ return { buffer: Buffer.from(await response.arrayBuffer()), type: response.headers.get('content-type') || '' };
+}
+
+// A three.ws URL maps onto this checkout, so importing our own blog never
+// depends on the live site being deployed.
+function localPathFor(url) {
+ const parsed = new URL(url);
+ if (parsed.hostname !== 'three.ws' && parsed.hostname !== 'www.three.ws') return null;
+ const path = decodeURIComponent(parsed.pathname);
+ for (const candidate of [path.slice(1), `public${path}`, `${path.slice(1)}.html`]) {
+ if (candidate && existsSync(resolve(root, candidate)) && extname(candidate)) return resolve(root, candidate);
+ }
+ return null;
+}
+
+async function loadSource(ref) {
+ if (/^https?:\/\//.test(ref)) {
+ const local = localPathFor(ref);
+ const html = local ? readFileSync(local, 'utf8') : (await fetchBytes(ref)).buffer.toString('utf8');
+ return { html, baseUrl: ref };
+ }
+ if (slugOk(ref) && existsSync(resolve(root, `blog/${ref}.html`))) {
+ return { html: readFileSync(resolve(root, `blog/${ref}.html`), 'utf8'), baseUrl: `https://three.ws/blog/${ref}` };
+ }
+ fail(`${ref} is neither a URL nor a post in blog/`);
+}
+
+// Store an image as an upload-ready file under public/x-media/<id>/. SVG and
+// AVIF are rasterized because X accepts neither.
+async function saveImage(src, baseUrl, dir, name) {
+ const absolute = new URL(src, baseUrl).toString();
+ const local = localPathFor(absolute);
+ const buffer = local ? readFileSync(local) : (await fetchBytes(absolute)).buffer;
+ const { default: sharp } = await import('sharp');
+ const meta = await sharp(buffer, { animated: true }).metadata();
+ let ext = { jpeg: '.jpg', png: '.png', webp: '.webp', gif: '.gif' }[meta.format];
+ let bytes = buffer;
+ if (!ext) {
+ bytes = await sharp(buffer, { density: 192 }).png().toBuffer();
+ ext = '.png';
+ }
+ if (ext !== '.gif' && bytes.length > 5 * 1024 * 1024) {
+ bytes = await sharp(bytes).resize({ width: 2400, withoutEnlargement: true }).jpeg({ quality: 88, mozjpeg: true }).toBuffer();
+ ext = '.jpg';
+ }
+ const path = `${dir}/${name}${ext}`;
+ mkdirSync(resolve(root, dir), { recursive: true });
+ writeFileSync(resolve(root, path), bytes);
+ return path;
+}
+
+// The house style bans en and em dashes; imported prose gets a comma instead.
+const noDashes = (text) => String(text).replace(/\s*[\u2013\u2014]\s*/g, ', ');
+
+const meta = (doc, selector) => doc.querySelector(selector)?.getAttribute('content')?.trim() || '';
+
+async function importSource() {
+ const ref = positional[1];
+ const as = option('as', 'post');
+ const id = option('id');
+ if (!ref) fail('Usage: import <blog-slug|url> --as post|article --id slug');
+ if (!['post', 'article'].includes(as)) fail('--as must be post or article');
+ if (!slugOk(id)) fail('--id must be a lowercase slug');
+ const queue = loadQueue(root);
+ if (queue.items.some((item) => item.id === id)) fail(`${id} is already in the queue`);
+
+ const { parse } = await import('node-html-parser');
+ const { html, baseUrl } = await loadSource(ref);
+ const doc = parse(html);
+ const canonical = doc.querySelector('link[rel="canonical"]')?.getAttribute('href') || meta(doc, 'meta[property="og:url"]') || baseUrl;
+ const title = (meta(doc, 'meta[property="og:title"]') || doc.querySelector('title')?.textContent || id).trim();
+ const description = meta(doc, 'meta[property="og:description"]') || meta(doc, 'meta[name="description"]');
+ const ogImage = meta(doc, 'meta[property="og:image"]') || meta(doc, 'meta[name="twitter:image"]');
+ const mediaDir = `public/x-media/${id}`;
+ const cover = ogImage ? await saveImage(ogImage, baseUrl, mediaDir, '00-cover') : null;
+
+ const item = {
+ id,
+ status: 'draft',
+ kind: as,
+ lane: option('lane', as === 'article' ? 'article' : 'community'),
+ pattern: option('pattern', as === 'article' ? 'longform' : 'mechanism'),
+ notBefore: new Date(Math.ceil((Date.now() + 86400000) / 3600000) * 3600000).toISOString(),
+ source: { url: canonical, importedAt: new Date().toISOString() },
+ };
+
+ if (as === 'post') {
+ const link = ` ${canonical}`;
+ let lead = description || title;
+ while (weightedLength(`${lead}${link}`) > 280) lead = lead.replace(/\s+\S+$/, '');
+ item.posts = [{ text: `${lead}${link}`, media: cover ? [{ path: cover, alt: description || title }] : [] }];
+ } else {
+ const { default: TurndownService } = await import('turndown');
+ const { gfm } = await import('@joplin/turndown-plugin-gfm');
+ const content =
+ doc.querySelector('article') || doc.querySelector('main .post-wrap') || doc.querySelector('main') || doc.querySelector('body');
+ for (const selector of ['script', 'style', 'nav', 'header', 'footer', 'aside', 'form', 'button', 'svg', 'canvas', 'iframe', 'video', 'noscript', '.post-meta', '#nav-container', '#footer-container']) {
+ for (const node of content.querySelectorAll(selector)) node.remove();
+ }
+ // Site chrome inside the post body: "← Blog" style back links.
+ for (const anchor of content.querySelectorAll('a')) {
+ if (/^\s*[\u2190<]/.test(anchor.textContent)) (anchor.parentNode?.textContent.trim() === anchor.textContent.trim() ? anchor.parentNode : anchor).remove();
+ }
+ // The title becomes the Article title, not a heading inside the body.
+ content.querySelector('h1')?.remove();
+ let index = 0;
+ for (const img of content.querySelectorAll('img')) {
+ const src = img.getAttribute('src');
+ if (!src || src.startsWith('data:')) {
+ img.remove();
+ continue;
+ }
+ try {
+ img.setAttribute('src', await saveImage(src, baseUrl, mediaDir, String(++index).padStart(2, '0')));
+ } catch (err) {
+ console.warn(`skipped image ${src}: ${err.message}`);
+ img.remove();
+ }
+ }
+ for (const anchor of content.querySelectorAll('a[href]')) {
+ anchor.setAttribute('href', new URL(anchor.getAttribute('href'), baseUrl).toString());
+ }
+ const turndown = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced', bulletListMarker: '-' });
+ turndown.use(gfm);
+ turndown.remove(['style', 'script']);
+ const markdown = noDashes(turndown.turndown(content.innerHTML))
+ .replace(/\n{3,}/g, '\n\n')
+ .replace(/(\n\s*(?:\* \* \*|-{3,})\s*)+$/, '')
+ .trim();
+ const body = `data/x-content/articles/${id}.md`;
+ mkdirSync(resolve(root, dirname(body)), { recursive: true });
+ writeFileSync(resolve(root, body), `${markdown}\n\n---\n\nOriginally published at [${new URL(canonical).host}${new URL(canonical).pathname}](${canonical}).\n`);
+ item.article = { title: noDashes(title.replace(/\s*[|\u2013\u2014-]\s*three\.ws\s*$/i, '')), body };
+ if (cover) item.article.cover = { path: cover };
+ if (description) item.posts = [{ text: noDashes(description) }];
+ }
+
+ queue.items.push(item);
+ writeFileSync(resolve(root, QUEUE_PATH), `${JSON.stringify(queue, null, '\t')}\n`);
+ console.log(`Added ${id} as a ${as} draft from ${canonical}`);
+ if (item.article) console.log(`Article body: ${item.article.body}`);
+ console.log(`Media: ${mediaDir}/`);
+ console.log('Edit the copy in your own voice, run `npm run x:content -- check`, then set status to review.');
+}
+
+// --- video -----------------------------------------------------------------
+
+function ffmpegPath() {
+ const bundled = resolve(root, 'node_modules/ffmpeg-static/ffmpeg');
+ return existsSync(bundled) ? bundled : 'ffmpeg';
+}
+
+function prepareVideo() {
+ const input = positional[1];
+ const out = option('out');
+ if (!input || !existsSync(input)) fail('Usage: prepare-video <input> --out public/x-media/<id>/clip.mp4 [--captions file.srt] [--item slug]');
+ if (!out || !out.startsWith('public/x-media/') || mediaType(out)?.kind !== 'video' || extname(out) !== '.mp4') fail('--out must be an .mp4 under public/x-media/');
+ const captions = option('captions');
+ if (captions && !existsSync(captions)) fail(`captions file ${captions} is missing`);
+
+ const L = VIDEO_LIMITS;
+ const filters = [
+ `scale='min(${L.maxWidth},iw)':'min(${L.maxHeight},ih)':force_original_aspect_ratio=decrease`,
+ 'scale=trunc(iw/2)*2:trunc(ih/2)*2',
+ ];
+ // Most of the feed autoplays muted: burned-in captions carry the story.
+ if (captions) {
+ const escaped = resolve(captions).replace(/\\/g, '\\\\').replace(/:/g, '\\:').replace(/'/g, "\\'");
+ filters.push(`subtitles='${escaped}':force_style='FontName=Inter,FontSize=18,PrimaryColour=&H00FFFFFF,OutlineColour=&H90000000,BorderStyle=3,Outline=6,Shadow=0,MarginV=36'`);
+ }
+ mkdirSync(resolve(root, dirname(out)), { recursive: true });
+ const ffmpeg = ffmpegPath();
+ const encode = spawnSync(ffmpeg, [
+ '-y', '-hide_banner', '-i', input,
+ '-t', String(L.maxDurationSec),
+ '-vf', filters.join(','),
+ '-fpsmax', String(L.maxFps),
+ '-c:v', 'libx264', '-profile:v', 'high', '-preset', 'slow', '-crf', '20', '-pix_fmt', 'yuv420p',
+ '-c:a', 'aac', '-b:a', '128k', '-ar', '48000', '-ac', '2',
+ '-movflags', '+faststart',
+ resolve(root, out),
+ ], { encoding: 'utf8', stdio: ['ignore', 'inherit', 'pipe'] });
+ if (encode.status !== 0) fail(`ffmpeg failed:\n${encode.stderr.split('\n').slice(-15).join('\n')}`);
+
+ const probeRun = spawnSync(ffmpeg, ['-hide_banner', '-i', resolve(root, out)], { encoding: 'utf8' });
+ const probe = parseFfmpegProbe(probeRun.stderr);
+ if (!probe) fail(`could not read the encoded file:\n${probeRun.stderr}`);
+ console.log(`Encoded ${relative(root, resolve(root, out))}`);
+ console.log(JSON.stringify(probe, null, '\t'));
+
+ const itemId = option('item');
+ if (!itemId) {
+ console.log('\nAdd this as the media entry\'s "probe", or rerun with --item <slug> to write it.');
+ return;
+ }
+ const queue = loadQueue(root);
+ const item = queue.items.find((row) => row.id === itemId);
+ if (!item) fail(`no queue item named ${itemId}`);
+ const post = (item.posts ||= [{ text: '' }])[0];
+ post.media = [{ path: out, probe }];
+ writeFileSync(resolve(root, QUEUE_PATH), `${JSON.stringify(queue, null, '\t')}\n`);
+ console.log(`\nAttached to ${itemId} as the head post's only media.`);
+}
+
+const commands = { check, plan, run, import: importSource, 'prepare-video': prepareVideo };
+if (!commands[command]) fail(`Unknown command ${command}. Commands: ${Object.keys(commands).join(', ')}`);
+await commands[command]();
diff --git a/src/launch/launch-model.js b/src/launch/launch-model.js
new file mode 100644
index 000000000..1048d6315
--- /dev/null
+++ b/src/launch/launch-model.js
@@ -0,0 +1,127 @@
+// Pure logic behind /launch: form validation, the cost preview, and the small
+// formatting rules the page shares with its tests. No DOM, no network.
+
+export const NAME_MAX = 32;
+export const SYMBOL_MAX = 10;
+export const DESCRIPTION_MAX = 500;
+export const MAX_SOL_BUY_IN = 50;
+export const MAX_USDC_BUY_IN = 1_000_000;
+// pump.fun create fee + mint and curve rent, the same estimate the server's
+// agent-wallet preflight uses.
+export const DEFAULT_CREATE_COST_SOL = 0.022;
+export const DEV_BUY_PRESETS = Object.freeze({ sol: ['0.1', '0.5', '1', '2'], usdc: ['10', '50', '100', '250'] });
+
+/** Tickers are uppercase ASCII letters and digits, the way every launchpad shows them. */
+export function normalizeSymbol(raw) {
+ return String(raw || '')
+ .toUpperCase()
+ .replace(/[^A-Z0-9]/g, '')
+ .slice(0, SYMBOL_MAX);
+}
+
+/** A ticker suggestion from a name: the first letters of each word, else the name itself. */
+export function suggestSymbol(name) {
+ const words = String(name || '').trim().split(/\s+/).filter(Boolean);
+ if (!words.length) return '';
+ const initials = normalizeSymbol(words.map((w) => w[0]).join(''));
+ if (words.length > 1 && initials.length >= 2) return initials;
+ return normalizeSymbol(words.join(''));
+}
+
+/** Parse the dev-buy input. Returns a finite, non-negative number or NaN. */
+export function parseBuyIn(raw) {
+ const s = String(raw ?? '').trim();
+ if (s === '') return 0;
+ if (!/^\d*\.?\d*$/.test(s)) return NaN;
+ const n = Number(s);
+ return Number.isFinite(n) && n >= 0 ? n : NaN;
+}
+
+/**
+ * Everything that must be true before the Launch button arms, as a list of
+ * human-readable problems (empty when ready). Order matches the form top-down
+ * so the first item is the next thing to fix.
+ */
+export function launchProblems(form, { quote = 'sol' } = {}) {
+ const problems = [];
+ if (!form.agentId) problems.push({ field: 'agent', text: 'Pick the 3D agent this coin belongs to' });
+ const name = String(form.name || '').trim();
+ if (!name) problems.push({ field: 'name', text: 'Name your coin' });
+ else if ([...name].length > NAME_MAX) problems.push({ field: 'name', text: `Name must be ${NAME_MAX} characters or fewer` });
+ const symbol = normalizeSymbol(form.symbol);
+ if (symbol.length < 2) problems.push({ field: 'symbol', text: 'Ticker needs at least two letters or digits' });
+ if (String(form.description || '').length > DESCRIPTION_MAX) {
+ problems.push({ field: 'description', text: `Description must be ${DESCRIPTION_MAX} characters or fewer` });
+ }
+ const buy = parseBuyIn(form.buyIn);
+ const cap = quote === 'usdc' ? MAX_USDC_BUY_IN : MAX_SOL_BUY_IN;
+ if (Number.isNaN(buy)) problems.push({ field: 'buyIn', text: 'Dev buy must be a number' });
+ else if (buy > cap) problems.push({ field: 'buyIn', text: `Dev buy is capped at ${cap.toLocaleString('en-US')} ${quote.toUpperCase()}` });
+ for (const key of ['website', 'twitter', 'telegram']) {
+ const v = String(form[key] || '').trim();
+ if (v && v.length > 200) problems.push({ field: key, text: `${key} link is too long` });
+ }
+ return problems;
+}
+
+/**
+ * The launch cost preview. The fee is floored to the quote's base units exactly
+ * as the server computes it, so the preview matches the signed transaction.
+ * @returns {{ quote:'SOL'|'USDC', buyIn:number, fee:number, feeBps:number,
+ * createSol:number, totalSol:number, totalQuote:number }}
+ */
+export function launchCost({ buyIn, quote = 'sol', feeBps = 0, createCostSol = DEFAULT_CREATE_COST_SOL }) {
+ const buy = Math.max(0, Number.isFinite(buyIn) ? buyIn : 0);
+ const decimals = quote === 'usdc' ? 6 : 9;
+ const scale = 10 ** decimals;
+ const atomics = Math.floor(buy * scale);
+ const feeAtomics = feeBps > 0 ? Math.floor((atomics * feeBps) / 10_000) : 0;
+ const fee = feeAtomics / scale;
+ const isUsdc = quote === 'usdc';
+ return {
+ quote: isUsdc ? 'USDC' : 'SOL',
+ buyIn: buy,
+ fee,
+ feeBps,
+ createSol: createCostSol,
+ totalSol: isUsdc ? createCostSol : createCostSol + buy + fee,
+ totalQuote: isUsdc ? buy + fee : 0,
+ };
+}
+
+/** Trim trailing zeros for display without losing sub-cent precision. */
+export function formatAmount(n, maxDecimals = 6) {
+ if (!Number.isFinite(n)) return '0';
+ if (n === 0) return '0';
+ const fixed = n.toFixed(maxDecimals).replace(/\.?0+$/, '');
+ return fixed === '0' || fixed === '-0' ? `<${(1 / 10 ** maxDecimals).toFixed(maxDecimals)}` : fixed;
+}
+
+/** "EPjF…Dt1v" */
+export function shortAddress(a, head = 4, tail = 4) {
+ const s = String(a || '');
+ return s.length > head + tail + 1 ? `${s.slice(0, head)}…${s.slice(-tail)}` : s;
+}
+
+/** A post announcing the launch, for the success screen's share button. */
+export function shareText({ name, symbol, mint, agentName }) {
+ const who = agentName ? ` for my 3D AI agent ${agentName}` : '';
+ return `I just launched $${symbol} (${name})${who} on @trythreews\n\nhttps://three.ws/launches/${mint}`;
+}
+
+/** Map a server or wallet error to one sentence a launcher can act on. */
+export function friendlyLaunchError(err) {
+ const code = err?.code || '';
+ const msg = String(err?.message || err || '');
+ if (code === 'USER_REJECTED' || /reject|denied|cancel/i.test(msg)) return 'You cancelled the request in your wallet. Nothing was sent.';
+ if (code === 'launch_payload_too_large') return msg.charAt(0).toUpperCase() + msg.slice(1) + '.';
+ if (code === 'insufficient_funds' || code === 'insufficient_usdc' || /insufficient (funds|lamports)|0x1\b/i.test(msg)) {
+ return 'Not enough balance to cover the dev buy, fee and network costs. Lower the dev buy or add funds.';
+ }
+ if (code === 'wallet not linked to your account' || /not linked/i.test(msg)) return 'Link this wallet to your three.ws account, then launch again.';
+ if (code === 'unauthorized' || /sign in required/i.test(msg)) return 'Your session expired. Sign in again to launch.';
+ if (code === 'rate_limited') return 'Too many attempts in a short time. Wait a moment and try again.';
+ if (/blockhash not found|block height exceeded|expired/i.test(msg)) return 'The transaction expired before it was sent. Launch again to get a fresh one.';
+ if (code === 'rpc_unavailable' || /failed to fetch|network/i.test(msg)) return 'Could not reach the Solana network. Check your connection and try again.';
+ return msg ? msg.replace(/^Error:\s*/, '') : 'Something went wrong. Nothing was charged; try again.';
+}
diff --git a/src/launch/launch-page.css b/src/launch/launch-page.css
new file mode 100644
index 000000000..e3d0b6a55
--- /dev/null
+++ b/src/launch/launch-page.css
@@ -0,0 +1,1217 @@
+/* /launch: the three.ws coin launchpad for 3D agents. Built on the platform
+ tokens in public/tokens.css so it follows the light/dark theme. */
+
+.lx {
+ --lx-accent: #86efac;
+ --lx-accent-ink: #052e16;
+ --lx-accent-soft: rgba(134, 239, 172, 0.1);
+ --lx-accent-stroke: rgba(134, 239, 172, 0.34);
+ --lx-field: rgba(255, 255, 255, 0.035);
+ --lx-field-focus: rgba(255, 255, 255, 0.06);
+ width: 100%;
+ max-width: 1160px;
+ margin: 0 auto;
+ padding: 28px 20px 96px;
+ box-sizing: border-box;
+ color: var(--ink);
+ font-family: var(--font-body);
+}
+:root[data-theme='light'] .lx {
+ --lx-accent: #15803d;
+ --lx-accent-ink: #ffffff;
+ --lx-accent-soft: rgba(21, 128, 61, 0.08);
+ --lx-accent-stroke: rgba(21, 128, 61, 0.35);
+ --lx-field: rgba(15, 18, 28, 0.03);
+ --lx-field-focus: rgba(15, 18, 28, 0.055);
+}
+.lx *,
+.lx *::before,
+.lx *::after {
+ box-sizing: border-box;
+}
+
+/* ── Header + tabs ─────────────────────────────────────────────────────── */
+.lx-head {
+ display: flex;
+ align-items: flex-end;
+ justify-content: space-between;
+ gap: 20px;
+ flex-wrap: wrap;
+ margin-bottom: 24px;
+}
+.lx-eyebrow {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0 0 10px;
+ font: 600 11px/1 var(--font-mono);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+}
+.lx-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--lx-accent);
+ box-shadow: 0 0 10px var(--lx-accent);
+}
+.lx-head h1 {
+ margin: 0;
+ font: 700 clamp(26px, 4vw, 38px) / 1.08 var(--font-display);
+ letter-spacing: -0.025em;
+ color: var(--ink-bright, var(--ink));
+}
+.lx-sub {
+ margin: 10px 0 0;
+ max-width: 60ch;
+ font-size: 15px;
+ line-height: 1.55;
+ color: var(--ink-dim);
+}
+.lx-tabs {
+ display: inline-flex;
+ gap: 4px;
+ padding: 4px;
+ border-radius: var(--radius-pill);
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+}
+.lx-tab {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 38px;
+ padding: 0 16px;
+ border: 0;
+ border-radius: var(--radius-pill);
+ background: transparent;
+ color: var(--ink-dim);
+ font: 600 14px var(--font-body);
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+}
+.lx-tab:hover {
+ color: var(--ink);
+ background: var(--surface-2);
+}
+.lx-tab[aria-selected='true'] {
+ color: var(--ink-bright, var(--ink));
+ background: var(--surface-3);
+}
+.lx-tab:focus-visible {
+ outline: 2px solid var(--lx-accent);
+ outline-offset: 2px;
+}
+.lx-tab-badge {
+ min-width: 20px;
+ padding: 2px 6px;
+ border-radius: var(--radius-pill);
+ background: var(--lx-accent);
+ color: var(--lx-accent-ink);
+ font: 700 11px/1.3 var(--font-mono);
+ text-align: center;
+}
+
+/* ── Create layout ─────────────────────────────────────────────────────── */
+.lx-grid {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 360px;
+ gap: 20px;
+ align-items: start;
+ animation: lx-in 0.25s ease both;
+}
+@media (max-width: 920px) {
+ .lx-grid {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+@keyframes lx-in {
+ from {
+ opacity: 0;
+ transform: translateY(6px);
+ }
+ to {
+ opacity: 1;
+ transform: none;
+ }
+}
+.lx-form {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ min-width: 0;
+}
+.lx-card {
+ border-radius: var(--radius-lg);
+ border: 1px solid var(--stroke);
+ background: var(--surface-glass);
+ padding: 20px;
+}
+.lx-card-h {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 12px;
+ margin: 0 0 4px;
+}
+.lx-card-h h2 {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin: 0;
+ font: 650 15px/1.3 var(--font-body);
+ color: var(--ink-bright, var(--ink));
+}
+.lx-step {
+ display: inline-grid;
+ place-items: center;
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ font: 700 11px var(--font-mono);
+ background: var(--surface-3);
+ color: var(--ink-dim);
+}
+.lx-step.done {
+ background: var(--lx-accent);
+ color: var(--lx-accent-ink);
+}
+.lx-card-note {
+ margin: 0 0 16px;
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--ink-dim);
+}
+.lx-link {
+ color: var(--lx-accent);
+ text-decoration: none;
+ font-weight: 600;
+ font-size: 13px;
+ border-radius: 4px;
+}
+.lx-link:hover {
+ text-decoration: underline;
+}
+.lx-link:focus-visible {
+ outline: 2px solid var(--lx-accent);
+ outline-offset: 2px;
+}
+
+/* ── Agent picker ──────────────────────────────────────────────────────── */
+.lx-agents {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(132px, 1fr));
+ gap: 10px;
+}
+.lx-agent {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 8px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ color: inherit;
+ text-align: left;
+ font: inherit;
+ cursor: pointer;
+ transition: border-color 0.15s, background 0.15s, transform 0.15s;
+}
+.lx-agent:hover {
+ border-color: var(--stroke-strong);
+ background: var(--surface-2);
+ transform: translateY(-1px);
+}
+.lx-agent:active {
+ transform: translateY(0);
+}
+.lx-agent:focus-visible {
+ outline: 2px solid var(--lx-accent);
+ outline-offset: 2px;
+}
+.lx-agent[aria-checked='true'] {
+ border-color: var(--lx-accent-stroke);
+ background: var(--lx-accent-soft);
+ box-shadow: 0 0 0 1px var(--lx-accent-stroke);
+}
+.lx-agent[aria-checked='true']::after {
+ content: '';
+ position: absolute;
+ top: 12px;
+ right: 12px;
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ background: var(--lx-accent)
+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M3.5 8.5l3 3 6-7' fill='none' stroke='%23052e16' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")
+ center / 12px no-repeat;
+}
+.lx-agent-img {
+ aspect-ratio: 1;
+ width: 100%;
+ border-radius: 7px;
+ object-fit: cover;
+ background: var(--surface-2);
+}
+.lx-agent-ph {
+ display: grid;
+ place-items: center;
+ aspect-ratio: 1;
+ width: 100%;
+ border-radius: 7px;
+ background: linear-gradient(135deg, var(--lx-accent-soft), var(--surface-2));
+ font: 700 28px var(--font-display);
+ color: var(--lx-accent);
+}
+.lx-agent-name {
+ display: block;
+ font-size: 13px;
+ font-weight: 600;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.lx-agent-sub {
+ display: block;
+ margin-top: 2px;
+ font-size: 11px;
+ color: var(--ink-dim);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.lx-agent-new {
+ display: grid;
+ place-items: center;
+ gap: 6px;
+ min-height: 160px;
+ padding: 12px;
+ border-radius: var(--radius-md);
+ border: 1px dashed var(--stroke-strong);
+ color: var(--ink-dim);
+ font-size: 13px;
+ font-weight: 600;
+ text-align: center;
+ text-decoration: none;
+ transition: color 0.15s, border-color 0.15s, background 0.15s;
+}
+.lx-agent-new:hover {
+ color: var(--lx-accent);
+ border-color: var(--lx-accent-stroke);
+ background: var(--lx-accent-soft);
+}
+.lx-agent-new:focus-visible {
+ outline: 2px solid var(--lx-accent);
+ outline-offset: 2px;
+}
+.lx-agent-new span {
+ font-size: 26px;
+ line-height: 1;
+}
+.lx-agent-search {
+ margin-bottom: 12px;
+}
+.lx-skel {
+ border-radius: var(--radius-md);
+ min-height: 168px;
+ background: linear-gradient(100deg, var(--surface-1) 30%, var(--surface-3) 50%, var(--surface-1) 70%);
+ background-size: 200% 100%;
+ animation: lx-shimmer 1.2s linear infinite;
+}
+@keyframes lx-shimmer {
+ to {
+ background-position: -200% 0;
+ }
+}
+.lx-empty {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 12px;
+ padding: 18px;
+ border-radius: var(--radius-md);
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ font-size: 14px;
+ line-height: 1.55;
+ color: var(--ink-dim);
+}
+.lx-empty strong {
+ color: var(--ink-bright, var(--ink));
+}
+.lx-empty.is-error {
+ border-color: rgba(248, 113, 113, 0.3);
+ background: rgba(248, 113, 113, 0.06);
+}
+
+/* ── Fields ────────────────────────────────────────────────────────────── */
+.lx-row {
+ display: grid;
+ grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr);
+ gap: 12px;
+}
+@media (max-width: 560px) {
+ .lx-row {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+.lx-field {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ min-width: 0;
+ margin-top: 12px;
+}
+.lx-label {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--ink);
+}
+.lx-label .lx-opt,
+.lx-count {
+ font-weight: 500;
+ color: var(--ink-dim);
+ font-family: var(--font-mono);
+ font-size: 11px;
+}
+.lx-input,
+.lx-textarea {
+ width: 100%;
+ min-height: 44px;
+ padding: 11px 13px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--stroke);
+ background: var(--lx-field);
+ color: var(--ink-bright, var(--ink));
+ font: 400 15px/1.4 var(--font-body);
+ transition: border-color 0.15s, background 0.15s, box-shadow 0.15s;
+}
+.lx-input::placeholder,
+.lx-textarea::placeholder {
+ color: var(--ink-dim);
+ opacity: 0.8;
+}
+.lx-input:hover,
+.lx-textarea:hover {
+ border-color: var(--stroke-strong);
+}
+.lx-input:focus,
+.lx-textarea:focus {
+ outline: none;
+ border-color: var(--lx-accent-stroke);
+ background: var(--lx-field-focus);
+ box-shadow: 0 0 0 3px var(--lx-accent-soft);
+}
+.lx-input[aria-invalid='true'] {
+ border-color: rgba(248, 113, 113, 0.55);
+}
+.lx-input.is-mono {
+ font-family: var(--font-mono);
+ letter-spacing: 0.04em;
+}
+.lx-textarea {
+ min-height: 96px;
+ resize: vertical;
+}
+.lx-hint {
+ margin: 0;
+ font-size: 12px;
+ line-height: 1.45;
+ color: var(--ink-dim);
+}
+.lx-disclosure {
+ margin-top: 12px;
+}
+.lx-disclosure summary {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-height: 32px;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--ink-dim);
+ cursor: pointer;
+ list-style: none;
+ border-radius: 6px;
+}
+.lx-disclosure summary::-webkit-details-marker {
+ display: none;
+}
+.lx-disclosure summary::before {
+ content: '+';
+ display: inline-grid;
+ place-items: center;
+ width: 18px;
+ height: 18px;
+ border-radius: 5px;
+ background: var(--surface-2);
+ font-family: var(--font-mono);
+}
+.lx-disclosure[open] summary::before {
+ content: '−';
+}
+.lx-disclosure summary:hover {
+ color: var(--ink);
+}
+.lx-disclosure summary:focus-visible {
+ outline: 2px solid var(--lx-accent);
+ outline-offset: 2px;
+}
+
+/* ── Image ─────────────────────────────────────────────────────────────── */
+.lx-image {
+ display: grid;
+ grid-template-columns: 120px minmax(0, 1fr);
+ gap: 16px;
+ align-items: center;
+}
+@media (max-width: 520px) {
+ .lx-image {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+.lx-image-thumb {
+ position: relative;
+ width: 120px;
+ height: 120px;
+ border-radius: var(--radius-md);
+ overflow: hidden;
+ background: var(--surface-2);
+ border: 1px solid var(--stroke);
+}
+.lx-image-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.lx-drop {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 16px;
+ border-radius: var(--radius-md);
+ border: 1px dashed var(--stroke-strong);
+ background: var(--surface-1);
+ transition: border-color 0.15s, background 0.15s;
+}
+.lx-drop.is-over {
+ border-color: var(--lx-accent);
+ background: var(--lx-accent-soft);
+}
+.lx-drop-actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+/* ── Segmented controls, chips, toggles ────────────────────────────────── */
+.lx-seg {
+ display: grid;
+ grid-auto-flow: column;
+ grid-auto-columns: minmax(0, 1fr);
+ gap: 6px;
+ padding: 4px;
+ border-radius: var(--radius-md);
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+}
+.lx-seg button {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 2px;
+ min-height: 44px;
+ padding: 8px 12px;
+ border-radius: 7px;
+ border: 1px solid transparent;
+ background: transparent;
+ color: var(--ink-dim);
+ font: 600 13px var(--font-body);
+ text-align: left;
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s, border-color 0.15s;
+}
+.lx-seg button small {
+ font-weight: 500;
+ font-size: 11px;
+ color: var(--ink-dim);
+}
+.lx-seg button:hover:not(:disabled) {
+ color: var(--ink);
+ background: var(--surface-2);
+}
+.lx-seg button[aria-checked='true'] {
+ color: var(--ink-bright, var(--ink));
+ background: var(--lx-accent-soft);
+ border-color: var(--lx-accent-stroke);
+}
+.lx-seg button:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+.lx-seg button:focus-visible {
+ outline: 2px solid var(--lx-accent);
+ outline-offset: 1px;
+}
+.lx-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-top: 8px;
+}
+.lx-chip {
+ min-height: 32px;
+ padding: 0 12px;
+ border-radius: var(--radius-pill);
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ color: var(--ink);
+ font: 600 12px var(--font-mono);
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s;
+}
+.lx-chip:hover {
+ background: var(--surface-3);
+ border-color: var(--stroke-strong);
+}
+.lx-chip[aria-pressed='true'] {
+ border-color: var(--lx-accent-stroke);
+ background: var(--lx-accent-soft);
+}
+.lx-chip:focus-visible {
+ outline: 2px solid var(--lx-accent);
+ outline-offset: 2px;
+}
+.lx-buy {
+ position: relative;
+}
+.lx-buy .lx-input {
+ padding-right: 64px;
+}
+.lx-buy-unit {
+ position: absolute;
+ right: 14px;
+ top: 50%;
+ transform: translateY(-50%);
+ font: 600 12px var(--font-mono);
+ color: var(--ink-dim);
+ pointer-events: none;
+}
+.lx-toggle-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ margin-top: 14px;
+ padding: 12px 14px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+}
+.lx-toggle-row strong {
+ display: block;
+ font-size: 13px;
+}
+.lx-toggle-row span {
+ display: block;
+ margin-top: 2px;
+ font-size: 12px;
+ color: var(--ink-dim);
+ line-height: 1.4;
+}
+.lx-switch {
+ position: relative;
+ flex-shrink: 0;
+ width: 42px;
+ height: 24px;
+ border-radius: var(--radius-pill);
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-3);
+ cursor: pointer;
+ transition: background 0.18s, border-color 0.18s;
+}
+.lx-switch::after {
+ content: '';
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ background: var(--ink);
+ transition: transform 0.18s;
+}
+.lx-switch[aria-checked='true'] {
+ background: var(--lx-accent);
+ border-color: var(--lx-accent);
+}
+.lx-switch[aria-checked='true']::after {
+ transform: translateX(18px);
+ background: var(--lx-accent-ink);
+}
+.lx-switch:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+.lx-switch:focus-visible {
+ outline: 2px solid var(--lx-accent);
+ outline-offset: 2px;
+}
+
+/* ── Buttons ───────────────────────────────────────────────────────────── */
+.lx-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 40px;
+ padding: 0 16px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-2);
+ color: var(--ink-bright, var(--ink));
+ font: 600 13px var(--font-body);
+ text-decoration: none;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s, transform 0.1s, opacity 0.15s;
+}
+.lx-btn:hover:not(:disabled) {
+ background: var(--surface-3);
+}
+.lx-btn:active:not(:disabled) {
+ transform: scale(0.98);
+}
+.lx-btn:focus-visible {
+ outline: 2px solid var(--lx-accent);
+ outline-offset: 2px;
+}
+.lx-btn:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+.lx-btn.is-primary {
+ width: 100%;
+ min-height: 52px;
+ border: 0;
+ background: var(--lx-accent);
+ color: var(--lx-accent-ink);
+ font-size: 15px;
+ font-weight: 700;
+ box-shadow: 0 8px 28px -12px var(--lx-accent);
+}
+.lx-btn.is-primary:hover:not(:disabled) {
+ background: var(--lx-accent);
+ filter: brightness(1.06);
+}
+.lx-btn.is-primary:disabled {
+ box-shadow: none;
+}
+.lx-btn.is-small {
+ min-height: 32px;
+ padding: 0 12px;
+ font-size: 12px;
+}
+
+/* ── Sidebar: preview, costs, checklist ────────────────────────────────── */
+.lx-side {
+ position: sticky;
+ top: calc(var(--header-h, 56px) + 16px);
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+@media (max-width: 920px) {
+ .lx-side {
+ position: static;
+ }
+}
+.lx-preview {
+ overflow: hidden;
+ padding: 0;
+}
+.lx-stage {
+ position: relative;
+ aspect-ratio: 1 / 0.82;
+ background:
+ radial-gradient(120% 90% at 50% 100%, var(--lx-accent-soft), transparent 60%),
+ var(--surface-1);
+ border-bottom: 1px solid var(--stroke);
+}
+.lx-stage model-viewer,
+.lx-stage > img {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ --poster-color: transparent;
+ background: transparent;
+}
+.lx-stage-empty {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ padding: 24px;
+ text-align: center;
+ font-size: 13px;
+ color: var(--ink-dim);
+}
+.lx-stage-tag {
+ position: absolute;
+ left: 12px;
+ top: 12px;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 10px;
+ border-radius: var(--radius-pill);
+ background: rgba(0, 0, 0, 0.55);
+ backdrop-filter: blur(8px);
+ color: #fff;
+ font: 600 11px var(--font-mono);
+}
+.lx-coin {
+ display: grid;
+ grid-template-columns: 56px minmax(0, 1fr);
+ gap: 12px;
+ align-items: center;
+ padding: 16px;
+}
+.lx-coin-img {
+ width: 56px;
+ height: 56px;
+ border-radius: 12px;
+ object-fit: cover;
+ background: var(--surface-3);
+}
+.lx-coin-ph {
+ display: grid;
+ place-items: center;
+ width: 56px;
+ height: 56px;
+ border-radius: 12px;
+ background: var(--surface-3);
+ color: var(--ink-dim);
+ font: 700 18px var(--font-display);
+}
+.lx-coin-name {
+ margin: 0;
+ font: 700 16px/1.25 var(--font-display);
+ color: var(--ink-bright, var(--ink));
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.lx-coin-sym {
+ margin: 2px 0 0;
+ font: 600 12px var(--font-mono);
+ color: var(--lx-accent);
+}
+.lx-coin-desc {
+ grid-column: 1 / -1;
+ margin: 0;
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--ink-dim);
+ overflow-wrap: anywhere;
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+.lx-coin-link {
+ grid-column: 1 / -1;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font: 500 11px var(--font-mono);
+ color: var(--ink-dim);
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+.lx-rows {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ margin: 0;
+ padding: 16px;
+}
+.lx-rows div {
+ display: flex;
+ justify-content: space-between;
+ gap: 12px;
+ font-size: 13px;
+}
+.lx-rows dt {
+ color: var(--ink-dim);
+}
+.lx-rows dd {
+ margin: 0;
+ font-family: var(--font-mono);
+ font-size: 12px;
+ color: var(--ink);
+ text-align: right;
+}
+.lx-rows .is-total {
+ margin-top: 4px;
+ padding-top: 10px;
+ border-top: 1px solid var(--stroke);
+}
+.lx-rows .is-total dt,
+.lx-rows .is-total dd {
+ font-weight: 700;
+ color: var(--ink-bright, var(--ink));
+}
+.lx-rows .is-fee dd {
+ color: var(--lx-accent);
+}
+.lx-checklist {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin: 0;
+ padding: 14px 16px;
+ list-style: none;
+ font-size: 13px;
+ color: var(--ink-dim);
+}
+.lx-checklist li {
+ display: flex;
+ gap: 8px;
+}
+.lx-checklist li::before {
+ content: '';
+ flex-shrink: 0;
+ width: 6px;
+ height: 6px;
+ margin-top: 7px;
+ border-radius: 50%;
+ background: var(--warn);
+}
+.lx-checklist button {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: inherit;
+ font: inherit;
+ text-align: left;
+ cursor: pointer;
+ text-decoration: underline dotted;
+ text-underline-offset: 3px;
+}
+.lx-checklist button:hover {
+ color: var(--ink);
+}
+.lx-wallet {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ padding: 12px 16px;
+ font-size: 13px;
+}
+.lx-wallet-addr {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ font-family: var(--font-mono);
+ font-size: 12px;
+}
+.lx-wallet-addr::before {
+ content: '';
+ flex-shrink: 0;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--success);
+}
+.lx-badge {
+ display: inline-flex;
+ align-items: center;
+ padding: 2px 8px;
+ border-radius: var(--radius-pill);
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-2);
+ font: 600 10px/1.5 var(--font-mono);
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ white-space: nowrap;
+}
+.lx-badge.is-good {
+ border-color: var(--lx-accent-stroke);
+ background: var(--lx-accent-soft);
+ color: var(--lx-accent);
+}
+.lx-fine {
+ margin: 0;
+ padding: 0 4px;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--ink-dim);
+ text-align: center;
+}
+.lx-fine a {
+ color: inherit;
+}
+
+/* ── Progress / result dialog ──────────────────────────────────────────── */
+.lx-dialog {
+ width: min(460px, calc(100vw - 32px));
+ max-height: calc(100vh - 32px);
+ padding: 0;
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-lg);
+ background: var(--bg-1, #111318);
+ color: var(--ink);
+ box-shadow: 0 30px 80px -20px rgba(0, 0, 0, 0.6);
+}
+.lx-dialog::backdrop {
+ background: rgba(3, 4, 8, 0.6);
+ backdrop-filter: blur(4px);
+}
+.lx-dialog[open] {
+ animation: lx-pop 0.2s ease both;
+}
+@keyframes lx-pop {
+ from {
+ opacity: 0;
+ transform: translateY(8px) scale(0.98);
+ }
+ to {
+ opacity: 1;
+ transform: none;
+ }
+}
+.lx-dialog-body {
+ padding: 24px;
+}
+.lx-dialog h2 {
+ margin: 0 0 6px;
+ font: 700 20px/1.25 var(--font-display);
+ color: var(--ink-bright, var(--ink));
+}
+.lx-dialog p {
+ margin: 0;
+ font-size: 14px;
+ line-height: 1.55;
+ color: var(--ink-dim);
+}
+.lx-steps {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ margin: 20px 0 0;
+ padding: 0;
+ list-style: none;
+}
+.lx-steps li {
+ display: grid;
+ grid-template-columns: 22px minmax(0, 1fr);
+ gap: 12px;
+ align-items: center;
+ font-size: 14px;
+ color: var(--ink-dim);
+}
+.lx-steps li[data-state='active'] {
+ color: var(--ink-bright, var(--ink));
+ font-weight: 600;
+}
+.lx-steps li[data-state='done'] {
+ color: var(--ink);
+}
+.lx-steps li[data-state='error'] {
+ color: var(--danger);
+}
+.lx-steps .ic {
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ border: 2px solid var(--stroke-strong);
+}
+.lx-steps li[data-state='active'] .ic {
+ border-color: var(--lx-accent);
+ border-top-color: transparent;
+ animation: lx-spin 0.8s linear infinite;
+}
+.lx-steps li[data-state='done'] .ic {
+ border-color: var(--lx-accent);
+ background: var(--lx-accent)
+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M3.5 8.5l3 3 6-7' fill='none' stroke='%23052e16' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")
+ center / 12px no-repeat;
+}
+.lx-steps li[data-state='error'] .ic {
+ border-color: var(--danger);
+ background: rgba(248, 113, 113, 0.18);
+}
+.lx-steps small {
+ display: block;
+ margin-top: 2px;
+ font-weight: 400;
+ font-size: 12px;
+ color: var(--ink-dim);
+}
+@keyframes lx-spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+.lx-result-coin {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ margin: 18px 0;
+ padding: 14px;
+ border-radius: var(--radius-md);
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+}
+.lx-ca {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 4px;
+ font: 500 12px var(--font-mono);
+ color: var(--ink-dim);
+}
+.lx-actions {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+ margin-top: 18px;
+}
+.lx-actions .is-wide {
+ grid-column: 1 / -1;
+}
+.lx-alert {
+ margin-top: 16px;
+ padding: 12px 14px;
+ border-radius: var(--radius-md);
+ border: 1px solid rgba(248, 113, 113, 0.3);
+ background: rgba(248, 113, 113, 0.07);
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--ink);
+}
+.lx-alert.is-good {
+ border-color: var(--lx-accent-stroke);
+ background: var(--lx-accent-soft);
+}
+.lx-alert.is-warn {
+ border-color: rgba(251, 191, 36, 0.3);
+ background: rgba(251, 191, 36, 0.07);
+}
+
+/* ── My coins ──────────────────────────────────────────────────────────── */
+.lx-coins {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ animation: lx-in 0.25s ease both;
+}
+.lx-reward {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ gap: 16px;
+ align-items: center;
+}
+@media (max-width: 600px) {
+ .lx-reward {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+.lx-reward-kicker {
+ margin: 0 0 6px;
+ font: 600 11px var(--font-mono);
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+}
+.lx-reward-amt {
+ margin: 0;
+ font: 700 26px/1.1 var(--font-display);
+ color: var(--ink-bright, var(--ink));
+}
+.lx-reward-amt small {
+ font-size: 14px;
+ color: var(--ink-dim);
+ font-weight: 600;
+}
+.lx-reward-meta {
+ margin: 6px 0 0;
+ font-size: 12px;
+ color: var(--ink-dim);
+}
+.lx-coin-list {
+ display: flex;
+ flex-direction: column;
+ margin-top: 14px;
+ border-top: 1px solid var(--stroke);
+}
+.lx-coin-row {
+ display: grid;
+ grid-template-columns: 40px minmax(0, 1fr) auto;
+ gap: 12px;
+ align-items: center;
+ padding: 10px 0;
+ border-bottom: 1px solid var(--hairline, var(--stroke));
+}
+.lx-coin-row:last-child {
+ border-bottom: 0;
+}
+.lx-coin-row img,
+.lx-coin-row .lx-coin-ph {
+ width: 40px;
+ height: 40px;
+ border-radius: 9px;
+ font-size: 14px;
+}
+.lx-coin-row a {
+ color: var(--ink-bright, var(--ink));
+ text-decoration: none;
+ font-weight: 600;
+ font-size: 14px;
+}
+.lx-coin-row a:hover {
+ text-decoration: underline;
+}
+.lx-coin-row p {
+ margin: 2px 0 0;
+ font-size: 12px;
+ color: var(--ink-dim);
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+.lx-coin-row-links {
+ display: flex;
+ gap: 6px;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .lx-grid,
+ .lx-coins,
+ .lx-dialog[open] {
+ animation: none;
+ }
+ .lx-skel {
+ animation: none;
+ }
+ .lx-steps li[data-state='active'] .ic {
+ animation-duration: 2.4s;
+ }
+ .lx-agent,
+ .lx-btn,
+ .lx-switch::after {
+ transition: none;
+ }
+}
diff --git a/src/launch/launch-page.js b/src/launch/launch-page.js
new file mode 100644
index 000000000..838d5b2f2
--- /dev/null
+++ b/src/launch/launch-page.js
@@ -0,0 +1,1314 @@
+// /launch: pick one of your 3D agents, name a coin, launch it on pump.fun and
+// claim its creator rewards, all on three.ws.
+//
+// Data flow:
+// GET /api/auth/me, /api/avatars who is here and which agents they own
+// GET /api/pump/launch-config live fee, v1 activation, create cost
+// POST /api/pump/build-metadata image + metadata pinned, linked to the agent
+// POST /api/pump/launch-prep server-built tx (mint pre-signed, fee inside)
+// wallet signs → RPC → confirm → POST /api/pump/launch-confirm
+// POST /api/pump/launch-agent the agent's own wallet launches instead
+// GET /api/pump/my-coins coins + unclaimed rewards per creator wallet
+// POST /api/pump/collect-creator-fee-prep wallet claim (all quote mints)
+// POST /api/pump/collect-creator-fee-agent agent-wallet claim
+//
+// Launch Studio recipe links (?reward=) need the fee-split handoff the full
+// studio panel owns, so those visits mount that panel instead.
+
+import './launch-page.css';
+import { ensureRiskAck } from '../shared/risk-ack.js';
+import { ensureModelViewer } from '../shared/model-viewer-loader.js';
+import {
+ DESCRIPTION_MAX,
+ DEV_BUY_PRESETS,
+ NAME_MAX,
+ SYMBOL_MAX,
+ formatAmount,
+ friendlyLaunchError,
+ launchCost,
+ launchProblems,
+ normalizeSymbol,
+ parseBuyIn,
+ shareText,
+ shortAddress,
+ suggestSymbol,
+} from './launch-model.js';
+import {
+ connectLaunchWallet,
+ injectedProvider,
+ linkWallet,
+ restoreLaunchWallet,
+ signAndBroadcast,
+ solBalance,
+ waitForConfirmation,
+ walletInstalled,
+} from './launch-wallet.js';
+
+const IMAGE_MAX_BYTES = 4 * 1024 * 1024;
+const IMAGE_MAX_DIM = 1024;
+
+const $ = (sel, root = document) => root.querySelector(sel);
+const esc = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+
+const state = {
+ config: null,
+ user: undefined,
+ agents: null,
+ agentsError: '',
+ agentQuery: '',
+ form: {
+ agentId: null,
+ name: '',
+ symbol: '',
+ symbolTouched: false,
+ description: '',
+ website: '',
+ twitter: '',
+ telegram: '',
+ buyIn: '',
+ quote: 'sol',
+ rewards: 'creator',
+ mayhem: false,
+ launcher: 'wallet',
+ txFormat: 'auto',
+ imageDataUrl: '',
+ imageName: '',
+ },
+ wallet: null,
+ walletBusy: false,
+ walletError: '',
+ walletConflict: null,
+ balance: null,
+ agentWallet: null,
+ agentWalletError: '',
+ running: false,
+ coins: null,
+ coinsError: '',
+ claiming: new Set(),
+};
+
+// ── Networking ─────────────────────────────────────────────────────────────
+
+async function api(path, { method = 'GET', body } = {}) {
+ const res = await fetch(path, {
+ method,
+ credentials: 'include',
+ headers: body ? { 'content-type': 'application/json' } : undefined,
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const issues = Array.isArray(data?.issues) ? data.issues.map((i) => i.message).join('; ') : '';
+ throw Object.assign(new Error(data?.error_description || issues || data?.error || `Request failed (${res.status})`), {
+ code: data?.error,
+ status: res.status,
+ });
+ }
+ return data;
+}
+
+const selectedAgent = () => state.agents?.find((a) => a.id === state.form.agentId) || null;
+const feeBps = () => state.config?.launch_fee_bps ?? 0;
+const cost = () =>
+ launchCost({
+ buyIn: parseBuyIn(state.form.buyIn),
+ quote: state.form.quote,
+ feeBps: feeBps(),
+ createCostSol: state.config?.create_cost_sol_estimate,
+ });
+
+// ── Boot ───────────────────────────────────────────────────────────────────
+
+async function boot() {
+ const root = $('#launch-app');
+ const params = new URL(location.href).searchParams;
+ if (params.get('reward')) {
+ $('#lx-tabs').hidden = true;
+ mountRecipePanel(root);
+ return;
+ }
+ applyPrefill(params);
+ renderShell(root);
+ wireTabs(params.get('tab') === 'coins' ? 'coins' : 'create');
+ wireForm();
+ updateDerived();
+
+ api('/api/pump/launch-config')
+ .then(({ data }) => {
+ state.config = data;
+ renderLaunchOptions();
+ updateDerived();
+ })
+ .catch(() => {
+ state.config = { launch_fee_bps: 0, create_cost_sol_estimate: 0.022, tx_v1: { active: false }, config_error: true };
+ updateDerived();
+ });
+
+ restoreLaunchWallet().then((w) => {
+ if (w && !state.wallet) {
+ state.wallet = w;
+ refreshBalance();
+ renderWallet();
+ updateDerived();
+ }
+ });
+
+ await loadIdentity(params.get('avatar'));
+}
+
+async function loadIdentity(wantedAvatar) {
+ state.agents = null;
+ state.agentsError = '';
+ renderAgents();
+ try {
+ const me = await fetch('/api/auth/me', { credentials: 'include' });
+ if (me.status === 401 || me.status === 403) state.user = null;
+ else if (!me.ok) throw new Error(`the session check answered ${me.status}`);
+ else state.user = (await me.json()).user || null;
+
+ if (state.user) {
+ const { avatars = [] } = await api('/api/avatars?limit=100');
+ state.agents = avatars;
+ const match = wantedAvatar && avatars.find((a) => a.id === wantedAvatar || a.slug === wantedAvatar);
+ state.form.agentId = (match || avatars[0])?.id || null;
+ } else {
+ state.agents = [];
+ }
+ } catch (err) {
+ state.agentsError = /failed to fetch/i.test(err.message) ? 'three.ws could not be reached' : err.message;
+ state.agents = [];
+ }
+ renderAgents();
+ renderPreviewStage();
+ updateDerived();
+ if (!$('#panel-coins').hidden) loadCoins();
+}
+
+function applyPrefill(params) {
+ const f = state.form;
+ f.name = (params.get('name') || '').slice(0, NAME_MAX);
+ if (params.get('symbol')) {
+ f.symbol = normalizeSymbol(params.get('symbol'));
+ f.symbolTouched = true;
+ } else if (f.name) f.symbol = suggestSymbol(f.name);
+ f.description = (params.get('description') || '').slice(0, DESCRIPTION_MAX);
+ const buy = parseBuyIn(params.get('initialBuy'));
+ if (buy > 0) f.buyIn = String(buy);
+ let image = params.get('image') || '';
+ if (!image && params.get('imageSession')) {
+ try {
+ image = sessionStorage.getItem('twx.launch.image') || '';
+ } catch {
+ image = '';
+ }
+ }
+ if (image.startsWith('data:image/')) {
+ f.imageDataUrl = image;
+ f.imageName = 'snapshot.png';
+ } else if (/^https:\/\//.test(image)) {
+ importImageUrl(image);
+ }
+}
+
+// Recipe deep links keep their fee-routing promise through the full studio panel.
+async function mountRecipePanel(root) {
+ root.innerHTML = '<div class="lx-card"><p class="lx-card-note">Loading the recipe launcher…</p></div>';
+ const spec = '/launch/launch.js';
+ try {
+ const { mountLaunchCoin } = await import(/* @vite-ignore */ spec);
+ root.innerHTML = '';
+ mountLaunchCoin(root);
+ } catch (err) {
+ root.innerHTML = `<div class="lx-empty is-error"><strong>The recipe launcher did not load.</strong>${esc(err.message)}<a class="lx-btn" href="/launch">Open the standard launcher</a></div>`;
+ }
+}
+
+// ── Shell ──────────────────────────────────────────────────────────────────
+
+function renderShell(root) {
+ const f = state.form;
+ root.innerHTML = `
+ <div class="lx-grid" id="panel-create" role="tabpanel" aria-labelledby="tab-create">
+ <form class="lx-form" id="lx-form" novalidate>
+ <section class="lx-card" aria-labelledby="h-agent">
+ <div class="lx-card-h"><h2 id="h-agent"><span class="lx-step" data-step="agent">1</span>Link a 3D agent</h2><a class="lx-link" href="/create-agent">New agent</a></div>
+ <p class="lx-card-note">The coin launches for this agent. Its page becomes the coin's website and its 3D body rides in the token metadata.</p>
+ <div id="lx-agents"></div>
+ </section>
+
+ <section class="lx-card" aria-labelledby="h-details">
+ <div class="lx-card-h"><h2 id="h-details"><span class="lx-step" data-step="details">2</span>Coin details</h2></div>
+ <p class="lx-card-note">Choose carefully: the name, ticker and image are permanent once the coin is created.</p>
+ <div class="lx-row">
+ <label class="lx-field" style="margin-top:0">
+ <span class="lx-label">Coin name <span class="lx-count" id="c-name">0/${NAME_MAX}</span></span>
+ <input class="lx-input" id="f-name" name="name" maxlength="${NAME_MAX}" autocomplete="off" placeholder="Name your coin" value="${esc(f.name)}" />
+ </label>
+ <label class="lx-field" style="margin-top:0">
+ <span class="lx-label">Ticker <span class="lx-count" id="c-symbol">0/${SYMBOL_MAX}</span></span>
+ <input class="lx-input is-mono" id="f-symbol" name="symbol" maxlength="${SYMBOL_MAX}" autocomplete="off" placeholder="e.g. AGENT" value="${esc(f.symbol)}" />
+ </label>
+ </div>
+ <label class="lx-field">
+ <span class="lx-label">Description <span class="lx-opt">optional · <span id="c-desc">0/${DESCRIPTION_MAX}</span></span></span>
+ <textarea class="lx-textarea" id="f-description" name="description" maxlength="${DESCRIPTION_MAX}" placeholder="What is this agent and why does it have a coin?">${esc(f.description)}</textarea>
+ </label>
+ <details class="lx-disclosure">
+ <summary>Social links <span class="lx-opt">optional</span></summary>
+ <label class="lx-field"><span class="lx-label">Website <span class="lx-opt">defaults to the agent page</span></span>
+ <input class="lx-input" id="f-website" name="website" type="url" inputmode="url" placeholder="https://" value="${esc(f.website)}" /></label>
+ <div class="lx-row">
+ <label class="lx-field"><span class="lx-label">X</span><input class="lx-input" id="f-twitter" name="twitter" placeholder="https://x.com/…" value="${esc(f.twitter)}" /></label>
+ <label class="lx-field"><span class="lx-label">Telegram</span><input class="lx-input" id="f-telegram" name="telegram" placeholder="https://t.me/…" value="${esc(f.telegram)}" /></label>
+ </div>
+ </details>
+ </section>
+
+ <section class="lx-card" aria-labelledby="h-image">
+ <div class="lx-card-h"><h2 id="h-image"><span class="lx-step done">3</span>Image</h2></div>
+ <p class="lx-card-note">Defaults to your agent's portrait. Upload a square image to use something else.</p>
+ <div class="lx-image">
+ <div class="lx-image-thumb" id="img-thumb"></div>
+ <div class="lx-drop" id="img-drop">
+ <p class="lx-hint" id="img-status">PNG, JPG, GIF or WebP. Square, up to 4 MB. Drop it here.</p>
+ <div class="lx-drop-actions">
+ <label class="lx-btn is-small" for="f-image">Upload image</label>
+ <input id="f-image" type="file" accept="image/png,image/jpeg,image/gif,image/webp" hidden />
+ <button type="button" class="lx-btn is-small" id="img-reset">Use agent portrait</button>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <section class="lx-card" aria-labelledby="h-launch">
+ <div class="lx-card-h"><h2 id="h-launch"><span class="lx-step done">4</span>Launch settings</h2></div>
+ <div id="lx-options"></div>
+ </section>
+ </form>
+
+ <aside class="lx-side" aria-label="Launch preview">
+ <div class="lx-card lx-preview">
+ <div class="lx-stage" id="lx-stage"></div>
+ <div class="lx-coin" id="lx-coin"></div>
+ </div>
+ <div class="lx-card" style="padding:0">
+ <dl class="lx-rows" id="lx-costs"></dl>
+ <ul class="lx-checklist" id="lx-checklist" aria-live="polite"></ul>
+ </div>
+ <div class="lx-card" style="padding:0" id="lx-wallet"></div>
+ <button type="button" class="lx-btn is-primary" id="lx-launch">Launch coin</button>
+ <p class="lx-fine">Coins launch on pump.fun mainnet. Launching spends real funds and cannot be undone. <a href="/legal/risk">Risks</a></p>
+ </aside>
+ </div>
+
+ <section class="lx-coins" id="panel-coins" role="tabpanel" aria-labelledby="tab-coins" hidden>
+ <div id="claim-status" aria-live="polite"></div>
+ <div id="lx-coins-body"></div>
+ </section>
+
+ <dialog class="lx-dialog" id="lx-dialog" aria-labelledby="lx-dialog-title"><div class="lx-dialog-body" id="lx-dialog-body"></div></dialog>`;
+
+ renderAgents();
+ renderLaunchOptions();
+ renderImageThumb();
+ renderPreviewStage();
+ renderWallet();
+}
+
+// ── Tabs ───────────────────────────────────────────────────────────────────
+
+function wireTabs(initial) {
+ const tabs = [$('#tab-create'), $('#tab-coins')];
+ const select = (name, focus = false) => {
+ for (const t of tabs) {
+ const on = t.dataset.tab === name;
+ t.setAttribute('aria-selected', String(on));
+ t.tabIndex = on ? 0 : -1;
+ if (on && focus) t.focus();
+ }
+ $('#panel-create').hidden = name !== 'create';
+ $('#panel-coins').hidden = name !== 'coins';
+ const url = new URL(location.href);
+ if (name === 'coins') url.searchParams.set('tab', 'coins');
+ else url.searchParams.delete('tab');
+ history.replaceState(null, '', url);
+ if (name === 'coins' && state.user !== undefined) loadCoins();
+ };
+ for (const t of tabs) {
+ t.addEventListener('click', () => select(t.dataset.tab));
+ t.addEventListener('keydown', (e) => {
+ if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
+ e.preventDefault();
+ select(t.dataset.tab === 'create' ? 'coins' : 'create', true);
+ });
+ }
+ select(initial);
+}
+
+// ── Agents ─────────────────────────────────────────────────────────────────
+
+function agentThumb(a, cls = 'lx-agent-img') {
+ return a.thumbnail_url
+ ? `<img class="${cls}" src="${esc(a.thumbnail_url)}" alt="" loading="lazy" data-fallback="${esc((a.name || 'A').charAt(0).toUpperCase())}" />`
+ : `<span class="lx-agent-ph" aria-hidden="true">${esc((a.name || 'A').trim().charAt(0).toUpperCase())}</span>`;
+}
+
+function swapBrokenImages(root) {
+ for (const img of root.querySelectorAll('img[data-fallback]')) {
+ img.addEventListener(
+ 'error',
+ () => {
+ const ph = document.createElement('span');
+ ph.className = img.classList.contains('lx-agent-img') ? 'lx-agent-ph' : 'lx-coin-ph';
+ ph.setAttribute('aria-hidden', 'true');
+ ph.textContent = img.dataset.fallback;
+ img.replaceWith(ph);
+ },
+ { once: true },
+ );
+ }
+}
+
+function renderAgents() {
+ const box = $('#lx-agents');
+ if (!box) return;
+ if (state.agents === null || state.user === undefined) {
+ box.innerHTML = `<div class="lx-agents" aria-busy="true">${'<div class="lx-skel"></div>'.repeat(4)}</div>`;
+ return;
+ }
+ if (state.agentsError) {
+ box.innerHTML = `<div class="lx-empty is-error" role="alert"><strong>Could not load your agents.</strong><span>${esc(state.agentsError)}. Nothing was launched.</span><button type="button" class="lx-btn" id="agents-retry">Try again</button></div>`;
+ $('#agents-retry').addEventListener('click', () => loadIdentity(state.form.agentId));
+ return;
+ }
+ if (!state.user) {
+ box.innerHTML = `<div class="lx-empty"><strong>Sign in to pick an agent.</strong><span>Every coin on three.ws belongs to a 3D agent. Sign in to use one of yours, or create one in about a minute.</span><div class="lx-drop-actions"><a class="lx-btn" href="/login?next=${encodeURIComponent(location.pathname + location.search)}">Sign in</a><a class="lx-btn" href="/create-agent">Create an agent</a></div></div>`;
+ return;
+ }
+ if (!state.agents.length) {
+ box.innerHTML = `<div class="lx-empty"><strong>You don't have an agent yet.</strong><span>Create a 3D agent first. It takes about a minute, then come back here to launch its coin.</span><a class="lx-btn" href="/create-agent?next=/launch">Create your first agent</a></div>`;
+ return;
+ }
+ const q = state.agentQuery.trim().toLowerCase();
+ const list = q ? state.agents.filter((a) => `${a.name} ${a.slug || ''}`.toLowerCase().includes(q)) : state.agents;
+ const search =
+ state.agents.length > 8
+ ? `<input class="lx-input lx-agent-search" id="agent-q" type="search" placeholder="Search your ${state.agents.length} agents" value="${esc(state.agentQuery)}" aria-label="Search your agents" />`
+ : '';
+ const cards = list
+ .map((a) => {
+ const on = a.id === state.form.agentId;
+ return `<button type="button" role="radio" class="lx-agent" aria-checked="${on}" tabindex="${on ? 0 : -1}" data-id="${esc(a.id)}">${agentThumb(a)}<span><span class="lx-agent-name">${esc(a.name || 'Untitled agent')}</span><span class="lx-agent-sub">${a.slug ? `@${esc(a.slug)}` : esc(a.visibility || '')}</span></span></button>`;
+ })
+ .join('');
+ const hadFocus = box.contains(document.activeElement) && document.activeElement.id !== 'agent-q';
+ box.innerHTML = `${search}<div class="lx-agents" role="radiogroup" aria-label="Your agents">${cards || '<p class="lx-hint">No agent matches that search.</p>'}<a class="lx-agent-new" href="/create-agent?next=/launch"><span aria-hidden="true">+</span>New agent</a></div>`;
+ swapBrokenImages(box);
+
+ const radios = [...box.querySelectorAll('.lx-agent')];
+ if (radios.length && !radios.some((r) => r.tabIndex === 0)) radios[0].tabIndex = 0;
+ radios.forEach((btn, i) => {
+ btn.addEventListener('click', () => selectAgent(btn.dataset.id));
+ btn.addEventListener('keydown', (e) => {
+ const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[e.key];
+ if (!step) return;
+ e.preventDefault();
+ const next = radios[(i + step + radios.length) % radios.length];
+ selectAgent(next.dataset.id, true);
+ });
+ });
+ if (hadFocus) box.querySelector('.lx-agent[aria-checked="true"]')?.focus();
+ $('#agent-q')?.addEventListener('input', (e) => {
+ state.agentQuery = e.target.value;
+ renderAgents();
+ $('#agent-q')?.focus();
+ const el = $('#agent-q');
+ el?.setSelectionRange(el.value.length, el.value.length);
+ });
+}
+
+function selectAgent(id, focus = false) {
+ if (state.form.agentId !== id) {
+ state.form.agentId = id;
+ state.agentWallet = null;
+ state.agentWalletError = '';
+ const a = selectedAgent();
+ if (a && !state.form.name) {
+ state.form.name = (a.name || '').slice(0, NAME_MAX);
+ $('#f-name').value = state.form.name;
+ if (!state.form.symbolTouched) {
+ state.form.symbol = suggestSymbol(state.form.name);
+ $('#f-symbol').value = state.form.symbol;
+ }
+ }
+ renderAgents();
+ renderImageThumb();
+ renderPreviewStage();
+ if (state.form.launcher === 'agent') loadAgentWallet();
+ renderWallet();
+ updateDerived();
+ }
+ if (focus) $(`.lx-agent[data-id="${CSS.escape(id)}"]`)?.focus();
+}
+
+// ── Form ───────────────────────────────────────────────────────────────────
+
+function wireForm() {
+ const f = state.form;
+ const on = (id, fn) => $(id).addEventListener('input', fn);
+ on('#f-name', (e) => {
+ f.name = e.target.value;
+ if (!f.symbolTouched) {
+ f.symbol = suggestSymbol(f.name);
+ $('#f-symbol').value = f.symbol;
+ }
+ updateDerived();
+ });
+ on('#f-symbol', (e) => {
+ const normalized = normalizeSymbol(e.target.value);
+ if (normalized !== e.target.value) e.target.value = normalized;
+ f.symbol = normalized;
+ f.symbolTouched = normalized.length > 0;
+ updateDerived();
+ });
+ on('#f-description', (e) => {
+ f.description = e.target.value;
+ updateDerived();
+ });
+ for (const key of ['website', 'twitter', 'telegram']) {
+ on(`#f-${key}`, (e) => {
+ f[key] = e.target.value;
+ updateDerived();
+ });
+ }
+ $('#lx-form').addEventListener('submit', (e) => e.preventDefault());
+
+ const drop = $('#img-drop');
+ $('#f-image').addEventListener('change', (e) => {
+ const file = e.target.files?.[0];
+ e.target.value = '';
+ if (file) takeImageFile(file);
+ });
+ drop.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ drop.classList.add('is-over');
+ });
+ drop.addEventListener('dragleave', () => drop.classList.remove('is-over'));
+ drop.addEventListener('drop', (e) => {
+ e.preventDefault();
+ drop.classList.remove('is-over');
+ const file = e.dataTransfer?.files?.[0];
+ if (file) takeImageFile(file);
+ });
+ $('#img-reset').addEventListener('click', () => {
+ f.imageDataUrl = '';
+ f.imageName = '';
+ setImageStatus('Using your agent portrait.');
+ renderImageThumb();
+ updateDerived();
+ });
+ $('#lx-launch').addEventListener('click', onLaunchClick);
+}
+
+function setImageStatus(text, isError = false) {
+ const el = $('#img-status');
+ el.textContent = text;
+ el.style.color = isError ? 'var(--danger)' : '';
+}
+
+async function takeImageFile(file) {
+ if (!/^image\/(png|jpeg|gif|webp)$/.test(file.type)) {
+ setImageStatus('That file is not a PNG, JPG, GIF or WebP image.', true);
+ return;
+ }
+ try {
+ const dataUrl = file.size > IMAGE_MAX_BYTES || file.type !== 'image/gif' ? await downscale(file) : await readAsDataUrl(file);
+ if (dataUrl.length * 0.75 > IMAGE_MAX_BYTES) {
+ setImageStatus('That image is still over 4 MB after resizing. Use a smaller one.', true);
+ return;
+ }
+ state.form.imageDataUrl = dataUrl;
+ state.form.imageName = file.name;
+ setImageStatus(`Using ${file.name}.`);
+ renderImageThumb();
+ updateDerived();
+ } catch {
+ setImageStatus('Could not read that image. Try another file.', true);
+ }
+}
+
+function readAsDataUrl(file) {
+ return new Promise((resolve, reject) => {
+ const r = new FileReader();
+ r.onload = () => resolve(String(r.result));
+ r.onerror = () => reject(r.error);
+ r.readAsDataURL(file);
+ });
+}
+
+// Square-crop and cap at 1024px so every coin image is balanced and small.
+async function downscale(file) {
+ const bitmap = await createImageBitmap(file);
+ const side = Math.min(bitmap.width, bitmap.height);
+ const out = Math.min(IMAGE_MAX_DIM, side);
+ const canvas = document.createElement('canvas');
+ canvas.width = canvas.height = out;
+ canvas.getContext('2d').drawImage(bitmap, (bitmap.width - side) / 2, (bitmap.height - side) / 2, side, side, 0, 0, out, out);
+ bitmap.close?.();
+ return canvas.toDataURL(file.type === 'image/jpeg' ? 'image/jpeg' : 'image/png', 0.92);
+}
+
+async function importImageUrl(url) {
+ try {
+ const res = await fetch(url, { mode: 'cors' });
+ if (!res.ok) return;
+ const blob = await res.blob();
+ await takeImageFile(new File([blob], 'prefill', { type: blob.type }));
+ } catch {
+ setImageStatus('The linked image could not be loaded, so your agent portrait will be used.');
+ }
+}
+
+function currentImage() {
+ return state.form.imageDataUrl || selectedAgent()?.thumbnail_url || '';
+}
+
+function renderImageThumb() {
+ const box = $('#img-thumb');
+ if (!box) return;
+ const src = currentImage();
+ box.innerHTML = src ? `<img src="${esc(src)}" alt="Coin image" />` : '<span class="lx-stage-empty">No image yet</span>';
+ $('#img-reset').hidden = !state.form.imageDataUrl;
+}
+
+function renderLaunchOptions() {
+ const box = $('#lx-options');
+ if (!box) return;
+ const f = state.form;
+ const presets = DEV_BUY_PRESETS[f.quote];
+ const v1Active = !!state.config?.tx_v1?.active;
+ const seg = (name, value, label, sub, disabled = false) =>
+ `<button type="button" role="radio" data-seg="${name}" data-value="${value}" aria-checked="${String(f[name]) === String(value)}" ${disabled ? 'disabled' : ''}>${label}${sub ? `<small>${sub}</small>` : ''}</button>`;
+
+ box.innerHTML = `
+ <div class="lx-field" style="margin-top:4px">
+ <span class="lx-label" id="l-launcher">Launch from</span>
+ <div class="lx-seg" role="radiogroup" aria-labelledby="l-launcher">
+ ${seg('launcher', 'wallet', 'Your wallet', 'You sign, you earn rewards')}
+ ${seg('launcher', 'agent', "Agent's wallet", 'The agent signs and earns')}
+ </div>
+ </div>
+ <div class="lx-field">
+ <span class="lx-label" id="l-quote">Pair with</span>
+ <div class="lx-seg" role="radiogroup" aria-labelledby="l-quote">
+ ${seg('quote', 'sol', 'SOL', 'Classic pump.fun curve')}
+ ${seg('quote', 'usdc', 'USDC', 'Stable-priced curve')}
+ </div>
+ </div>
+ <div class="lx-field">
+ <span class="lx-label" id="l-rewards">Creator rewards go to</span>
+ <div class="lx-seg" role="radiogroup" aria-labelledby="l-rewards">
+ ${seg('rewards', 'creator', 'Creator', 'Claim them on this page')}
+ ${seg('rewards', 'holders', 'Holders', 'Paid out to holders', f.mayhem)}
+ </div>
+ </div>
+ <label class="lx-field" for="f-buy">
+ <span class="lx-label">Dev buy <span class="lx-opt">optional</span></span>
+ <div class="lx-buy"><input class="lx-input is-mono" id="f-buy" inputmode="decimal" autocomplete="off" placeholder="0.0" value="${esc(f.buyIn)}" aria-describedby="buy-hint" /><span class="lx-buy-unit">${f.quote.toUpperCase()}</span></div>
+ </label>
+ <div class="lx-chips" role="group" aria-label="Dev buy presets">
+ ${['0', ...presets].map((p) => `<button type="button" class="lx-chip" data-buy="${p}" aria-pressed="${String(parseBuyIn(f.buyIn)) === String(Number(p))}">${p === '0' ? 'None' : `${p} ${f.quote.toUpperCase()}`}</button>`).join('')}
+ </div>
+ <p class="lx-hint" id="buy-hint" style="margin-top:8px">Buy your own coin in the same transaction, before anyone else can.${feeBps() > 0 ? ` three.ws adds a ${feeBps() / 100}% fee on the dev buy.` : ''}</p>
+ <div class="lx-toggle-row">
+ <div><strong>Mayhem mode</strong><span>Higher-volatility curve for 24 hours. Set at creation only.</span></div>
+ <button type="button" class="lx-switch" role="switch" id="f-mayhem" aria-checked="${f.mayhem}" aria-label="Mayhem mode" ${f.rewards === 'holders' ? 'disabled' : ''}></button>
+ </div>
+ <details class="lx-disclosure" ${f.txFormat !== 'auto' ? 'open' : ''}>
+ <summary>Transaction format <span class="lx-badge ${v1Active ? 'is-good' : ''}" style="margin-left:6px">${v1Active ? 'v1 live' : 'v0'}</span></summary>
+ <div class="lx-field">
+ <div class="lx-seg" role="radiogroup" aria-label="Transaction format">
+ ${seg('txFormat', 'auto', 'Auto', 'Smallest that fits')}
+ ${seg('txFormat', '0', 'v0', 'Every wallet')}
+ ${seg('txFormat', '1', 'v1', '4,096-byte envelope', !v1Active)}
+ </div>
+ <p class="lx-hint" style="margin-top:8px">Solana transaction v1 fits launches that overflow the classic 1,232-byte limit, such as USDC coins with a dev buy. Auto uses v1 only when it is needed and your wallet supports it.</p>
+ </div>
+ </details>`;
+
+ for (const b of box.querySelectorAll('[data-seg]')) {
+ b.addEventListener('click', () => setOption(b.dataset.seg, b.dataset.value));
+ b.addEventListener('keydown', (e) => {
+ const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[e.key];
+ if (!step) return;
+ e.preventDefault();
+ const group = [...b.parentElement.querySelectorAll('[data-seg]:not(:disabled)')];
+ const next = group[(group.indexOf(b) + step + group.length) % group.length];
+ setOption(next.dataset.seg, next.dataset.value);
+ $(`[data-seg="${next.dataset.seg}"][data-value="${next.dataset.value}"]`)?.focus();
+ });
+ }
+ for (const c of box.querySelectorAll('[data-buy]')) {
+ c.addEventListener('click', () => {
+ f.buyIn = c.dataset.buy === '0' ? '' : c.dataset.buy;
+ $('#f-buy').value = f.buyIn;
+ syncBuyChips();
+ updateDerived();
+ });
+ }
+ $('#f-buy').addEventListener('input', (e) => {
+ f.buyIn = e.target.value.replace(/[^\d.]/g, '');
+ if (f.buyIn !== e.target.value) e.target.value = f.buyIn;
+ syncBuyChips();
+ updateDerived();
+ });
+ $('#f-mayhem').addEventListener('click', () => {
+ f.mayhem = !f.mayhem;
+ renderLaunchOptions();
+ updateDerived();
+ });
+}
+
+function syncBuyChips() {
+ for (const c of document.querySelectorAll('[data-buy]')) {
+ c.setAttribute('aria-pressed', String(String(parseBuyIn(state.form.buyIn)) === String(Number(c.dataset.buy))));
+ }
+}
+
+function setOption(name, value) {
+ const f = state.form;
+ const next = name === 'txFormat' && value !== 'auto' ? Number(value) : value;
+ if (String(f[name]) === String(next)) return;
+ f[name] = next;
+ if (name === 'quote') f.buyIn = '';
+ if (name === 'rewards' && value === 'holders') f.mayhem = false;
+ if (name === 'launcher') {
+ if (value === 'agent') loadAgentWallet();
+ renderWallet();
+ }
+ renderLaunchOptions();
+ updateDerived();
+}
+
+// ── Preview + derived UI ───────────────────────────────────────────────────
+
+let stageAgentId = null;
+function renderPreviewStage() {
+ const stage = $('#lx-stage');
+ if (!stage) return;
+ const a = selectedAgent();
+ if (!a) {
+ stageAgentId = null;
+ stage.innerHTML = `<div class="lx-stage-empty">${state.agents === null ? 'Loading your agents…' : 'Pick an agent to see it here'}</div>`;
+ return;
+ }
+ if (stageAgentId === a.id) return;
+ stageAgentId = a.id;
+ const tag = `<span class="lx-stage-tag">3D agent · ${esc(a.name || 'Untitled')}</span>`;
+ if (a.model_url) {
+ stage.innerHTML = `<model-viewer src="${esc(a.model_url)}" ${a.thumbnail_url ? `poster="${esc(a.thumbnail_url)}"` : ''} alt="${esc(a.name || 'Agent')} in 3D" camera-controls auto-rotate rotation-per-second="18deg" interaction-prompt="none" shadow-intensity="0.8" exposure="1.05" environment-image="neutral"></model-viewer>${tag}`;
+ ensureModelViewer().catch(() => {
+ if (stageAgentId !== a.id) return;
+ stage.innerHTML = a.thumbnail_url ? `<img src="${esc(a.thumbnail_url)}" alt="${esc(a.name || 'Agent')}" />${tag}` : `<div class="lx-stage-empty">3D preview unavailable</div>${tag}`;
+ });
+ } else {
+ stage.innerHTML = a.thumbnail_url ? `<img src="${esc(a.thumbnail_url)}" alt="${esc(a.name || 'Agent')}" />${tag}` : `<div class="lx-stage-empty">This agent has no body yet</div>${tag}`;
+ }
+}
+
+function updateDerived() {
+ const f = state.form;
+ const a = selectedAgent();
+ const problems = launchProblems(f, { quote: f.quote });
+ const c = cost();
+
+ const count = (id, n, max) => {
+ const el = $(id);
+ if (el) el.textContent = `${n}/${max}`;
+ };
+ count('#c-name', [...f.name].length, NAME_MAX);
+ count('#c-symbol', f.symbol.length, SYMBOL_MAX);
+ count('#c-desc', f.description.length, DESCRIPTION_MAX);
+ document.querySelector('[data-step="agent"]')?.classList.toggle('done', !!a);
+ document.querySelector('[data-step="details"]')?.classList.toggle('done', !problems.some((p) => p.field === 'name' || p.field === 'symbol'));
+
+ const img = currentImage();
+ const coin = $('#lx-coin');
+ if (coin) {
+ coin.innerHTML = `${img ? `<img class="lx-coin-img" src="${esc(img)}" alt="" />` : `<span class="lx-coin-ph" aria-hidden="true">?</span>`}
+ <div style="min-width:0"><p class="lx-coin-name">${esc(f.name.trim() || 'Your coin name')}</p><p class="lx-coin-sym">$${esc(f.symbol || 'TICKER')}</p></div>
+ ${f.description.trim() ? `<p class="lx-coin-desc">${esc(f.description.trim())}</p>` : ''}
+ <span class="lx-coin-link">↗ ${a ? `three.ws/agents/${esc(a.agent_id || a.id).slice(0, 8)}…` : 'links to your agent'}</span>`;
+ }
+
+ const costs = $('#lx-costs');
+ if (costs) {
+ const q = c.quote;
+ const rows = [
+ ['pump.fun create + rent', `~${formatAmount(c.createSol, 4)} SOL`],
+ ['Dev buy', c.buyIn > 0 ? `${formatAmount(c.buyIn)} ${q}` : 'None'],
+ ];
+ const feeRow =
+ feeBps() > 0
+ ? `<div class="is-fee"><dt>three.ws fee · ${feeBps() / 100}%</dt><dd>${c.fee > 0 ? `${formatAmount(c.fee, q === 'USDC' ? 6 : 9)} ${q}` : '0'}</dd></div>`
+ : '';
+ const total = q === 'USDC' ? `${formatAmount(c.totalQuote, 6)} USDC + ~${formatAmount(c.totalSol, 4)} SOL` : `~${formatAmount(c.totalSol, 6)} SOL`;
+ costs.innerHTML = `${rows.map(([k, v]) => `<div><dt>${k}</dt><dd>${v}</dd></div>`).join('')}${feeRow}<div class="is-total"><dt>Total</dt><dd>${total}</dd></div>`;
+ }
+
+ const list = $('#lx-checklist');
+ const walletProblem = walletBlocker(c);
+ const all = walletProblem ? [...problems, walletProblem] : problems;
+ if (list) {
+ list.hidden = !all.length;
+ list.innerHTML = all
+ .map((p) => `<li>${p.field && p.field !== 'wallet' ? `<button type="button" data-focus="${p.field}">${esc(p.text)}</button>` : esc(p.text)}</li>`)
+ .join('');
+ for (const b of list.querySelectorAll('[data-focus]')) b.addEventListener('click', () => focusField(b.dataset.focus));
+ }
+
+ const btn = $('#lx-launch');
+ if (btn) {
+ // Signing in and connecting a wallet are always reachable from the button;
+ // only an actual launch waits for a complete form and a funded signer.
+ const gateStep = state.user === null || (state.form.launcher === 'wallet' && !state.wallet && state.user);
+ btn.disabled = state.running || state.user === undefined || (!gateStep && (problems.length > 0 || !!walletProblem?.blocking));
+ btn.textContent = state.running ? 'Launching…' : launchLabel(walletProblem);
+ }
+}
+
+function launchLabel(walletProblem) {
+ if (state.user === null) return 'Sign in to launch';
+ if (state.form.launcher === 'wallet' && !state.wallet) return walletInstalled() ? 'Connect wallet to launch' : 'Install a Solana wallet';
+ if (walletProblem?.blocking) return 'Launch coin';
+ return `Launch $${state.form.symbol || 'coin'}`;
+}
+
+// Wallet state that stops a launch. Non-blocking items only inform the button label.
+function walletBlocker(c) {
+ if (state.user === null) return { field: 'wallet', text: 'Sign in to launch', blocking: false };
+ if (state.form.launcher === 'agent') {
+ if (!state.agentWallet) return { field: 'wallet', text: state.agentWalletError || "Loading the agent's wallet", blocking: true };
+ if (c.quote === 'SOL' && state.agentWallet.sol != null && state.agentWallet.sol < c.totalSol) {
+ return { field: 'wallet', text: `The agent's wallet needs ~${formatAmount(c.totalSol - state.agentWallet.sol, 4)} more SOL`, blocking: true };
+ }
+ return null;
+ }
+ if (!state.wallet) return null;
+ if (c.quote === 'SOL' && state.balance != null && state.balance < c.totalSol) {
+ return { field: 'wallet', text: `Your wallet needs ~${formatAmount(c.totalSol - state.balance, 4)} more SOL`, blocking: true };
+ }
+ return null;
+}
+
+function focusField(field) {
+ const map = { agent: '.lx-agent[aria-checked="true"], .lx-agent, #lx-agents a', name: '#f-name', symbol: '#f-symbol', description: '#f-description', buyIn: '#f-buy', website: '#f-website', twitter: '#f-twitter', telegram: '#f-telegram' };
+ const el = $(map[field] || '#f-name');
+ if (!el) return;
+ el.closest('details')?.setAttribute('open', '');
+ el.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ el.focus({ preventScroll: true });
+}
+
+// ── Wallets ────────────────────────────────────────────────────────────────
+
+async function refreshBalance() {
+ if (!state.wallet) return;
+ try {
+ state.balance = await solBalance(state.wallet.address);
+ } catch {
+ state.balance = null;
+ }
+ renderWallet();
+ updateDerived();
+}
+
+async function loadAgentWallet() {
+ const a = selectedAgent();
+ if (!a || !state.user) return;
+ state.agentWallet = null;
+ state.agentWalletError = '';
+ renderWallet();
+ try {
+ const data = await api('/api/pump/agent-wallet', {
+ method: 'POST',
+ body: { ...(a.agent_id ? { agent_id: a.agent_id } : { avatar_id: a.id }), network: 'mainnet' },
+ });
+ if (selectedAgent()?.id !== a.id) return;
+ state.agentWallet = data;
+ } catch (err) {
+ state.agentWalletError = friendlyLaunchError(err);
+ }
+ renderWallet();
+ updateDerived();
+}
+
+function renderWallet() {
+ const box = $('#lx-wallet');
+ if (!box) return;
+ if (state.form.launcher === 'agent') {
+ const w = state.agentWallet;
+ box.innerHTML = w
+ ? `<div class="lx-wallet"><div style="min-width:0"><div class="lx-wallet-addr">${esc(shortAddress(w.address))}</div><p class="lx-hint">Agent wallet · ${w.sol == null ? 'balance unavailable' : `${formatAmount(w.sol, 4)} SOL`}</p></div><div class="lx-drop-actions"><button type="button" class="lx-btn is-small" id="aw-copy">Copy</button><button type="button" class="lx-btn is-small" id="aw-refresh" aria-label="Refresh balance">Refresh</button></div></div>`
+ : `<div class="lx-wallet"><span class="lx-hint">${esc(state.agentWalletError || "Loading the agent's wallet…")}</span>${state.agentWalletError ? '<button type="button" class="lx-btn is-small" id="aw-retry">Retry</button>' : ''}</div>`;
+ $('#aw-copy')?.addEventListener('click', (e) => copyText(w.address, e.currentTarget));
+ $('#aw-refresh')?.addEventListener('click', loadAgentWallet);
+ $('#aw-retry')?.addEventListener('click', loadAgentWallet);
+ return;
+ }
+ if (!state.wallet && state.walletConflict) {
+ box.innerHTML = `<div class="lx-wallet" style="flex-wrap:wrap"><span class="lx-hint">${esc(shortAddress(state.walletConflict))} is linked to another three.ws account. Move it to this account to launch with it.</span><button type="button" class="lx-btn is-small" id="w-takeover" ${state.walletBusy ? 'disabled' : ''}>${state.walletBusy ? 'Moving…' : 'Move wallet here'}</button></div>`;
+ $('#w-takeover').addEventListener('click', takeoverWallet);
+ return;
+ }
+ if (!state.wallet) {
+ box.innerHTML = `<div class="lx-wallet"><span class="lx-hint">${esc(state.walletError || (walletInstalled() ? 'Connect the wallet that will sign the launch.' : 'Install Phantom, Solflare or Backpack to launch from your wallet.'))}</span>${walletInstalled() ? `<button type="button" class="lx-btn is-small" id="w-connect" ${state.walletBusy ? 'disabled' : ''}>${state.walletBusy ? 'Connecting…' : 'Connect'}</button>` : '<a class="lx-btn is-small" href="https://phantom.app/" target="_blank" rel="noopener">Get Phantom</a>'}</div>`;
+ $('#w-connect')?.addEventListener('click', connectWallet);
+ return;
+ }
+ const w = state.wallet;
+ box.innerHTML = `<div class="lx-wallet"><div style="min-width:0"><div class="lx-wallet-addr">${esc(shortAddress(w.address))}</div><p class="lx-hint">${esc(w.name)} · ${state.balance == null ? 'checking balance' : `${formatAmount(state.balance, 4)} SOL`}</p></div><span class="lx-badge ${w.v1 ? 'is-good' : ''}" title="${w.v1 ? 'This wallet signs Solana transaction v1' : 'This wallet signs v0 transactions'}">${w.v1 ? 'v1 ready' : 'v0'}</span></div>`;
+}
+
+async function connectWallet() {
+ if (state.walletBusy) return null;
+ if (!state.user) {
+ location.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;
+ return null;
+ }
+ state.walletBusy = true;
+ state.walletError = '';
+ state.walletConflict = null;
+ renderWallet();
+ try {
+ state.wallet = await connectLaunchWallet();
+ refreshBalance();
+ } catch (err) {
+ if (err.code === 'address_in_use') {
+ state.walletConflict = injectedProvider()?.publicKey?.toString() || null;
+ } else {
+ state.walletError = err.code === 'USER_REJECTED' ? 'Connection cancelled.' : friendlyLaunchError(err);
+ }
+ } finally {
+ state.walletBusy = false;
+ renderWallet();
+ updateDerived();
+ }
+ return state.wallet;
+}
+
+async function takeoverWallet() {
+ const address = state.walletConflict;
+ if (!address || state.walletBusy) return;
+ state.walletBusy = true;
+ renderWallet();
+ try {
+ await linkWallet(address, { takeover: true });
+ state.walletConflict = null;
+ state.walletBusy = false;
+ await connectWallet();
+ return;
+ } catch (err) {
+ state.walletConflict = null;
+ state.walletError = friendlyLaunchError(err);
+ }
+ state.walletBusy = false;
+ renderWallet();
+ updateDerived();
+}
+
+async function copyText(text, btn) {
+ try {
+ await navigator.clipboard.writeText(text);
+ if (btn) {
+ const old = btn.textContent;
+ btn.textContent = 'Copied';
+ setTimeout(() => (btn.textContent = old), 1500);
+ }
+ } catch {
+ if (btn) btn.textContent = 'Copy failed';
+ }
+}
+
+// ── Launch ─────────────────────────────────────────────────────────────────
+
+const WALLET_STEPS = [
+ ['metadata', 'Upload image and metadata'],
+ ['prepare', 'Build the launch transaction'],
+ ['sign', 'Approve in your wallet'],
+ ['confirm', 'Confirm on Solana'],
+ ['record', 'List it on three.ws'],
+];
+const AGENT_STEPS = [
+ ['metadata', 'Upload image and metadata'],
+ ['launch', "Agent signs and sends the launch"],
+];
+
+async function onLaunchClick() {
+ if (state.user === null) {
+ location.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;
+ return;
+ }
+ if (state.form.launcher === 'wallet' && !state.wallet) {
+ if (!walletInstalled()) {
+ window.open('https://phantom.app/', '_blank', 'noopener');
+ return;
+ }
+ if (!(await connectWallet())) return;
+ return;
+ }
+ const problems = launchProblems(state.form, { quote: state.form.quote });
+ if (problems.length) {
+ focusField(problems[0].field);
+ return;
+ }
+ if (!(await ensureRiskAck({ context: 'launch' }))) return;
+ if (state.form.launcher === 'agent') await runAgentLaunch();
+ else await runWalletLaunch();
+}
+
+function openDialog(title, lead, steps) {
+ const dlg = $('#lx-dialog');
+ $('#lx-dialog-body').innerHTML = `<h2 id="lx-dialog-title">${esc(title)}</h2><p>${esc(lead)}</p><ol class="lx-steps">${steps.map(([k, label]) => `<li data-step="${k}" data-state="pending"><span class="ic" aria-hidden="true"></span><span>${esc(label)}<small></small></span></li>`).join('')}</ol><div id="lx-dialog-extra"></div>`;
+ dlg.oncancel = (e) => {
+ if (state.running) e.preventDefault();
+ };
+ if (!dlg.open) dlg.showModal();
+}
+
+function step(key, st, note = '') {
+ const li = $(`#lx-dialog-body [data-step="${key}"]`);
+ if (!li) return;
+ li.dataset.state = st;
+ li.querySelector('small').textContent = note;
+ if (st === 'active') li.setAttribute('aria-current', 'step');
+ else li.removeAttribute('aria-current');
+}
+
+function metadataBody() {
+ const f = state.form;
+ const a = selectedAgent();
+ return {
+ name: f.name.trim(),
+ symbol: normalizeSymbol(f.symbol),
+ description: f.description.trim(),
+ avatar_id: a.id,
+ ...(a.agent_id ? { agent_id: a.agent_id } : {}),
+ ...(f.website.trim() ? { website: f.website.trim() } : {}),
+ ...(f.twitter.trim() ? { twitter: f.twitter.trim() } : {}),
+ ...(f.telegram.trim() ? { telegram: f.telegram.trim() } : {}),
+ ...(f.imageDataUrl ? { image_data_url: f.imageDataUrl } : {}),
+ };
+}
+
+function coinOptions() {
+ const f = state.form;
+ const buy = parseBuyIn(f.buyIn) || 0;
+ return {
+ coin_type: f.mayhem ? 'mayhem' : 'regular',
+ holder_reward: f.rewards === 'holders',
+ network: 'mainnet',
+ ...(f.quote === 'usdc' ? { quote_currency: 'usdc', usdc_buy_in: buy } : { quote_currency: 'sol', sol_buy_in: buy }),
+ };
+}
+
+async function runWalletLaunch() {
+ state.running = true;
+ updateDerived();
+ const a = selectedAgent();
+ openDialog(`Launching $${normalizeSymbol(state.form.symbol)}`, 'Keep this window open. Your wallet will ask you to approve one transaction.', WALLET_STEPS);
+ let current = 'metadata';
+ try {
+ step('metadata', 'active');
+ const meta = await api('/api/pump/build-metadata', { method: 'POST', body: metadataBody() });
+ step('metadata', 'done', meta.on_ipfs ? 'Pinned to IPFS' : 'Stored on three.ws');
+
+ current = 'prepare';
+ step('prepare', 'active', 'Stamping the 3ws mint mark');
+ const prep = await api('/api/pump/launch-prep', {
+ method: 'POST',
+ body: {
+ ...(a.agent_id ? { agent_id: a.agent_id } : { avatar_id: a.id }),
+ wallet_address: state.wallet.address,
+ name: state.form.name.trim(),
+ symbol: normalizeSymbol(state.form.symbol),
+ uri: meta.metadata_url,
+ ...coinOptions(),
+ transaction_version: state.form.txFormat,
+ v1_capable: !!state.wallet.v1,
+ },
+ });
+ step('prepare', 'done', `Transaction v${prep.transaction_version} · ${prep.tx_bytes.toLocaleString()} of ${prep.tx_limit_bytes.toLocaleString()} bytes`);
+
+ current = 'sign';
+ step('sign', 'active', 'Check your wallet');
+ const signature = await signAndBroadcast({ txBase64: prep.tx_base64, version: prep.transaction_version, address: state.wallet.address });
+ step('sign', 'done', 'Sent to Solana');
+
+ await finishConfirm({ prep, signature, agent: a });
+ } catch (err) {
+ step(current, 'error', friendlyLaunchError(err));
+ showDialogError(err);
+ } finally {
+ state.running = false;
+ updateDerived();
+ refreshBalance();
+ }
+}
+
+async function finishConfirm({ prep, signature, agent }) {
+ step('confirm', 'active', 'Usually a few seconds');
+ const confirmed = await waitForConfirmation(signature);
+ if (!confirmed) {
+ step('confirm', 'error', 'Still pending after 75 seconds');
+ $('#lx-dialog-extra').innerHTML = `<div class="lx-alert is-warn">Solana has not confirmed the launch yet. It may still land. <a class="lx-link" href="https://solscan.io/tx/${esc(signature)}" target="_blank" rel="noopener">View on Solscan</a></div><div class="lx-actions"><button type="button" class="lx-btn is-wide" id="lx-recheck">Check again</button></div>`;
+ $('#lx-recheck').addEventListener('click', async () => {
+ state.running = true;
+ $('#lx-dialog-extra').innerHTML = '';
+ try {
+ await finishConfirm({ prep, signature, agent });
+ } catch (err) {
+ showDialogError(err);
+ } finally {
+ state.running = false;
+ }
+ });
+ return;
+ }
+ step('confirm', 'done', 'Confirmed');
+ step('record', 'active');
+ const recorded = await recordLaunch(prep.prep_id, signature);
+ step('record', 'done');
+ showSuccess({ mint: recorded?.pump_agent_mint?.mint || prep.mint, signature, agent, fee: prep.platform_fee });
+}
+
+// The RPC that served confirmation can be a slot ahead of the one the server
+// reads, so a just-confirmed signature may briefly read as missing.
+async function recordLaunch(prepId, signature) {
+ for (let attempt = 0; attempt < 5; attempt++) {
+ try {
+ return await api('/api/pump/launch-confirm', { method: 'POST', body: { prep_id: prepId, tx_signature: signature } });
+ } catch (err) {
+ if (err.code === 'conflict') return null;
+ if (err.code !== 'tx_not_found' || attempt === 4) throw err;
+ await new Promise((r) => setTimeout(r, 2_000 * (attempt + 1)));
+ }
+ }
+ return null;
+}
+
+async function runAgentLaunch() {
+ state.running = true;
+ updateDerived();
+ const a = selectedAgent();
+ openDialog(`Launching $${normalizeSymbol(state.form.symbol)}`, `${a.name || 'Your agent'} signs this launch with its own wallet. No wallet prompt needed.`, AGENT_STEPS);
+ let current = 'metadata';
+ try {
+ step('metadata', 'active');
+ const meta = await api('/api/pump/build-metadata', { method: 'POST', body: metadataBody() });
+ step('metadata', 'done', meta.on_ipfs ? 'Pinned to IPFS' : 'Stored on three.ws');
+ current = 'launch';
+ step('launch', 'active', 'Signing, sending and confirming');
+ const out = await api('/api/pump/launch-agent', {
+ method: 'POST',
+ body: {
+ ...(a.agent_id ? { agent_id: a.agent_id } : { avatar_id: a.id }),
+ name: state.form.name.trim(),
+ symbol: normalizeSymbol(state.form.symbol),
+ uri: meta.metadata_url,
+ ...coinOptions(),
+ },
+ });
+ step('launch', 'done', 'Confirmed');
+ showSuccess({ mint: out.mint, signature: out.signature, agent: a, fee: out.platform_fee });
+ } catch (err) {
+ step(current, 'error', friendlyLaunchError(err));
+ showDialogError(err);
+ } finally {
+ state.running = false;
+ loadAgentWallet();
+ updateDerived();
+ }
+}
+
+function showDialogError(err) {
+ $('#lx-dialog-extra').innerHTML = `<div class="lx-alert" role="alert">${esc(friendlyLaunchError(err))}</div><div class="lx-actions"><button type="button" class="lx-btn" id="lx-close">Close</button><button type="button" class="lx-btn" id="lx-retry">Try again</button></div>`;
+ $('#lx-close').addEventListener('click', () => $('#lx-dialog').close());
+ $('#lx-retry').addEventListener('click', () => {
+ $('#lx-dialog').close();
+ onLaunchClick();
+ });
+ $('#lx-close').focus();
+}
+
+function showSuccess({ mint, signature, agent, fee }) {
+ const f = state.form;
+ const symbol = normalizeSymbol(f.symbol);
+ const img = currentImage();
+ const post = shareText({ name: f.name.trim(), symbol, mint, agentName: agent?.name });
+ const feeNote = fee?.settlement === 'failed' ? '<div class="lx-alert is-warn">The coin is live. The three.ws fee transfer did not go through, so you were not charged it.</div>' : '';
+ $('#lx-dialog-body').innerHTML = `
+ <h2 id="lx-dialog-title">$${esc(symbol)} is live</h2>
+ <p>Your coin is trading on pump.fun and listed on three.ws, linked to ${esc(agent?.name || 'your agent')}.</p>
+ <div class="lx-result-coin">
+ ${img ? `<img class="lx-coin-img" src="${esc(img)}" alt="" />` : '<span class="lx-coin-ph">?</span>'}
+ <div style="min-width:0"><p class="lx-coin-name">${esc(f.name.trim())}</p><div class="lx-ca"><span>${esc(shortAddress(mint, 6, 6))}</span><button type="button" class="lx-btn is-small" id="ok-copy">Copy CA</button></div></div>
+ </div>
+ ${feeNote}
+ <div class="lx-actions">
+ <a class="lx-btn" href="/launches/${esc(mint)}">Coin page</a>
+ <a class="lx-btn" href="https://pump.fun/coin/${esc(mint)}" target="_blank" rel="noopener">pump.fun</a>
+ <a class="lx-btn" href="/agents/${esc(agent?.agent_id || agent?.id || '')}">Agent page</a>
+ <a class="lx-btn" href="https://solscan.io/tx/${esc(signature || '')}" target="_blank" rel="noopener">Transaction</a>
+ <a class="lx-btn is-primary is-wide" href="https://x.com/intent/post?text=${encodeURIComponent(post)}" target="_blank" rel="noopener">Share on X</a>
+ <button type="button" class="lx-btn is-wide" id="ok-another">Launch another</button>
+ </div>
+ <p class="lx-hint" style="margin-top:14px;text-align:center">Creator rewards build up as people trade. Claim them any time under My coins.</p>`;
+ $('#ok-copy').addEventListener('click', (e) => copyText(mint, e.currentTarget));
+ $('#ok-another').addEventListener('click', () => {
+ $('#lx-dialog').close();
+ resetForm();
+ });
+ state.coins = null;
+ $('#ok-copy').focus();
+}
+
+function resetForm() {
+ Object.assign(state.form, { name: '', symbol: '', symbolTouched: false, description: '', website: '', twitter: '', telegram: '', buyIn: '', imageDataUrl: '', imageName: '', mayhem: false });
+ for (const id of ['#f-name', '#f-symbol', '#f-description', '#f-website', '#f-twitter', '#f-telegram']) $(id).value = '';
+ renderLaunchOptions();
+ renderImageThumb();
+ updateDerived();
+ $('#f-name').focus();
+}
+
+// ── My coins + claims ──────────────────────────────────────────────────────
+
+async function loadCoins() {
+ const box = $('#lx-coins-body');
+ if (!box) return;
+ if (state.user === null) {
+ box.innerHTML = `<div class="lx-card lx-empty"><strong>Sign in to see your coins.</strong><span>Coins you launch on three.ws show up here with their unclaimed creator rewards.</span><a class="lx-btn" href="/login?next=${encodeURIComponent('/launch?tab=coins')}">Sign in</a></div>`;
+ return;
+ }
+ if (!state.coins) box.innerHTML = `<div class="lx-card"><div class="lx-skel" style="min-height:120px"></div></div><div class="lx-card"><div class="lx-skel" style="min-height:120px"></div></div>`;
+ try {
+ const { data } = await api('/api/pump/my-coins');
+ state.coins = data;
+ state.coinsError = '';
+ } catch (err) {
+ state.coinsError = friendlyLaunchError(err);
+ }
+ renderCoins();
+}
+
+function rewardSummary(wallet) {
+ if (wallet.balance_error) return { text: 'Unavailable', claimable: false };
+ const parts = wallet.rewards.filter((r) => r.amount_ui != null && r.amount_ui > 0);
+ if (!parts.length) return { text: '0 <small>SOL</small>', claimable: false };
+ return { text: parts.map((r) => `${formatAmount(r.amount_ui, r.symbol === 'SOL' ? 6 : 2)} <small>${esc(r.symbol)}</small>`).join(' + '), claimable: true };
+}
+
+function coinRow(c) {
+ const thumb = c.agent?.thumbnail_url
+ ? `<img src="${esc(c.agent.thumbnail_url)}" alt="" loading="lazy" data-fallback="${esc(c.symbol.charAt(0))}" />`
+ : `<span class="lx-coin-ph" aria-hidden="true">${esc(c.symbol.charAt(0))}</span>`;
+ const route = { holders: 'Rewards go to holders', shared: 'Rewards split by a fee-sharing config', external: 'Created by a wallet not linked to this account', unknown: 'Creator unknown' }[c.reward_route];
+ return `<div class="lx-coin-row">${thumb}<div style="min-width:0"><a href="/launches/${esc(c.mint)}">${esc(c.name)} <span class="lx-coin-sym" style="display:inline">$${esc(c.symbol)}</span></a><p>${c.agent ? `${esc(c.agent.name)} · ` : ''}${new Date(c.created_at).toLocaleDateString()}${route ? ` · ${route}` : ''}</p></div><div class="lx-coin-row-links"><a class="lx-btn is-small" href="https://pump.fun/coin/${esc(c.mint)}" target="_blank" rel="noopener">pump.fun</a></div></div>`;
+}
+
+function renderCoins() {
+ const box = $('#lx-coins-body');
+ if (!box) return;
+ if (state.coinsError) {
+ box.innerHTML = `<div class="lx-card lx-empty is-error" role="alert"><strong>Could not load your coins.</strong><span>${esc(state.coinsError)}</span><button type="button" class="lx-btn" id="coins-retry">Try again</button></div>`;
+ $('#coins-retry').addEventListener('click', loadCoins);
+ return;
+ }
+ const data = state.coins;
+ const badge = $('#coins-badge');
+ if (!data?.coins?.length) {
+ if (badge) badge.hidden = true;
+ box.innerHTML = `<div class="lx-card lx-empty"><strong>No coins yet.</strong><span>Launch a coin for one of your agents and its creator rewards will show up here, ready to claim.</span><button type="button" class="lx-btn" id="coins-create">Launch your first coin</button></div>`;
+ $('#coins-create').addEventListener('click', () => $('#tab-create').click());
+ return;
+ }
+ const claimable = data.wallets.filter((w) => rewardSummary(w).claimable).length;
+ if (badge) {
+ badge.hidden = !claimable;
+ badge.textContent = String(claimable);
+ }
+ const byMint = new Map(data.coins.map((c) => [c.mint, c]));
+ const walletCards = data.wallets
+ .map((w) => {
+ const sum = rewardSummary(w);
+ const busy = state.claiming.has(w.address);
+ const who = w.kind === 'agent' ? `${esc(w.agent?.name || 'Agent')}'s wallet` : 'Your wallet';
+ return `<article class="lx-card">
+ <div class="lx-reward">
+ <div><p class="lx-reward-kicker">${who} · ${esc(shortAddress(w.address))}</p><p class="lx-reward-amt">${sum.text}</p><p class="lx-reward-meta">Unclaimed creator rewards across ${w.coins.length} coin${w.coins.length === 1 ? '' : 's'}${w.balance_error ? '. The balance could not be read right now.' : ''}</p></div>
+ <button type="button" class="lx-btn ${sum.claimable ? 'is-primary' : ''}" style="${sum.claimable ? 'width:auto;min-height:44px;padding:0 22px' : ''}" data-claim="${esc(w.address)}" ${!sum.claimable || busy ? 'disabled' : ''}>${busy ? 'Claiming…' : sum.claimable ? 'Claim rewards' : 'Nothing to claim'}</button>
+ </div>
+ <div class="lx-coin-list">${w.coins.map((m) => coinRow(byMint.get(m))).join('')}</div>
+ </article>`;
+ })
+ .join('');
+ const grouped = new Set(data.wallets.flatMap((w) => w.coins));
+ const others = data.coins.filter((c) => !grouped.has(c.mint));
+ const otherCard = others.length
+ ? `<article class="lx-card"><p class="lx-reward-kicker">Other coins</p><div class="lx-coin-list" style="border-top:0">${others.map(coinRow).join('')}</div></article>`
+ : '';
+ box.innerHTML = `${walletCards}${otherCard}`;
+ swapBrokenImages(box);
+ for (const b of box.querySelectorAll('[data-claim]')) b.addEventListener('click', () => claim(b.dataset.claim));
+}
+
+async function claim(address) {
+ const w = state.coins?.wallets.find((x) => x.address === address);
+ if (!w || state.claiming.has(address)) return;
+ if (!(await ensureRiskAck({ context: 'claim' }))) return;
+ const status = (html) => {
+ // Replaced on the next claim; the coin list re-renders below it without touching it.
+ const el = $('#claim-status');
+ if (el) el.innerHTML = html;
+ };
+ state.claiming.add(address);
+ renderCoins();
+ try {
+ let signature;
+ if (w.kind === 'agent') {
+ const out = await api('/api/pump/collect-creator-fee-agent', {
+ method: 'POST',
+ body: { agent_id: w.agent.id, mint: w.claim_mint, network: 'mainnet', all_quotes: true },
+ });
+ signature = out.signature;
+ } else {
+ if (!state.wallet || state.wallet.address !== address) {
+ await connectWallet();
+ if (!state.wallet || state.wallet.address !== address) {
+ throw new Error(`Switch your wallet to ${shortAddress(address)} to claim these rewards.`);
+ }
+ }
+ const prep = await api('/api/pump/collect-creator-fee-prep', {
+ method: 'POST',
+ body: { creator_address: address, wallet_address: address, network: 'mainnet', all_quotes: true, v1_capable: !!state.wallet.v1 },
+ });
+ signature = await signAndBroadcast({ txBase64: prep.tx_base64, version: prep.transaction_version, address });
+ const confirmed = await waitForConfirmation(signature);
+ if (!confirmed) {
+ status(`<div class="lx-alert is-warn">The claim was sent but has not confirmed yet. <a class="lx-link" href="https://solscan.io/tx/${esc(signature)}" target="_blank" rel="noopener">View on Solscan</a></div>`);
+ return;
+ }
+ }
+ status(`<div class="lx-alert is-good">Rewards claimed. <a class="lx-link" href="https://solscan.io/tx/${esc(signature)}" target="_blank" rel="noopener">View transaction</a></div>`);
+ } catch (err) {
+ status(`<div class="lx-alert" role="alert">${esc(friendlyLaunchError(err))}</div>`);
+ } finally {
+ state.claiming.delete(address);
+ await loadCoins();
+ refreshBalance();
+ }
+}
+
+boot();
diff --git a/src/launch/launch-wallet.js b/src/launch/launch-wallet.js
new file mode 100644
index 000000000..dbb360784
--- /dev/null
+++ b/src/launch/launch-wallet.js
@@ -0,0 +1,214 @@
+// Wallet plumbing for /launch: connect + link the wallet to the signed-in
+// account, detect Solana transaction v1 support, sign a server-built
+// transaction in whichever format it was compiled, broadcast it through the
+// same-origin RPC proxy and wait for confirmation.
+//
+// Signing and sending are split (unlike the onchain SolanaAdapter.signAndSend) because a
+// launch needs the signature BEFORE confirmation: a slow confirm must leave the
+// page holding the signature so it can finish recording the launch later
+// instead of losing track of a coin that did land.
+
+import { Connection, VersionedTransaction } from '@solana/web3.js';
+import { getWallets } from '@wallet-standard/app';
+import { findV1WalletStandardSigner } from '../onchain/adapters/solana.js';
+
+const RPC_URL = `${typeof window !== 'undefined' ? window.location.origin : 'https://three.ws'}/api/solana-rpc`;
+
+let connection = null;
+function rpc() {
+ if (!connection) connection = new Connection(RPC_URL, 'confirmed');
+ return connection;
+}
+
+/** The injected provider the adapter will also pick, for signing v0 transactions. */
+export function injectedProvider() {
+ if (typeof window === 'undefined') return null;
+ if (window.threeWsWallet?.isThreeWs) return window.threeWsWallet;
+ if (window.solana?.isThreeWs) return window.solana;
+ if (window.phantom?.solana?.isPhantom) return window.phantom.solana;
+ if (window.solana?.isPhantom) return window.solana;
+ if (window.backpack?.solana) return window.backpack.solana;
+ if (window.solflare?.isSolflare) return window.solflare;
+ return null;
+}
+
+export function walletInstalled() {
+ return !!injectedProvider();
+}
+
+async function v1SignerFor(address) {
+ let signer = findV1WalletStandardSigner(getWallets().get(), address);
+ if (signer) return signer;
+ // The injected connect does not always populate the Wallet Standard account
+ // list. A silent standard:connect on the v1-capable wallets fills it without
+ // a second prompt when the site is already approved.
+ for (const wallet of getWallets().get()) {
+ const v1 = wallet?.features?.['solana:signTransaction']?.supportedTransactionVersions?.includes(1);
+ const connect = wallet?.features?.['standard:connect']?.connect;
+ if (!v1 || !connect) continue;
+ try {
+ await connect({ silent: true });
+ } catch {
+ continue;
+ }
+ signer = findV1WalletStandardSigner(getWallets().get(), address);
+ if (signer) return signer;
+ }
+ return null;
+}
+
+function toBase64(bytes) {
+ let out = '';
+ for (let i = 0; i < bytes.length; i++) out += String.fromCharCode(bytes[i]);
+ return btoa(out);
+}
+
+async function walletIsLinked(address) {
+ const res = await fetch('/api/auth/wallets', { credentials: 'include' });
+ if (!res.ok) return false;
+ const { wallets = [] } = await res.json();
+ return wallets.some((w) => w.address === address && w.chain_type === 'solana');
+}
+
+/**
+ * Link a wallet to the signed-in account with a signed message. This is the
+ * account-link endpoint, not SIWS sign-in: SIWS verify replaces the session
+ * with the wallet's own account, which would log a creator out of the account
+ * that owns their agents. `takeover` moves a wallet another account holds.
+ */
+export async function linkWallet(address, { takeover = false } = {}) {
+ const provider = injectedProvider();
+ if (!provider?.signMessage) throw Object.assign(new Error('This wallet cannot sign messages.'), { code: 'NO_PROVIDER' });
+ const nonceRes = await fetch('/api/auth/wallets/nonce-solana', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ address, chainId: 'mainnet' }),
+ });
+ const nonce = await nonceRes.json().catch(() => ({}));
+ if (!nonceRes.ok) throw Object.assign(new Error(nonce.error_description || 'Could not start wallet linking.'), { code: nonce.error });
+ let signature;
+ try {
+ ({ signature } = await provider.signMessage(new TextEncoder().encode(nonce.message), 'utf8'));
+ } catch (e) {
+ throw rejected(e);
+ }
+ const linkRes = await fetch('/api/auth/wallets/link-solana', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ message: nonce.message, signature: toBase64(signature), takeover }),
+ });
+ const link = await linkRes.json().catch(() => ({}));
+ if (!linkRes.ok) throw Object.assign(new Error(link.error_description || 'Wallet link failed.'), { code: link.error });
+}
+
+/**
+ * Connect the browser wallet and make sure it is linked to the signed-in
+ * three.ws account (the launch endpoints refuse unlinked signers). A wallet
+ * held by another account throws `address_in_use`; the page offers a takeover.
+ * @returns {Promise<{ address: string, v1: boolean, name: string }>}
+ */
+export async function connectLaunchWallet() {
+ const provider = injectedProvider();
+ if (!provider) throw Object.assign(new Error('No Solana wallet found.'), { code: 'NO_PROVIDER' });
+ let address;
+ try {
+ const resp = await provider.connect();
+ address = (resp?.publicKey || provider.publicKey)?.toString();
+ } catch (e) {
+ throw rejected(e);
+ }
+ if (!address) throw new Error('Could not read the wallet address.');
+ if (!(await walletIsLinked(address))) await linkWallet(address);
+ const signer = await v1SignerFor(address);
+ const name = signer?.wallet?.name || (provider.isPhantom ? 'Phantom' : provider.isBackpack ? 'Backpack' : provider.isSolflare ? 'Solflare' : 'Wallet');
+ return { address, v1: !!signer, name };
+}
+
+/** Reconnect silently on page load when the site is already trusted. */
+export async function restoreLaunchWallet() {
+ const provider = injectedProvider();
+ if (!provider?.connect) return null;
+ try {
+ const resp = await provider.connect({ onlyIfTrusted: true });
+ const address = (resp?.publicKey || provider.publicKey)?.toString();
+ // An unlinked wallet is left for the Connect button, which runs the link.
+ if (!address || !(await walletIsLinked(address))) return null;
+ const signer = await v1SignerFor(address);
+ return { address, v1: !!signer, name: signer?.wallet?.name || 'Wallet' };
+ } catch {
+ return null;
+ }
+}
+
+export async function solBalance(address) {
+ const { PublicKey } = await import('@solana/web3.js');
+ return (await rpc().getBalance(new PublicKey(address), 'confirmed')) / 1e9;
+}
+
+function fromBase64(b64) {
+ const bin = atob(b64);
+ const out = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
+ return out;
+}
+
+function rejected(e) {
+ if (e?.code === 4001 || /reject|denied|cancel/i.test(e?.message || '')) {
+ return Object.assign(new Error('Signature cancelled.'), { code: 'USER_REJECTED' });
+ }
+ return e;
+}
+
+/**
+ * Sign a server-prepared transaction with the wallet and broadcast it.
+ * @param {{ txBase64: string, version: 0|1, address: string }} o
+ * @returns {Promise<string>} the transaction signature
+ */
+export async function signAndBroadcast({ txBase64, version, address }) {
+ let raw;
+ try {
+ if (version === 1) {
+ const signer = await v1SignerFor(address);
+ if (!signer) {
+ throw Object.assign(new Error('This wallet cannot sign Solana transaction v1. Switch the format to v0 or update the wallet.'), {
+ code: 'TX_VERSION_UNSUPPORTED',
+ });
+ }
+ const [result] = await signer.feature.signTransaction({
+ account: signer.account,
+ transaction: fromBase64(txBase64),
+ chain: 'solana:mainnet',
+ options: { preflightCommitment: 'confirmed' },
+ });
+ if (!result?.signedTransaction) throw new Error('The wallet returned no signed transaction.');
+ raw = result.signedTransaction;
+ } else {
+ const provider = injectedProvider();
+ if (!provider) throw Object.assign(new Error('No Solana wallet found.'), { code: 'NO_PROVIDER' });
+ const tx = VersionedTransaction.deserialize(fromBase64(txBase64));
+ const signed = await provider.signTransaction(tx);
+ raw = signed.serialize();
+ }
+ } catch (e) {
+ throw rejected(e);
+ }
+ return rpc().sendRawTransaction(raw, { skipPreflight: false, preflightCommitment: 'confirmed', maxRetries: 3 });
+}
+
+/**
+ * Poll until the signature confirms. Resolves true when confirmed, false when
+ * the window elapses (it may still land), throws when it failed on-chain.
+ */
+export async function waitForConfirmation(signature, { timeoutMs = 75_000 } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const { value } = await rpc().getSignatureStatuses([signature], { searchTransactionHistory: true });
+ const status = value?.[0];
+ if (status?.err) throw Object.assign(new Error(`The transaction failed on-chain: ${JSON.stringify(status.err)}`), { code: 'TX_FAILED' });
+ if (status?.confirmationStatus === 'confirmed' || status?.confirmationStatus === 'finalized') return true;
+ await new Promise((r) => setTimeout(r, 1_500));
+ }
+ return false;
+}
diff --git a/tests/launch-model.test.js b/tests/launch-model.test.js
new file mode 100644
index 000000000..20113129f
--- /dev/null
+++ b/tests/launch-model.test.js
@@ -0,0 +1,94 @@
+import { describe, expect, it } from 'vitest';
+import {
+ formatAmount,
+ friendlyLaunchError,
+ launchCost,
+ launchProblems,
+ normalizeSymbol,
+ parseBuyIn,
+ shareText,
+ suggestSymbol,
+} from '../src/launch/launch-model.js';
+import { txPaidPlatformFee } from '../api/_lib/pump-platform-fee.js';
+
+describe('launch model', () => {
+ it('normalizes tickers to uppercase letters and digits', () => {
+ expect(normalizeSymbol(' $aura-2 ')).toBe('AURA2');
+ expect(normalizeSymbol('abcdefghijklmnop')).toBe('ABCDEFGHIJ');
+ });
+
+ it('suggests a ticker from a name', () => {
+ expect(suggestSymbol('Neon Pilot Agent')).toBe('NPA');
+ expect(suggestSymbol('Aurora')).toBe('AURORA');
+ expect(suggestSymbol('')).toBe('');
+ });
+
+ it('parses dev-buy input strictly', () => {
+ expect(parseBuyIn('')).toBe(0);
+ expect(parseBuyIn('0.25')).toBe(0.25);
+ expect(parseBuyIn('1e3')).toBeNaN();
+ expect(parseBuyIn('-1')).toBeNaN();
+ });
+
+ it('lists problems top-down and clears when the form is ready', () => {
+ const empty = launchProblems({});
+ expect(empty.map((p) => p.field)).toEqual(['agent', 'name', 'symbol']);
+ expect(launchProblems({ agentId: 'a', name: 'Aurora', symbol: 'AUR', buyIn: '0.5' })).toEqual([]);
+ expect(launchProblems({ agentId: 'a', name: 'Aurora', symbol: 'AUR', buyIn: '51' })[0].field).toBe('buyIn');
+ expect(launchProblems({ agentId: 'a', name: 'Aurora', symbol: 'AUR', buyIn: '51' }, { quote: 'usdc' })).toEqual([]);
+ });
+
+ it('floors the fee to base units the way the server does', () => {
+ const sol = launchCost({ buyIn: 0.123456789, quote: 'sol', feeBps: 100, createCostSol: 0.022 });
+ expect(sol.fee).toBeCloseTo(0.001234567, 9);
+ expect(sol.totalSol).toBeCloseTo(0.022 + 0.123456789 + 0.001234567, 9);
+ const usdc = launchCost({ buyIn: 25, quote: 'usdc', feeBps: 100, createCostSol: 0.022 });
+ expect(usdc).toMatchObject({ quote: 'USDC', fee: 0.25, totalSol: 0.022, totalQuote: 25.25 });
+ expect(launchCost({ buyIn: 0, feeBps: 100 }).fee).toBe(0);
+ });
+
+ it('formats amounts without trailing zeros', () => {
+ expect(formatAmount(0.5)).toBe('0.5');
+ expect(formatAmount(0.0000001)).toBe('<0.000001');
+ expect(formatAmount(0)).toBe('0');
+ });
+
+ it('writes a share post that links the three.ws coin page', () => {
+ const t = shareText({ name: 'Aurora', symbol: 'AUR', mint: 'M1nt', agentName: 'Aurora' });
+ expect(t).toContain('$AUR');
+ expect(t).toContain('https://three.ws/launches/M1nt');
+ });
+
+ it('turns wallet rejections into plain language', () => {
+ expect(friendlyLaunchError({ code: 'USER_REJECTED', message: 'x' })).toMatch(/cancelled/);
+ expect(friendlyLaunchError(new Error('Blockhash not found'))).toMatch(/expired/);
+ });
+});
+
+describe('txPaidPlatformFee', () => {
+ const recipient = 'Fee1111111111111111111111111111111111111111';
+ const solTx = (delta) => ({
+ transaction: { message: { accountKeys: [{ pubkey: 'Payer' }, { pubkey: recipient }] } },
+ meta: { preBalances: [10_000_000, 1_000], postBalances: [9_000_000, 1_000 + delta] },
+ });
+
+ it('accepts a SOL fee that landed and rejects one that did not', () => {
+ const fee = { asset: 'SOL', amount: '5000', recipient };
+ expect(txPaidPlatformFee(solTx(5000), fee)).toBe(true);
+ expect(txPaidPlatformFee(solTx(0), fee)).toBe(false);
+ expect(txPaidPlatformFee(solTx(0), null)).toBe(true);
+ });
+
+ it('reads USDC fees from token balance deltas', () => {
+ const mint = 'USDCmint';
+ const tx = {
+ transaction: { message: { accountKeys: [] } },
+ meta: {
+ preTokenBalances: [],
+ postTokenBalances: [{ owner: recipient, mint, uiTokenAmount: { amount: '250000' } }],
+ },
+ };
+ expect(txPaidPlatformFee(tx, { asset: 'USDC', amount: '250000', recipient }, mint)).toBe(true);
+ expect(txPaidPlatformFee(tx, { asset: 'USDC', amount: '250001', recipient }, mint)).toBe(false);
+ });
+});