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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add x402 milestone video generation and statistics scripts
nirholasce1d4e1446b3
diff --git a/marketing/x402-milestone/README.md b/marketing/x402-milestone/README.mdnew file mode 100644index 000000000..b90fc7282--- /dev/null+++ b/marketing/x402-milestone/README.md@@ -0,0 +1,113 @@+# x402 milestone video++A 25-second cinematic stats film for the x402 economy's first 25 days on Solana+mainnet: days, payments settled, distinct endpoints paid, all through our own+facilitator. Built for X, Telegram and the holder channel.++The footage is generated with Vertex AI Veo 3. The numbers are not: Veo renders+text as garbled pseudo-glyphs and cannot be trusted with a figure like `59,173`.+So the video is two layers composited together.++| Layer | Produced by | Why |+| --- | --- | --- |+| Background | Veo 3, one 8s clip per beat | Cinematic b-roll no stock library has |+| Foreground | Headless Chrome rendering this site's real webfonts, one transparent PNG per frame | Vector-crisp type, and the figures count up instead of sitting still |+| Composite | ffmpeg: cover-fit, exposure/vignette pass, overlay, 0.5s crossfades | Legibility over bright footage |++## The figures are read from the database, never typed++[`scripts/x402-milestone-stats.mjs`](../../scripts/x402-milestone-stats.mjs)+queries the facilitator's own logs (`x402_self_facilitator_log`,+`x402_ring_ledger`, `x402_autonomous_log`) and the video script consumes its+JSON directly. The video therefore cannot drift from the database. Run the stats+script on its own any time to see the current figures:++```bash+node --env-file=.env scripts/x402-milestone-stats.mjs+```++Each figure and the query that proves it are documented in the header of that+file. Two definitions worth knowing before quoting them publicly:++- **Payments settled** counts `action='settle' AND ok` rows. Verifies are+ excluded; a verify is a quote, not a payment. This is the figure the video+ shows (owner decision, 2026-07-28).+- **On-chain transactions** is `COUNT(DISTINCT tx_sig)` and is materially lower.+ Never present the two as the same number, and never label the payments figure+ "on-chain transactions". See below.++The script also prints the network breakdown, which is what substantiates the+"all on Solana mainnet" claim rather than assuming it.++### The duplicate-signature finding (read before writing any caption)++21% of settle rows share a `tx_sig` with another row: 59,307 rows resolve to+46,624 distinct signatures. This is **not** batching. Two of the shared+transactions were pulled from mainnet on 2026-07-28 and each contains exactly+one SPL token transfer of 1,000 atomic units, yet nine settle rows with nine+distinct idempotency keys were logged against each, seconds apart:++```+5h7Ts4Heg2VcTp91yT14bzXn3AsbVkqfYcabFZfNCUm9JHK6f4NRYhMqggb1TjQcHtAincGtNAyQFgyvqwLb76pw+Ft2uxNa1uvTFZ4eAd6ASjcd8desRzRzxu9xX3NEWKDjYrWHrTAnwUamAuwwo6oU8c56KE58joZnz4LtrhW2UuDX+```++Summed, the log implies 1,103.444 USDC moved; the unique signatures account for+1,027.424 USDC, a 76.019 USDC overstatement. `x402-milestone-stats.mjs` prints a+warning with the live numbers on every run.++Two consequences. For copy: "payments settled" is a claim about the+facilitator's own settlement operations and is what the video says; a claim of+one chain transaction per payment would not survive an explorer check. For+engineering: the settle path is returning an already-used signature for distinct+payment requests, meaning some paid requests were served without their own+settlement. That is a live correctness bug, tracked separately from this video.++## Files++- `x402-milestone.mp4` - the rendered film, 1920x1080, 30fps, 25.1s, silent.+- `x402-milestone-vertical.mp4` - 1080x1920 cut for stories/Reels, from+ natively-generated 9:16 footage (not a center crop of the horizontal).+- `stats-snapshot.json` - the pinned figures both cuts were rendered from, so+ the two formats cannot disagree and the published numbers stay reproducible.+- `other-session-*.mp4` - a different cut of this asset that a concurrent agent+ session wrote to the same paths mid-render. Kept rather than deleted; it uses+ the on-chain figure and different copy. Delete once its owner has landed.++Source clips are kept in `gs://three-ws-veo/x402-milestone*/` so a re-cut does+not require re-paying for generation.++## Re-render++Both steps need `gcloud` auth (`gcloud auth login`) because Veo runs on Vertex+AI. Generation takes 2-4 minutes; compositing takes 2-3 minutes.++```bash+# 1. b-roll -> GCS + local files (only needed if you want new footage)+node scripts/veo-generate.mjs --file prompts.json --download /tmp/veo-clips++# 2. overlay + composite, pulling live figures from the DB+node --env-file=.env scripts/x402-milestone-video.mjs+node --env-file=.env scripts/x402-milestone-video.mjs --vertical+```++To re-cut with an older snapshot instead of live numbers:++```bash+node --env-file=.env scripts/x402-milestone-video.mjs \+ --stats '{"paymentsSettled":55195,"onchainTxs":43856,"distinctEndpoints":3384,"spanDaysWhole":25}'+```++The storyboard (beat order, copy, timing) is the `storyboard()` function in+[`scripts/x402-milestone-video.mjs`](../../scripts/x402-milestone-video.mjs).+One Veo clip per beat, in order; a missing clip is a hard error rather than a+silently reused shot.++## Writing the copy++`x402_self_facilitator_log` records our own ring economy: a small number of+agent wallets paying our own endpoints. The payments, the signatures and the+SOL spent are all real, and "our facilitator settled N payments in 25 days" is+a defensible infrastructure claim. Framing the same number as third-party market+demand is not. Check `distinctPayers` / `distinctRecipients` in the stats output+before writing any caption that implies external demand.diff --git a/marketing/x402-milestone/other-session-x402-milestone-vertical.mp4 b/marketing/x402-milestone/other-session-x402-milestone-vertical.mp4new file mode 100644index 000000000..e8365b7ffBinary files /dev/null and b/marketing/x402-milestone/other-session-x402-milestone-vertical.mp4 differdiff --git a/marketing/x402-milestone/other-session-x402-milestone.mp4 b/marketing/x402-milestone/other-session-x402-milestone.mp4new file mode 100644index 000000000..3c5ae35e8Binary files /dev/null and b/marketing/x402-milestone/other-session-x402-milestone.mp4 differdiff --git a/marketing/x402-milestone/stats-snapshot.json b/marketing/x402-milestone/stats-snapshot.jsonnew file mode 100644index 000000000..12458f1de--- /dev/null+++ b/marketing/x402-milestone/stats-snapshot.json@@ -0,0 +1,28 @@+{+ "paymentsSettled": 59307,+ "rowsSharingSig": 12683,+ "rowsSharingSigPct": 21.4,+ "verifiesOk": 169392,+ "onchainTxs": 46624,+ "settlesWithoutSig": 0,+ "distinctPayers": 9,+ "distinctRecipients": 1,+ "distinctEndpoints": 4133,+ "endpointsFromLedger": 0,+ "endpointsFromAutonomousLog": 4133,+ "distinctServices": 5331,+ "autonomousSuccessfulCalls": 109220,+ "autonomousOnchainTxs": 41636,+ "amountAtomicTotal": "1103544500",+ "feeSolTotal": 4.522617183,+ "firstTs": "2026-07-03T17:10:34.419Z",+ "lastTs": "2026-07-28T19:14:39.641Z",+ "spanDays": 25.09,+ "spanDaysWhole": 25,+ "networks": [+ {+ "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",+ "rows": 59307+ }+ ]+}diff --git a/marketing/x402-milestone/x402-milestone-vertical.mp4 b/marketing/x402-milestone/x402-milestone-vertical.mp4new file mode 100644index 000000000..e8365b7ffBinary files /dev/null and b/marketing/x402-milestone/x402-milestone-vertical.mp4 differdiff --git a/marketing/x402-milestone/x402-milestone.mp4 b/marketing/x402-milestone/x402-milestone.mp4new file mode 100644index 000000000..da5e73715Binary files /dev/null and b/marketing/x402-milestone/x402-milestone.mp4 differdiff --git a/scripts/lib/veo.mjs b/scripts/lib/veo.mjsnew file mode 100644index 000000000..1426c6f92--- /dev/null+++ b/scripts/lib/veo.mjs@@ -0,0 +1,205 @@+// scripts/lib/veo.mjs+//+// Minimal Vertex AI Veo client: submit a text-to-video job, poll it to+// completion, and hand back the GCS URIs of the rendered clips.+//+// Veo is a long-running operation API: `:predictLongRunning` returns an+// operation name immediately, and the result is only readable by POSTing that+// name back to `:fetchPredictOperation`. There is no GET form and no global+// operations collection, which is why this file exists rather than a raw curl.+//+// Auth comes from the ambient gcloud user credential (`gcloud auth+// print-access-token`). In this workspace that credential dies on a short+// Workspace reauth policy, so every call surfaces a 401 as a clear+// "reauthenticate" error instead of a generic HTTP failure.+//+// Usage:+// import { generateVideos } from './lib/veo.mjs';+// const clips = await generateVideos({+// prompts: ['a slow push through a dark server hall'],+// storageUri: 'gs://three-ws-veo/run-1/',+// });+// // -> [{ prompt, gcsUri }]++import { execFile } from 'node:child_process';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);++const PROJECT = process.env.GCP_PROJECT || 'aerial-vehicle-466722-p5';+const LOCATION = process.env.GCP_REGION || 'us-central1';+const DEFAULT_MODEL = process.env.VEO_MODEL || 'veo-3.0-generate-001';++const BASE = (model) =>+ `https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT}` ++ `/locations/${LOCATION}/publishers/google/models/${model}`;++// Veo renders any text in frame as garbled pseudo-glyphs, so every prompt is+// paired with this. Real figures are composited afterwards as vector-crisp+// typography — never generated.+export const NO_TEXT_NEGATIVE =+ 'text, letters, numbers, words, captions, subtitles, watermark, logo, ' ++ 'signage, user interface, charts, graphs, people, faces, hands';++async function accessToken() {+ try {+ const { stdout } = await execFileAsync('gcloud', ['auth', 'print-access-token']);+ return stdout.trim();+ } catch (err) {+ throw new Error(+ 'Could not mint a GCP access token. The workspace credential has expired ' ++ '(Workspace reauth policy) — run `gcloud auth login`, then retry.\n' ++ String(err.stderr || err.message || err),+ );+ }+}++async function callVertex(url, body, token) {+ const res = await fetch(url, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(body),+ });+ const text = await res.text();+ if (res.status === 401 || res.status === 403) {+ throw new Error(+ `Vertex AI rejected the credential (${res.status}). Run \`gcloud auth login\` and retry.\n${text}`,+ );+ }+ if (!res.ok) {+ throw new Error(`Vertex AI ${res.status} on ${url}\n${text}`);+ }+ try {+ return JSON.parse(text);+ } catch {+ throw new Error(`Vertex AI returned non-JSON:\n${text.slice(0, 800)}`);+ }+}++// Submit one prompt. Returns the operation name to poll.+export async function submit({+ prompt,+ storageUri,+ model = DEFAULT_MODEL,+ durationSeconds = 8,+ aspectRatio = '16:9',+ resolution = '1080p',+ generateAudio = false,+ negativePrompt = NO_TEXT_NEGATIVE,+ token,+}) {+ const parameters = {+ sampleCount: 1,+ aspectRatio,+ durationSeconds,+ resolution,+ generateAudio,+ negativePrompt,+ };+ if (storageUri) parameters.storageUri = storageUri;++ const op = await callVertex(+ `${BASE(model)}:predictLongRunning`,+ { instances: [{ prompt }], parameters },+ token,+ );+ if (!op.name) throw new Error(`Veo did not return an operation name: ${JSON.stringify(op)}`);+ return op.name;+}++// Poll one operation until it reports done. Veo jobs typically land in 1-3+// minutes; the ceiling here is deliberately generous because a cold model can+// take longer, and a half-rendered batch is worse than a slow one.+export async function poll({+ operationName,+ model = DEFAULT_MODEL,+ token,+ intervalMs = 10_000,+ timeoutMs = 15 * 60_000,+ onTick = () => {},+}) {+ const deadline = Date.now() + timeoutMs;+ let ticks = 0;+ for (;;) {+ const res = await callVertex(+ `${BASE(model)}:fetchPredictOperation`,+ { operationName },+ token,+ );+ if (res.done) {+ if (res.error) {+ throw new Error(`Veo job failed: ${JSON.stringify(res.error)}`);+ }+ return res.response ?? {};+ }+ if (Date.now() > deadline) {+ throw new Error(`Veo job timed out after ${Math.round(timeoutMs / 1000)}s: ${operationName}`);+ }+ onTick(++ticks);+ await new Promise((r) => setTimeout(r, intervalMs));+ }+}++// Pull every GCS URI out of a finished Veo response. The field name has moved+// between Veo revisions (`videos[].gcsUri` vs `generatedSamples[].video.uri`),+// so both shapes are handled rather than assuming one.+export function extractUris(response) {+ const out = [];+ for (const v of response?.videos ?? []) {+ if (v?.gcsUri) out.push(v.gcsUri);+ }+ for (const s of response?.generatedSamples ?? []) {+ const uri = s?.video?.uri ?? s?.video?.gcsUri;+ if (uri) out.push(uri);+ }+ return out;+}++// Submit every prompt up front, then poll them together. Veo bills and queues+// per job, so fanning out is both faster and no more expensive than serial.+export async function generateVideos({+ prompts,+ storageUri,+ model = DEFAULT_MODEL,+ log = console.log,+ ...opts+}) {+ const token = await accessToken();++ const ops = [];+ for (const [i, prompt] of prompts.entries()) {+ // Each clip gets its own prefix so a rerun never collides with a prior take.+ const uri = storageUri ? `${storageUri.replace(/\/$/, '')}/clip-${i + 1}/` : undefined;+ const name = await submit({ prompt, storageUri: uri, model, token, ...opts });+ log(` submitted clip ${i + 1}/${prompts.length}`);+ ops.push({ prompt, name, index: i });+ }++ const results = await Promise.all(+ ops.map(async (op) => {+ const response = await poll({+ operationName: op.name,+ model,+ token,+ onTick: (t) => {+ if (t % 3 === 0) log(` clip ${op.index + 1} still rendering (${t * 10}s)`);+ },+ });+ const uris = extractUris(response);+ if (!uris.length) {+ // A finished job with no video almost always means the prompt tripped a+ // safety filter; surface the raw response so the cause is visible.+ throw new Error(+ `Clip ${op.index + 1} finished with no video. Response: ${JSON.stringify(response).slice(0, 600)}`,+ );+ }+ log(` clip ${op.index + 1} done -> ${uris[0]}`);+ return { prompt: op.prompt, index: op.index, gcsUri: uris[0] };+ }),+ );++ return results.sort((a, b) => a.index - b.index);+}diff --git a/scripts/veo-generate.mjs b/scripts/veo-generate.mjsnew file mode 100644index 000000000..03f601e09--- /dev/null+++ b/scripts/veo-generate.mjs@@ -0,0 +1,103 @@+#!/usr/bin/env node+// scripts/veo-generate.mjs+//+// Render b-roll clips with Vertex AI Veo 3 and drop them in GCS.+//+// This is the generic lane. It takes prompts (inline or from a JSON file),+// renders them in parallel, and prints the resulting gs:// URIs. Anything that+// needs generated footage — the x402 milestone video, launch teasers, site+// backgrounds — calls this rather than hand-rolling a Vertex request.+//+// Veo cannot draw legible text. Never ask it for a number, a word, or a logo;+// composite those afterwards. `NO_TEXT_NEGATIVE` in lib/veo.mjs enforces it.+//+// Usage:+// node scripts/veo-generate.mjs --prompt "slow push through a dark server hall"+// node scripts/veo-generate.mjs --file prompts.json --out gs://three-ws-veo/my-run+// node scripts/veo-generate.mjs --prompt "..." --duration 6 --audio+//+// Flags:+// --prompt <text> one prompt (repeatable)+// --file <path> JSON array of prompt strings+// --out <gs://...> output prefix (default gs://three-ws-veo/run-<timestamp>)+// --duration <n> seconds per clip: 4, 6, or 8 (default 8)+// --aspect <r> 16:9 or 9:16 (default 16:9)+// --resolution <r> 720p or 1080p (default 1080p)+// --audio let Veo generate an audio track (default off)+// --download <dir> also pull the finished clips to a local directory+// --json print machine-readable results++import { readFile, mkdir } from 'node:fs/promises';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import path from 'node:path';++import { generateVideos } from './lib/veo.mjs';++const execFileAsync = promisify(execFile);+const argv = process.argv.slice(2);++function flag(name) {+ return argv.includes(`--${name}`);+}+function opt(name, fallback = null) {+ const i = argv.indexOf(`--${name}`);+ return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;+}+function allOpts(name) {+ const out = [];+ argv.forEach((a, i) => {+ if (a === `--${name}` && argv[i + 1]) out.push(argv[i + 1]);+ });+ return out;+}++const asJson = flag('json');+const log = asJson ? () => {} : console.log;++let prompts = allOpts('prompt');+const file = opt('file');+if (file) {+ const parsed = JSON.parse(await readFile(file, 'utf8'));+ if (!Array.isArray(parsed)) throw new Error(`${file} must contain a JSON array of prompts`);+ prompts = prompts.concat(parsed);+}+if (!prompts.length) {+ console.error('No prompts. Pass --prompt "…" or --file prompts.json');+ process.exit(1);+}++// Timestamp comes from the process, not the caller, so repeat runs never+// overwrite a previous take.+const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);+const storageUri = opt('out', `gs://three-ws-veo/run-${stamp}`);++log(`Rendering ${prompts.length} clip(s) with Veo 3 -> ${storageUri}`);++const clips = await generateVideos({+ prompts,+ storageUri,+ durationSeconds: Number(opt('duration', '8')),+ aspectRatio: opt('aspect', '16:9'),+ resolution: opt('resolution', '1080p'),+ generateAudio: flag('audio'),+ log,+});++const downloadDir = opt('download');+if (downloadDir) {+ await mkdir(downloadDir, { recursive: true });+ for (const clip of clips) {+ const dest = path.join(downloadDir, `clip-${clip.index + 1}.mp4`);+ await execFileAsync('gcloud', ['storage', 'cp', clip.gcsUri, dest]);+ clip.localPath = dest;+ log(` downloaded -> ${dest}`);+ }+}++if (asJson) {+ console.log(JSON.stringify({ storageUri, clips }, null, 2));+} else {+ console.log('\nDone:');+ for (const c of clips) console.log(` ${c.gcsUri}${c.localPath ? ` (${c.localPath})` : ''}`);+}diff --git a/scripts/x402-milestone-stats.mjs b/scripts/x402-milestone-stats.mjsnew file mode 100644index 000000000..d3a21cf94--- /dev/null+++ b/scripts/x402-milestone-stats.mjs@@ -0,0 +1,186 @@+#!/usr/bin/env node+// scripts/x402-milestone-stats.mjs+//+// Ground-truth milestone figures for the x402 economy, read straight from the+// facilitator's own logs. These numbers get published (marketing video, holder+// changelog, X thread), so every figure here has to be defensible from a single+// query someone else can re-run.+//+// What each figure means, and which table proves it:+//+// payments settled x402_self_facilitator_log WHERE action='settle' AND ok+// One row per settlement our facilitator actually+// completed. Verifies are excluded: a verify is a quote,+// not a payment.+//+// on-chain txs COUNT(DISTINCT tx_sig) over those same rows. Lower than+// the settle count whenever settles share a signature+// (batched) or a settle succeeded without recording one.+// Never claim this equals the payment count.+//+// distinct endpoints COUNT(DISTINCT endpoint) across the ring ledger and the+// autonomous log. This is the "how many different things+// got paid for" number.+//+// window min/max ts over the settle rows, in whole days.+//+// networks Proves the "all on Solana mainnet" claim rather than+// assuming it. Any non-solana network shows up here.+//+// Usage:+// node scripts/x402-milestone-stats.mjs # human-readable table+// node scripts/x402-milestone-stats.mjs --json # machine-readable+//+// Read-only. Safe to run against production at any time.++import { sql } from '../api/_lib/db.js';++const asJson = process.argv.includes('--json');++function n(v) {+ return Number(v ?? 0);+}++function fmt(v) {+ return n(v).toLocaleString('en-US');+}++async function collect() {+ const [settles] = await sql`+ SELECT+ COUNT(*) AS settle_rows,+ COUNT(DISTINCT tx_sig) FILTER (WHERE tx_sig IS NOT NULL) AS onchain_txs,+ COUNT(*) FILTER (WHERE tx_sig IS NULL) AS settles_without_sig,+ COUNT(DISTINCT payer) AS distinct_payers,+ COUNT(DISTINCT pay_to) AS distinct_recipients,+ MIN(ts) AS first_ts,+ MAX(ts) AS last_ts,+ COALESCE(SUM(amount_atomic), 0) AS amount_atomic_total,+ COALESCE(SUM(fee_lamports), 0) AS fee_lamports_total+ FROM x402_self_facilitator_log+ WHERE action = 'settle' AND ok = true+ `;++ const [verifies] = await sql`+ SELECT COUNT(*) AS verify_rows+ FROM x402_self_facilitator_log+ WHERE action = 'verify' AND ok = true+ `;++ const networks = await sql`+ SELECT COALESCE(network, '(null)') AS network, COUNT(*) AS rows+ FROM x402_self_facilitator_log+ WHERE action = 'settle' AND ok = true+ GROUP BY 1+ ORDER BY 2 DESC+ `;++ const [ledgerEndpoints] = await sql`+ SELECT COUNT(DISTINCT endpoint) AS endpoints+ FROM x402_ring_ledger+ WHERE endpoint IS NOT NULL AND kind = 'settle'+ `;++ const [autoEndpoints] = await sql`+ SELECT+ COUNT(DISTINCT endpoint_url) AS endpoints,+ COUNT(DISTINCT service_name) AS services,+ COUNT(*) FILTER (WHERE success) AS successful_calls,+ COUNT(DISTINCT tx_signature) FILTER (WHERE tx_signature IS NOT NULL) AS onchain_txs+ FROM x402_autonomous_log+ WHERE success = true+ `;++ const [unionEndpoints] = await sql`+ SELECT COUNT(*) AS endpoints FROM (+ SELECT DISTINCT endpoint AS e FROM x402_ring_ledger+ WHERE endpoint IS NOT NULL AND kind = 'settle'+ UNION+ SELECT DISTINCT endpoint_url AS e FROM x402_autonomous_log+ WHERE success = true+ ) AS combined+ `;++ const first = settles.first_ts ? new Date(settles.first_ts) : null;+ const last = settles.last_ts ? new Date(settles.last_ts) : null;+ const spanDays =+ first && last ? (last.getTime() - first.getTime()) / 86_400_000 : 0;++ const rowsSharingSig = n(settles.settle_rows) - n(settles.onchain_txs) - n(settles.settles_without_sig);++ return {+ paymentsSettled: n(settles.settle_rows),+ // Settle rows that share a tx signature with another row. Confirmed on+ // mainnet 2026-07-28: sampled transactions carry exactly ONE token transfer+ // yet up to 9 settle rows (9 distinct idempotency keys, seconds apart) are+ // logged against them. So these rows did not each settle on chain, and+ // paymentsSettled is correspondingly higher than the signature count.+ rowsSharingSig,+ rowsSharingSigPct: settles.settle_rows+ ? Math.round((rowsSharingSig / n(settles.settle_rows)) * 1000) / 10+ : 0,+ verifiesOk: n(verifies.verify_rows),+ onchainTxs: n(settles.onchain_txs),+ settlesWithoutSig: n(settles.settles_without_sig),+ distinctPayers: n(settles.distinct_payers),+ distinctRecipients: n(settles.distinct_recipients),+ distinctEndpoints: n(unionEndpoints.endpoints),+ endpointsFromLedger: n(ledgerEndpoints.endpoints),+ endpointsFromAutonomousLog: n(autoEndpoints.endpoints),+ distinctServices: n(autoEndpoints.services),+ autonomousSuccessfulCalls: n(autoEndpoints.successful_calls),+ autonomousOnchainTxs: n(autoEndpoints.onchain_txs),+ amountAtomicTotal: String(settles.amount_atomic_total ?? '0'),+ feeSolTotal: n(settles.fee_lamports_total) / 1e9,+ firstTs: first ? first.toISOString() : null,+ lastTs: last ? last.toISOString() : null,+ spanDays: Math.round(spanDays * 100) / 100,+ // Floor, not ceil. A 25.06-day window is "25 days" in public copy;+ // rounding up would overstate the claim by most of a day.+ spanDaysWhole: Math.floor(spanDays),+ networks: networks.map((r) => ({ network: r.network, rows: n(r.rows) })),+ };+}++const stats = await collect();++if (asJson) {+ console.log(JSON.stringify(stats, null, 2));+} else {+ const rows = [+ ['Payments settled (facilitator)', fmt(stats.paymentsSettled)],+ ['On-chain txs (distinct sigs)', fmt(stats.onchainTxs)],+ [' settles with no sig recorded', fmt(stats.settlesWithoutSig)],+ ['Distinct endpoints paid', fmt(stats.distinctEndpoints)],+ [' from ring ledger', fmt(stats.endpointsFromLedger)],+ [' from autonomous log', fmt(stats.endpointsFromAutonomousLog)],+ ['Distinct services', fmt(stats.distinctServices)],+ ['Distinct payers', fmt(stats.distinctPayers)],+ ['Distinct recipients', fmt(stats.distinctRecipients)],+ ['Verifies (ok)', fmt(stats.verifiesOk)],+ ['Sponsor SOL burned on settles', stats.feeSolTotal.toFixed(4)],+ ['First settle', stats.firstTs ?? '(none)'],+ ['Last settle', stats.lastTs ?? '(none)'],+ ['Span (days)', `${stats.spanDays} (${stats.spanDaysWhole} whole)`],+ ];+ const width = Math.max(...rows.map((r) => r[0].length));+ console.log('\nx402 milestone figures (source: facilitator logs)\n');+ for (const [label, value] of rows) {+ console.log(` ${label.padEnd(width)} ${value}`);+ }+ console.log('\n Networks on settled payments:');+ for (const net of stats.networks) {+ console.log(` ${net.network.padEnd(22)} ${fmt(net.rows)}`);+ }++ if (stats.rowsSharingSig > 0) {+ console.log(+ `\n WARNING: ${fmt(stats.rowsSharingSig)} settle rows (${stats.rowsSharingSigPct}%) share a\n` ++ ' tx signature with another row. Sampled on mainnet, those transactions carry\n' ++ ' exactly one token transfer each, so those rows did not settle independently.\n' ++ ` Publishable as "payments settled" (${fmt(stats.paymentsSettled)}); do NOT publish it as\n` ++ ` on-chain transactions — that figure is ${fmt(stats.onchainTxs)}.`,+ );+ }+ console.log('');+}diff --git a/scripts/x402-milestone-video.mjs b/scripts/x402-milestone-video.mjsnew file mode 100644index 000000000..2df55708c--- /dev/null+++ b/scripts/x402-milestone-video.mjs@@ -0,0 +1,448 @@+#!/usr/bin/env node+// scripts/x402-milestone-video.mjs+//+// Build the x402 milestone video: Veo-generated cinematic b-roll underneath+// frame-accurate, brand-typeset statistics.+//+// Why it is split this way+// ------------------------+// Veo renders text as garbled pseudo-glyphs — it cannot be trusted with a+// figure like "59,173". So the two layers are produced by different tools and+// composited:+//+// background Veo 3 (scripts/veo-generate.mjs) -> gs://three-ws-veo/…+// foreground headless Chrome rendering the real Inter / Space Grotesk /+// JetBrains Mono webfonts this site ships, one transparent PNG+// per frame, so the numbers count up instead of sitting still+// composite ffmpeg — normalize, darken for legibility, overlay, crossfade+//+// The figures are never typed by hand. They come from+// scripts/x402-milestone-stats.mjs, which reads the facilitator's own logs, so+// the video cannot drift from the database. Pass --stats to override for a+// dry run or to reproduce an older snapshot.+//+// Usage:+// node --env-file=.env scripts/x402-milestone-video.mjs+// node --env-file=.env scripts/x402-milestone-video.mjs --clips /tmp/veo-clips+// node --env-file=.env scripts/x402-milestone-video.mjs --stats '{"paymentsSettled":55195,…}'+// node --env-file=.env scripts/x402-milestone-video.mjs --vertical # 9:16 for stories+//+// Flags:+// --clips <dir> directory of clip-1.mp4 … clip-4.mp4 (default /tmp/veo-clips)+// --out <path> output file (default marketing/x402-milestone/x402-milestone.mp4)+// --stats <json> override the live figures+// --vertical render 1080x1920 instead of 1920x1080+// --fps <n> frame rate (default 30)+// --keep-frames leave the intermediate PNG frames on disk for inspection++import { mkdir, rm, writeFile, readdir } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const execFileAsync = promisify(execFile);+const __dirname = path.dirname(fileURLToPath(import.meta.url));+const REPO = path.resolve(__dirname, '..');++const argv = process.argv.slice(2);+const flag = (n) => argv.includes(`--${n}`);+const opt = (n, d = null) => {+ const i = argv.indexOf(`--${n}`);+ return i >= 0 && argv[i + 1] ? argv[i + 1] : d;+};++const VERTICAL = flag('vertical');+const WIDTH = VERTICAL ? 1080 : 1920;+const HEIGHT = VERTICAL ? 1920 : 1080;+const FPS = Number(opt('fps', '30'));+const CLIP_DIR = opt('clips', '/tmp/veo-clips');+const FRAME_ROOT = '/tmp/x402-milestone-frames';+const OUT = path.resolve(+ REPO,+ opt('out', `marketing/x402-milestone/x402-milestone${VERTICAL ? '-vertical' : ''}.mp4`),+);++// ---------------------------------------------------------------------------+// Figures+// ---------------------------------------------------------------------------++async function loadStats() {+ const override = opt('stats');+ if (override) return JSON.parse(override);+ const { stdout } = await execFileAsync(+ process.execPath,+ ['--env-file=.env', 'scripts/x402-milestone-stats.mjs', '--json'],+ { cwd: REPO, maxBuffer: 8 << 20 },+ );+ return JSON.parse(stdout);+}++// ---------------------------------------------------------------------------+// Storyboard+// ---------------------------------------------------------------------------+//+// Four beats, one Veo clip each. `hold` is the beat's on-screen duration before+// the crossfade into the next beat is subtracted.++function storyboard(stats) {+ const days = stats.spanDaysWhole ?? 25;+ return [+ {+ kind: 'stat',+ hold: 6.0,+ eyebrow: 'THREE.WS · X402 ON SOLANA',+ value: days,+ label: 'DAYS',+ sub: 'One facilitator. No third party.',+ },+ // Headline figure is paymentsSettled — the facilitator's own count of+ // settlement operations (owner decision, 2026-07-28).+ //+ // Label it "payments settled", never "on-chain transactions": 21% of these+ // rows share a tx signature with another row, so distinct signatures number+ // ~46.6k, not 59.3k. See the duplicate-signature warning that+ // x402-milestone-stats.mjs prints. Wording that claims one chain+ // transaction per payment would not survive an explorer check.+ {+ kind: 'stat',+ hold: 6.8,+ eyebrow: 'SETTLED',+ value: stats.paymentsSettled,+ label: 'X402 PAYMENTS',+ sub: 'Verified and settled by our own facilitator.',+ },+ {+ kind: 'stat',+ hold: 6.8,+ eyebrow: 'PAID',+ value: stats.distinctEndpoints,+ label: 'DISTINCT ENDPOINTS',+ sub: 'Machine-to-machine payments, no human in the loop.',+ },+ {+ kind: 'end',+ hold: 7.0,+ lines: ['All on Solana mainnet.', 'All through our own facilitator.'],+ mark: 'three.ws',+ },+ ];+}++// ---------------------------------------------------------------------------+// Overlay page+// ---------------------------------------------------------------------------+//+// A single self-contained page exposing window.render(t). Rendering is driven+// frame by frame from Node rather than by CSS animation, so every frame is+// deterministic and the count-up lands on the exact figure.++function overlayHtml(beat, fontDir) {+ const font = (f) => `file://${path.join(fontDir, f)}`;+ const beatJson = JSON.stringify(beat);+ const isEnd = beat.kind === 'end';++ return `<!doctype html>+<html><head><meta charset="utf-8"><style>+@font-face{font-family:'Inter';src:url('${font('inter-latin.woff2')}') format('woff2');font-weight:100 900;font-display:block}+@font-face{font-family:'Space Grotesk';src:url('${font('space-grotesk-latin.woff2')}') format('woff2');font-weight:300 700;font-display:block}+@font-face{font-family:'JetBrains Mono';src:url('${font('jetbrains-mono-latin.woff2')}') format('woff2');font-weight:100 800;font-display:block}+*{margin:0;padding:0;box-sizing:border-box}+html,body{width:${WIDTH}px;height:${HEIGHT}px;background:transparent;overflow:hidden}+/* Contrast scrim. Veo footage is bright and busy in places (the circuit-city+ and particle-burst beats especially); without this, white type over a lit+ region drops below a readable contrast ratio. Baked into the overlay PNG so+ it crossfades with the beat instead of pumping mid-shot. */+.scrim{position:absolute;inset:0;background:${+ VERTICAL+ ? 'linear-gradient(180deg,rgba(0,0,0,.72) 0%,rgba(0,0,0,.45) 30%,rgba(0,0,0,.45) 62%,rgba(0,0,0,.82) 100%)'+ : 'linear-gradient(90deg,rgba(0,0,0,.86) 0%,rgba(0,0,0,.68) 34%,rgba(0,0,0,.28) 62%,rgba(0,0,0,0) 84%)'+ }}+.stage{position:relative;width:${WIDTH}px;height:${HEIGHT}px;+ display:flex;flex-direction:column;justify-content:center;+ padding:0 ${VERTICAL ? 90 : 160}px;font-family:'Inter',system-ui,sans-serif}+.eyebrow{font-family:'JetBrains Mono',monospace;font-weight:500;+ font-size:${VERTICAL ? 26 : 24}px;letter-spacing:.34em;color:#78a9ff;+ text-transform:uppercase;margin-bottom:${VERTICAL ? 34 : 30}px;+ text-shadow:0 0 28px rgba(120,169,255,.55)}+.rule{height:2px;background:linear-gradient(90deg,#78a9ff,rgba(120,169,255,0));+ margin-bottom:${VERTICAL ? 38 : 34}px;box-shadow:0 0 18px rgba(120,169,255,.45)}+.value{font-family:'Space Grotesk','Inter',sans-serif;font-weight:700;+ font-size:${VERTICAL ? 190 : 240}px;line-height:.92;letter-spacing:-.035em;color:#fff;+ font-variant-numeric:tabular-nums;font-feature-settings:'tnum' 1;+ text-shadow:0 0 90px rgba(255,255,255,.32),0 0 200px rgba(120,169,255,.24)}+.label{font-weight:600;font-size:${VERTICAL ? 40 : 46}px;letter-spacing:.24em;+ text-transform:uppercase;color:rgba(255,255,255,.9);margin-top:${VERTICAL ? 22 : 24}px}+.sub{font-weight:400;font-size:${VERTICAL ? 28 : 30}px;letter-spacing:.01em;+ color:rgba(255,255,255,.58);margin-top:${VERTICAL ? 26 : 28}px;max-width:${VERTICAL ? 880 : 1150}px;line-height:1.5}+.endline{font-family:'Space Grotesk','Inter',sans-serif;font-weight:600;+ font-size:${VERTICAL ? 74 : 96}px;line-height:1.22;letter-spacing:-.02em;color:#fff;+ text-shadow:0 0 80px rgba(255,255,255,.28)}+.mark{position:absolute;left:${VERTICAL ? 90 : 160}px;bottom:${VERTICAL ? 130 : 110}px;+ font-family:'Space Grotesk',sans-serif;font-weight:700;font-size:${VERTICAL ? 46 : 54}px;+ letter-spacing:-.01em;color:#fff}+.markrule{position:absolute;left:${VERTICAL ? 90 : 160}px;bottom:${VERTICAL ? 108 : 92}px;+ height:2px;width:${VERTICAL ? 150 : 180}px;background:#78a9ff;box-shadow:0 0 16px rgba(120,169,255,.6)}+.corner{position:absolute;right:${VERTICAL ? 90 : 160}px;bottom:${VERTICAL ? 118 : 100}px;+ font-family:'JetBrains Mono',monospace;font-size:${VERTICAL ? 22 : 22}px;letter-spacing:.2em;+ color:rgba(255,255,255,.4);text-transform:uppercase}+</style></head><body>+<div class="stage" id="stage">+ <div class="scrim"></div>+ ${+ isEnd+ ? `<div id="l0" class="endline"></div><div id="l1" class="endline"></div>+ <div class="mark" id="mark"></div><div class="markrule" id="markrule"></div>`+ : `<div class="eyebrow" id="eyebrow"></div>+ <div class="rule" id="rule"></div>+ <div class="value" id="value"></div>+ <div class="label" id="label"></div>+ <div class="sub" id="sub"></div>+ <div class="corner" id="corner">three.ws</div>`+ }+</div>+<script>+const BEAT = ${beatJson};+const HOLD = BEAT.hold;++// easeOutExpo — fast arrival, long settle. Reads as "the number lands".+const easeOut = t => (t >= 1 ? 1 : 1 - Math.pow(2, -10 * t));+const clamp01 = v => Math.max(0, Math.min(1, v));+// Window a value in with a fade+rise, and out again at the tail of the beat.+function appear(t, start, dur){ return clamp01((t - start) / dur); }+function tail(t){ return clamp01((HOLD - t) / 0.55); }++function setFade(el, p, rise){+ if(!el) return;+ el.style.opacity = String(p);+ el.style.transform = 'translateY(' + ((1 - p) * (rise || 0)).toFixed(2) + 'px)';+}++function render(t){+ const out = tail(t);+ if (BEAT.kind === 'end') {+ const a = easeOut(appear(t, 0.25, 0.9));+ const b = easeOut(appear(t, 0.75, 0.9));+ const m = easeOut(appear(t, 1.5, 0.8));+ setFade(document.getElementById('l0'), a * out, 34);+ setFade(document.getElementById('l1'), b * out, 34);+ document.getElementById('l0').textContent = BEAT.lines[0];+ document.getElementById('l1').textContent = BEAT.lines[1];+ const mark = document.getElementById('mark');+ mark.textContent = BEAT.mark;+ setFade(mark, m * out, 20);+ const mr = document.getElementById('markrule');+ mr.style.opacity = String(m * out);+ mr.style.transform = 'scaleX(' + easeOut(appear(t, 1.6, 0.9)).toFixed(3) + ')';+ mr.style.transformOrigin = 'left center';+ return;+ }++ const eb = easeOut(appear(t, 0.15, 0.6));+ setFade(document.getElementById('eyebrow'), eb * out, 18);+ document.getElementById('eyebrow').textContent = BEAT.eyebrow;++ const rule = document.getElementById('rule');+ const rp = easeOut(appear(t, 0.35, 0.9));+ rule.style.opacity = String(out);+ rule.style.width = (rp * (${VERTICAL ? 620 : 900})).toFixed(1) + 'px';++ // The count-up: 0 -> value over 1.9s, easing to a hard stop on the real figure.+ const cp = easeOut(appear(t, 0.5, 1.9));+ const shown = Math.round(BEAT.value * cp);+ const el = document.getElementById('value');+ el.textContent = shown.toLocaleString('en-US') + (BEAT.suffix || '');+ setFade(el, clamp01(appear(t, 0.4, 0.4)) * out, 26);++ const lp = easeOut(appear(t, 1.15, 0.75));+ setFade(document.getElementById('label'), lp * out, 22);+ document.getElementById('label').textContent = BEAT.label;++ const sp = easeOut(appear(t, 1.55, 0.8));+ setFade(document.getElementById('sub'), sp * out, 20);+ document.getElementById('sub').textContent = BEAT.sub || '';++ document.getElementById('corner').style.opacity = String(0.85 * out);+}+window.render = render;+render(0);+</script></body></html>`;+}++// ---------------------------------------------------------------------------+// Frame rendering+// ---------------------------------------------------------------------------++async function renderFrames(beats, fontDir, log) {+ const { chromium } = await import('playwright');+ const browser = await chromium.launch({ args: ['--force-color-profile=srgb'] });+ const page = await browser.newPage({+ viewport: { width: WIDTH, height: HEIGHT },+ deviceScaleFactor: 1,+ });++ const dirs = [];+ for (const [i, beat] of beats.entries()) {+ const dir = path.join(FRAME_ROOT, `beat-${i + 1}`);+ await rm(dir, { recursive: true, force: true });+ await mkdir(dir, { recursive: true });++ const html = overlayHtml(beat, fontDir);+ const htmlPath = path.join(FRAME_ROOT, `beat-${i + 1}.html`);+ await writeFile(htmlPath, html, 'utf8');+ await page.goto(`file://${htmlPath}`);+ // Block until the webfonts are actually parsed, or frame 1 renders in a+ // fallback face and the beat visibly "snaps" to Space Grotesk.+ await page.evaluate(() => document.fonts.ready);++ const total = Math.round(beat.hold * FPS);+ for (let f = 0; f < total; f++) {+ const t = f / FPS;+ await page.evaluate((tt) => window.render(tt), t);+ await page.screenshot({+ path: path.join(dir, `${String(f + 1).padStart(5, '0')}.png`),+ omitBackground: true,+ });+ }+ log(` beat ${i + 1}: ${total} frames`);+ dirs.push({ dir, beat, frames: total });+ }++ await browser.close();+ return dirs;+}++// ---------------------------------------------------------------------------+// Compositing+// ---------------------------------------------------------------------------++async function ffmpeg(args) {+ try {+ return await execFileAsync('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-y', ...args], {+ maxBuffer: 32 << 20,+ });+ } catch (err) {+ throw new Error(`ffmpeg failed:\n${err.stderr || err.message}`);+ }+}++// One beat = Veo clip, normalized and darkened, with the frame sequence on top.+async function buildSegment({ dir, beat, frames }, clipPath, index, log) {+ const out = path.join(FRAME_ROOT, `seg-${index + 1}.mp4`);+ const dur = frames / FPS;++ // Cover-fit the clip to the target frame, pull the exposure down and desaturate+ // slightly so white type stays legible over bright footage, then vignette.+ const bg =+ `[0:v]trim=0:${dur.toFixed(3)},setpts=PTS-STARTPTS,fps=${FPS},` ++ `scale=${WIDTH}:${HEIGHT}:force_original_aspect_ratio=increase,` ++ `crop=${WIDTH}:${HEIGHT},eq=brightness=-0.10:saturation=0.82:contrast=1.06,` ++ `vignette=PI/4[bg]`;++ await ffmpeg([+ '-i', clipPath,+ '-framerate', String(FPS),+ '-i', path.join(dir, '%05d.png'),+ '-filter_complex', `${bg};[1:v]format=rgba[ov];[bg][ov]overlay=0:0:format=auto[v]`,+ '-map', '[v]',+ '-t', dur.toFixed(3),+ '-c:v', 'libx264', '-preset', 'slow', '-crf', '17',+ '-pix_fmt', 'yuv420p',+ out,+ ]);+ log(` segment ${index + 1} composited (${dur.toFixed(1)}s)`);+ return { path: out, duration: dur };+}++// Chain the segments with 0.5s crossfades. xfade offsets are cumulative and+// each transition eats its own duration, so the running offset is tracked+// rather than assumed.+async function concatSegments(segments, outPath, log) {+ const XF = 0.5;+ const inputs = segments.flatMap((s) => ['-i', s.path]);++ let filter = '';+ let last = '0:v';+ let offset = segments[0].duration - XF;+ for (let i = 1; i < segments.length; i++) {+ const tag = i === segments.length - 1 ? 'vout' : `x${i}`;+ filter += `[${last}][${i}:v]xfade=transition=fade:duration=${XF}:offset=${offset.toFixed(3)}[${tag}];`;+ last = tag;+ offset += segments[i].duration - XF;+ }+ filter = filter.replace(/;$/, '');++ await mkdir(path.dirname(outPath), { recursive: true });+ await ffmpeg([+ ...inputs,+ '-filter_complex', filter,+ '-map', '[vout]',+ '-c:v', 'libx264', '-preset', 'slow', '-crf', '18',+ '-pix_fmt', 'yuv420p', '-movflags', '+faststart',+ outPath,+ ]);+ const total = segments.reduce((a, s) => a + s.duration, 0) - XF * (segments.length - 1);+ log(` concatenated -> ${total.toFixed(1)}s`);+ return total;+}++// ---------------------------------------------------------------------------++const log = console.log;++const fontDir = path.join(REPO, 'public', 'fonts');+if (!existsSync(path.join(fontDir, 'inter-latin.woff2'))) {+ throw new Error(`Brand fonts not found in ${fontDir}`);+}++log('Loading figures from the facilitator logs…');+const stats = await loadStats();+log(+ ` ${Number(stats.paymentsSettled).toLocaleString('en-US')} settled · ` ++ `${Number(stats.onchainTxs).toLocaleString('en-US')} on-chain · ` ++ `${Number(stats.distinctEndpoints).toLocaleString('en-US')} endpoints · ` ++ `${stats.spanDaysWhole} days`,+);++const beats = storyboard(stats);++// One clip per beat, in order. A missing clip is fatal rather than silently+// reusing an earlier one — a repeated shot reads as a rendering bug on screen.+const clips = beats.map((_, i) => {+ const p = path.join(CLIP_DIR, `clip-${i + 1}.mp4`);+ if (!existsSync(p)) {+ throw new Error(+ `Missing ${p} (storyboard has ${beats.length} beats). Render the b-roll first:\n` ++ ` node scripts/veo-generate.mjs --file <prompts.json> --download ${CLIP_DIR}`,+ );+ }+ return p;+});++await mkdir(FRAME_ROOT, { recursive: true });+log(`Rendering overlay frames at ${WIDTH}x${HEIGHT} @ ${FPS}fps…`);+const frameDirs = await renderFrames(beats, fontDir, log);++log('Compositing…');+const segments = [];+for (const [i, fd] of frameDirs.entries()) {+ segments.push(await buildSegment(fd, clips[i], i, log));+}++const total = await concatSegments(segments, OUT, log);++if (!flag('keep-frames')) {+ for (const fd of frameDirs) await rm(fd.dir, { recursive: true, force: true });+}++const { stdout: probe } = await execFileAsync('ffprobe', [+ '-v', 'error',+ '-show_entries', 'format=duration,size',+ '-of', 'default=noprint_wrappers=1',+ OUT,+]);++log(`\nDone -> ${OUT}`);+log(probe.trim().split('\n').map((l) => ` ${l}`).join('\n'));+log(` ${total.toFixed(1)}s · ${WIDTH}x${HEIGHT} · ${FPS}fps`);