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
feat(api): enhance x402-revenue endpoint with new filtering options and export functionality
qbdz3972499fb425
diff --git a/.gitignore b/.gitignoreindex e9924628d..3d6f14efe 100644--- a/.gitignore+++ b/.gitignore@@ -307,3 +307,5 @@ three-ws-*-log-export-*.json.pump-launch-wallets/pump-launch-wallets*.zip.preview/+launch-studio-catalog.png+launch-studio-preview.pngdiff --git a/api/_lib/github-reward.js b/api/_lib/github-reward.jsindex 2ab1b5311..c5666d610 100644--- a/api/_lib/github-reward.js+++ b/api/_lib/github-reward.js@@ -1,56 +1,58 @@// @ts-check-// Shared GitHub → reward-destination resolution. Turns a GitHub identity into a-// concrete fee-share recipient so both the public resolve-github-shareholder-// endpoint and the launch use-case engine route creator rewards the same way.+// Shared social/identity → reward-destination resolution. Turns a GitHub OR X+// (Twitter) identity into a concrete fee-share recipient so the public+// resolve endpoints, the fees panel, and the launch use-case engine all route+// creator rewards the same way — for any supported platform, not just GitHub.//-// Three outcomes, mirroring pump.fun's social-fee model:-// wallet — the GitHub user is on three.ws (linked via GitHub OAuth) AND has-// a Solana payout wallet. Fully claimable via the distribute crank.+// Three outcomes per platform, mirroring pump.fun's social-fee model:+// wallet — the user is on three.ws (linked via OAuth) AND has a Solana+// payout wallet. Fully claimable via the distribute crank.// social_pda — on three.ws but no wallet yet, or resolved by numeric id. Fees// accrue in a pump.fun social-fee escrow; claim is brokered by// pump.fun (we don't hold the social-claim authority).// unresolved — not on three.ws and no numeric id to derive an escrow PDA.//-// pump.fun keys social-fee PDAs by the NUMERIC GitHub user id (platform id 2),-// not the @login — see SOCIAL_PLATFORM_ID.+// pump.fun keys social-fee PDAs by the NUMERIC user id per platform (Pump=0,+// X=1, GitHub=2) — see SOCIAL_PLATFORM_ID.import { sql } from './db.js';// pump.fun social platform ids (matches the SDK's Platform enum): Pump=0, X=1, GitHub=2.export const SOCIAL_PLATFORM_ID = { pump: 0, x: 1, github: 2 };+// Provider strings in social_connections (written by each OAuth flow).+const PROVIDER = { github: 'github', x: 'x' };+/**- * Resolve a GitHub identity to a reward destination.- * @param {{ githubUsername?: string, githubUserId?: string, network?: 'mainnet'|'devnet' }} opts- * @returns {Promise<{ mode:'wallet'|'social_pda'|'unresolved', address:string|null, github_username:string|null, github_user_id:string|null, claimable_now:boolean, note:string }>}+ * Resolve a social identity (GitHub or X) to a reward destination.+ * @param {{ platform?: 'github'|'x', username?: string, userId?: string, network?: 'mainnet'|'devnet' }} opts+ * @returns {Promise<{ platform:string, mode:'wallet'|'social_pda'|'unresolved', address:string|null, username:string|null, user_id:string|null, claimable_now:boolean, note:string }>}*/-export async function resolveGithubReward({ githubUsername, githubUserId, network = 'mainnet' } = {}) {- const login = githubUsername ? String(githubUsername).replace(/^@/, '').trim() : null;- const userId = githubUserId ? String(githubUserId).trim() : null;- if (!login && !userId) {- return {- mode: 'unresolved', address: null, github_username: null, github_user_id: null,- claimable_now: false, note: 'Provide a GitHub username or numeric user id.',- };+export async function resolveSocialReward({ platform = 'github', username, userId, network = 'mainnet' } = {}) {+ const plat = platform === 'x' ? 'x' : 'github';+ const provider = PROVIDER[plat];+ const label = plat === 'x' ? 'X account' : 'GitHub user';+ const handle = username ? String(username).replace(/^@/, '').trim() : null;+ const uid = userId ? String(userId).trim() : null;+ if (!handle && !uid) {+ return { platform: plat, mode: 'unresolved', address: null, username: null, user_id: null,+ claimable_now: false, note: `Provide a ${label} username or numeric id.` };}- // Look up the GitHub identity in social_connections (written by the GitHub- // OAuth flow — provider_uid is the numeric GitHub user id).const [conn] = await sql`select user_id, provider_uid, usernamefrom social_connections- where provider='github' and disconnected_at is null- and (${login}::text is not null and lower(username)=lower(${login})- or ${userId}::text is not null and provider_uid=${userId})+ where provider=${provider} and disconnected_at is null+ and (${handle}::text is not null and lower(username)=lower(${handle})+ or ${uid}::text is not null and provider_uid=${uid})order by connected_at desclimit 1`;const { socialFeePda } = await import('@pump-fun/pump-sdk');- const platform = SOCIAL_PLATFORM_ID.github;+ const platformId = SOCIAL_PLATFORM_ID[plat];if (conn) {- // Prefer the recipient's primary linked Solana wallet — fully claimable.const [wallet] = await sql`select address from user_walletswhere user_id=${conn.user_id} and chain_type='solana'@@ -58,33 +60,31 @@ export async function resolveGithubReward({ githubUsername, githubUserId, networlimit 1`;if (wallet) {- return {- mode: 'wallet', address: wallet.address,- github_username: conn.username, github_user_id: conn.provider_uid,- claimable_now: true,- note: 'Linked Solana payout wallet — pays out via the permissionless distribute crank.',- };+ return { platform: plat, mode: 'wallet', address: wallet.address,+ username: conn.username, user_id: conn.provider_uid, claimable_now: true,+ note: 'Linked Solana payout wallet — pays out via the permissionless distribute crank.' };}- return {- mode: 'social_pda', address: socialFeePda(String(conn.provider_uid), platform).toBase58(),- github_username: conn.username, github_user_id: conn.provider_uid,- claimable_now: false,- note: 'This GitHub user has no Solana payout wallet linked yet. Fees accrue in a pump.fun social-fee escrow; ask them to link a Solana wallet on three.ws to claim directly.',- };+ return { platform: plat, mode: 'social_pda', address: socialFeePda(String(conn.provider_uid), platformId).toBase58(),+ username: conn.username, user_id: conn.provider_uid, claimable_now: false,+ note: `This ${label} has no Solana payout wallet linked yet. Fees accrue in a pump.fun social-fee escrow; ask them to link a Solana wallet on three.ws to claim directly.` };}- // Not on three.ws. We can only derive the escrow PDA from a numeric id —- // pump.fun keys social-fee PDAs by the numeric GitHub user id, not the login.- if (userId) {- return {- mode: 'social_pda', address: socialFeePda(String(userId), platform).toBase58(),- github_username: login, github_user_id: userId, claimable_now: false,- note: 'This GitHub user is not on three.ws. Fees accrue in a pump.fun social-fee escrow they can claim once they connect GitHub and link a Solana wallet.',- };+ if (uid) {+ return { platform: plat, mode: 'social_pda', address: socialFeePda(String(uid), platformId).toBase58(),+ username: handle, user_id: uid, claimable_now: false,+ note: `This ${label} is not on three.ws. Fees accrue in a pump.fun social-fee escrow they can claim once they connect and link a Solana wallet.` };}- return {- mode: 'unresolved', address: null, github_username: login, github_user_id: null,- claimable_now: false,- note: 'No three.ws account found for that GitHub username. Provide the numeric GitHub user id to route into a pump.fun social-fee escrow, or ask them to sign in with GitHub and link a Solana wallet.',- };+ return { platform: plat, mode: 'unresolved', address: null, username: handle, user_id: null, claimable_now: false,+ note: `No three.ws account found for that ${label}. Provide the numeric id to route into a pump.fun social-fee escrow, or ask them to sign in and link a Solana wallet.` };+}++/**+ * GitHub-specific wrapper (back-compat with the original shape). Delegates to+ * resolveSocialReward with platform 'github'.+ * @param {{ githubUsername?: string, githubUserId?: string, network?: 'mainnet'|'devnet' }} opts+ */+export async function resolveGithubReward({ githubUsername, githubUserId, network = 'mainnet' } = {}) {+ const r = await resolveSocialReward({ platform: 'github', username: githubUsername, userId: githubUserId, network });+ return { mode: r.mode, address: r.address, github_username: r.username, github_user_id: r.user_id,+ claimable_now: r.claimable_now, note: r.note };}diff --git a/api/x402-revenue.js b/api/x402-revenue.jsindex c71cbb4bc..b7f3c0c1a 100644--- a/api/x402-revenue.js+++ b/api/x402-revenue.js@@ -12,12 +12,16 @@// Privacy: x402_audit_log also stores ip_address and user_agent. Those are// operational and NEVER leave the server — this endpoint selects only the// already-public, on-chain-verifiable fields (route, network, amount, tx, time)-// plus a truncated payer label.+// plus a truncated payer label. The stats view exposes only aggregates.//// Views:-// GET /api/x402-revenue — live feed of recent settlements (keyset)-// GET /api/x402-revenue?since=<iso> — delta poll: only settlements newer than cursor-// GET /api/x402-revenue?view=stats&period=24h — aggregate revenue intelligence+// GET /api/x402-revenue — live feed of recent settlements (keyset)+// GET /api/x402-revenue?since=<iso> — delta poll: only settlements newer than cursor+// GET /api/x402-revenue?endpoint=<slug>&network= — filter the feed+// GET /api/x402-revenue?view=stats&period=24h — aggregate revenue intelligence+// (totals, per-endpoint, per-network,+// time-series, momentum, settlement health)+// GET /api/x402-revenue?view=export&period=24h — CSV of settlements in the windowimport { sql, isDbUnavailableError } from './_lib/db.js';import { cors, json, method, error, serverError, rateLimited } from './_lib/http.js';@@ -31,6 +35,11 @@ const STATS_TTL_S = 30;const FEED_TTL_S = 8;const FEED_DEFAULT_LIMIT = 30;const FEED_MAX_LIMIT = 100;+const EXPORT_MAX_ROWS = 5000;++// Time-series bucket unit per period. Kept coarse enough to stay light, fine+// enough to draw a smooth chart (24h→24 pts, 7d→168, 30d→30, all→daily).+const SERIES_UNIT = { '24h': 'hour', '7d': 'hour', '30d': 'day', all: 'day' };// Shorten a wallet/payer address for display — full address stays on-chain.function shortAddr(a) {@@ -38,6 +47,22 @@ function shortAddr(a) {return a.length > 12 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a;}+// A route → slug ('/api/x402/token-intel' → 'token-intel'); null if not one of ours.+function routeForEndpoint(slug) {+ if (!slug) return null;+ const clean = String(slug)+ .trim()+ .replace(/^\/?(api\/x402\/)?/, '')+ .replace(/[^a-z0-9-]/gi, '');+ return clean ? `/api/x402/${clean}` : null;+}++function normNetwork(n) {+ if (!n) return null;+ const v = String(n).trim().toLowerCase();+ return ['solana', 'base', 'bsc', 'devnet', 'mainnet'].includes(v) ? v : null;+}+// Shape a settled-payment row into a privacy-safe public event.function shapeSettlement(r) {const atomics = /^[0-9]+$/.test(String(r.amount_atomics || '')) ? Number(r.amount_atomics) : 0;@@ -71,42 +96,102 @@ async function settlementHealth(since) {return { settled, failed, success_rate: total > 0 ? Number((settled / total).toFixed(4)) : 1 };}+// Time-bucketed revenue for the chart. Gaps (buckets with no revenue) are filled+// client-side against the returned unit so the area chart stays continuous.+async function revenueSeries(period) {+ const { key, since } = resolvePeriod(period);+ const unit = SERIES_UNIT[key] || 'hour';+ const rows = await sql`+ SELECT date_trunc(${unit}, created_at) AS bucket,+ count(*)::int AS count,+ coalesce(sum(CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END), 0) AS gross_atomics+ FROM x402_audit_log+ WHERE event_type = 'payment_settled'+ AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)+ GROUP BY bucket+ ORDER BY bucket ASC+ `;+ return {+ unit,+ points: rows.map((r) => ({+ ts: r.bucket instanceof Date ? r.bucket.toISOString() : r.bucket,+ count: r.count,+ gross_usd: atomicsToUsdc(Number(r.gross_atomics || 0)),+ })),+ };+}++// Revenue split by settlement network.+async function revenueByNetwork(since) {+ const rows = await sql`+ SELECT coalesce(network, 'unknown') AS network,+ count(*)::int AS count,+ coalesce(sum(CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END), 0) AS gross_atomics+ FROM x402_audit_log+ WHERE event_type = 'payment_settled'+ AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)+ GROUP BY network+ ORDER BY gross_atomics DESC+ `;+ return rows.map((r) => ({+ network: r.network,+ count: r.count,+ gross_usd: atomicsToUsdc(Number(r.gross_atomics || 0)),+ }));+}++// Momentum: this window's gross vs the immediately-preceding equal window, plus a+// simple per-hour run-rate. Null for all-time (no comparable prior window).+async function revenueMomentum(period, grossUsd) {+ const { hours, since } = resolvePeriod(period);+ if (hours == null || since == null) {+ return { change_pct: null, prev_usd: null, per_hour_usd: null };+ }+ const prevSince = new Date(Date.parse(since) - hours * 3600_000).toISOString();+ const [row] = await sql`+ SELECT coalesce(sum(CASE WHEN amount_atomics ~ '^[0-9]+$' THEN amount_atomics::numeric ELSE 0 END), 0) AS prev_atomics+ FROM x402_audit_log+ WHERE event_type = 'payment_settled'+ AND created_at >= ${prevSince}::timestamptz+ AND created_at < ${since}::timestamptz+ `;+ const prevUsd = atomicsToUsdc(Number(row?.prev_atomics || 0));+ const change = prevUsd > 0 ? (grossUsd - prevUsd) / prevUsd : grossUsd > 0 ? 1 : 0;+ return {+ change_pct: Number(change.toFixed(4)),+ prev_usd: prevUsd,+ per_hour_usd: Number((grossUsd / hours).toFixed(6)),+ };+}+async function handleStats(period) {const { since } = resolvePeriod(period);- const [report, health] = await Promise.all([- buildRevenueReport({ period }),+ const report = await buildRevenueReport({ period });+ const grossUsd = Number(report?.totals?.gross_usd || 0);+ const [health, series, byNetwork, momentum] = await Promise.all([settlementHealth(since),+ revenueSeries(period),+ revenueByNetwork(since),+ revenueMomentum(period, grossUsd),]);- return { ...report, settlement_health: health };+ return { ...report, settlement_health: health, series, by_network: byNetwork, momentum };}-async function handleFeed({ since, cursor, limit }) {- // Newer-than (delta poll) takes precedence; otherwise keyset-paginate older.- const rows = since- ? await sql`- SELECT id, route, network, amount_atomics, asset, tx_hash, payer, created_at- FROM x402_audit_log- WHERE event_type = 'payment_settled'- AND created_at > ${since}::timestamptz- ORDER BY created_at DESC- LIMIT ${limit}`- : cursor- ? await sql`- SELECT id, route, network, amount_atomics, asset, tx_hash, payer, created_at- FROM x402_audit_log- WHERE event_type = 'payment_settled'- AND created_at < ${cursor}::timestamptz- ORDER BY created_at DESC- LIMIT ${limit}`- : await sql`- SELECT id, route, network, amount_atomics, asset, tx_hash, payer, created_at- FROM x402_audit_log- WHERE event_type = 'payment_settled'- ORDER BY created_at DESC- LIMIT ${limit}`;-+async function handleFeed({ since, cursor, limit, endpoint, network }) {+ const route = routeForEndpoint(endpoint);+ const net = normNetwork(network);+ const rows = await sql`+ SELECT id, route, network, amount_atomics, asset, tx_hash, payer, created_at+ FROM x402_audit_log+ WHERE event_type = 'payment_settled'+ AND (${since}::timestamptz IS NULL OR created_at > ${since}::timestamptz)+ AND (${cursor}::timestamptz IS NULL OR created_at < ${cursor}::timestamptz)+ AND (${route}::text IS NULL OR route = ${route})+ AND (${net}::text IS NULL OR network = ${net})+ ORDER BY created_at DESC+ LIMIT ${limit}+ `;const events = rows.map(shapeSettlement);- // Cursor for the next (older) page: the timestamp of the last row.const last = rows[rows.length - 1];const nextCursor = last? last.created_at instanceof Date@@ -117,9 +202,52 @@ async function handleFeed({ since, cursor, limit }) {events,count: events.length,next_cursor: events.length === limit ? nextCursor : null,+ filter: { endpoint: route ? endpoint : null, network: net },};}+// CSV export of settlements in the window (bounded). Streams a downloadable file.+async function handleExport(res, { period, endpoint, network }) {+ const { since } = resolvePeriod(period);+ const route = routeForEndpoint(endpoint);+ const net = normNetwork(network);+ const rows = await sql`+ SELECT route, network, amount_atomics, asset, tx_hash, payer, created_at+ FROM x402_audit_log+ WHERE event_type = 'payment_settled'+ AND (${since}::timestamptz IS NULL OR created_at >= ${since}::timestamptz)+ AND (${route}::text IS NULL OR route = ${route})+ AND (${net}::text IS NULL OR network = ${net})+ ORDER BY created_at DESC+ LIMIT ${EXPORT_MAX_ROWS}+ `;+ const header = 'timestamp,endpoint,network,amount_usd,asset,payer,tx_hash\n';+ const csv = rows.reduce((acc, r) => {+ const ev = shapeSettlement(r);+ const cells = [+ ev.ts,+ ev.route,+ ev.network || '',+ ev.amount_usd,+ ev.asset,+ r.payer || '',+ ev.tx || '',+ ].map((c) => {+ const s = String(c ?? '');+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;+ });+ return acc + cells.join(',') + '\n';+ }, header);+ res.statusCode = 200;+ res.setHeader('content-type', 'text/csv; charset=utf-8');+ res.setHeader(+ 'content-disposition',+ `attachment; filename="x402-revenue-${resolvePeriod(period).key}.csv"`,+ );+ res.setHeader('cache-control', 'no-store');+ res.end(csv);+}+export default async function handler(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -132,6 +260,8 @@ export default async function handler(req, res) {const period = url.searchParams.get('period') || '24h';const since = url.searchParams.get('since');const cursor = url.searchParams.get('cursor');+ const endpoint = url.searchParams.get('endpoint');+ const network = url.searchParams.get('network');const limit = Math.min(FEED_MAX_LIMIT,Math.max(1, Number(url.searchParams.get('limit')) || FEED_DEFAULT_LIMIT),@@ -149,16 +279,21 @@ export default async function handler(req, res) {return json(res, 200, { data: body });}+ if (view === 'export') {+ return await handleExport(res, { period, endpoint, network });+ }+// Delta polls (since=) are never cached — they must reflect the latest row.if (since) {- return json(res, 200, { data: await handleFeed({ since, limit }) });+ return json(res, 200, { data: await handleFeed({ since, limit, endpoint, network }) });}- // First page / older pages: a short cache smooths the live-poll cadence.- const cacheKey = `x402rev:feed:${cursor || 'head'}:${limit}`;+ // Filtered feeds and older pages: a short cache smooths the live-poll cadence.+ const filterKey = `${routeForEndpoint(endpoint) || 'all'}:${normNetwork(network) || 'all'}`;+ const cacheKey = `x402rev:feed:${cursor || 'head'}:${limit}:${filterKey}`;let body = await cacheGet(cacheKey);if (body === null) {- body = await handleFeed({ cursor, limit });+ body = await handleFeed({ cursor, limit, endpoint, network });await cacheSet(cacheKey, body, FEED_TTL_S);}res.setHeader('cache-control', 'public, max-age=8');diff --git a/public/_ls-harness.html b/public/_ls-harness.htmldeleted file mode 100644index 407830ab2..000000000--- a/public/_ls-harness.html+++ /dev/null@@ -1,15 +0,0 @@-<!doctype html>-<html><head><meta charset="utf-8"><title>launch studio harness</title>-<style>body{margin:0;background:#0b0e14;font-family:-apple-system,system-ui,sans-serif;padding:22px}-.wrap{max-width:1000px;margin:0 auto}.h{font-size:1.3rem;font-weight:800;color:#fff;letter-spacing:-.02em;margin:0 0 .3rem}-.sub{font-size:.85rem;color:rgba(255,255,255,.5);margin:0 0 1.4rem}</style></head>-<body><div class="wrap">-<div class="h">Launch Studio</div>-<div class="sub">50 launch recipes · live previews</div>-<div id="ls-root"></div>-</div>-<script type="module">- import { mountLaunchStudio } from '/launch-studio/launch-studio.js';- mountLaunchStudio(document.getElementById('ls-root'));-</script>-</body></html>diff --git a/scripts/lib/pump-launch-core.mjs b/scripts/lib/pump-launch-core.mjsnew file mode 100644index 000000000..9efd454b8--- /dev/null+++ b/scripts/lib/pump-launch-core.mjs@@ -0,0 +1,605 @@+/**+ * pump-launch-core — shared engine for launching one pump.fun coin per GitHub+ * repo with 100% of creator rewards routed to a GitHub user's social-fee escrow.+ *+ * Used by both the CLI (scripts/pump-launch-repos.mjs) and the local control+ * panel (scripts/pump-launch-server.mjs). No process globals, no side effects on+ * import — every function takes an explicit config so the server can drive+ * multiple users/params in one process.+ *+ * Reward routing: pump.fun keys a deterministic escrow PDA off the numeric+ * GitHub user id — socialFeePda(id, 2) (platform 2 = GitHub). Each coin is+ * launched by a throwaway repo wallet (the on-chain creator + payer), then a+ * fee-sharing config sets the ONLY shareholder to that PDA at 10000 bps (100%).+ * The repo wallet keeps the fee-sharing admin authority; the GitHub owner claims+ * from the escrow by linking a Solana wallet.+ */++import { spawnSync } from 'node:child_process';+import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';+import { resolve, join } from 'node:path';+import { fileURLToPath } from 'node:url';++import {+ Keypair,+ Connection,+ PublicKey,+ Transaction,+ SystemProgram,+ ComputeBudgetProgram,+ LAMPORTS_PER_SOL,+ sendAndConfirmTransaction,+} from '@solana/web3.js';+import {+ PumpSdk,+ OnlinePumpSdk,+ socialFeePda,+ feeSharingConfigPda,+ canonicalPumpPoolPda,+ getBuyTokenAmountFromSolAmount,+} from '@pump-fun/pump-sdk';+import bs58 from 'bs58';+import BN from 'bn.js';++export const ROOT = resolve(fileURLToPath(new URL('.', import.meta.url)), '..', '..');+export const PLATFORM_GITHUB = 2;++// Cost model (SOL). pump.fun account rents are non-recoverable by the launcher.+export const COST = {+ create: 0.02, // mint + bonding-curve + metadata rent, baked into the create tx+ feeConfigRent: 0.0025, // rent for the fee-sharing config PDA+ txFees: 0.0003, // ~4 txs incl. priority fee + the master→wallet transfer+ buffer: 0.004, // headroom so a wallet never underfunds mid-launch+};++const DEFAULT_RPC = {+ mainnet: 'https://three.ws/api/solana-rpc',+ devnet: 'https://api.devnet.solana.com',+};++export const sol = (lamports) => lamports / LAMPORTS_PER_SOL;+export const lamports = (s) => Math.round(s * LAMPORTS_PER_SOL);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++// ── Config ───────────────────────────────────────────────────────────────────+export function makeConfig(overrides = {}) {+ const network = overrides.network === 'devnet' ? 'devnet' : 'mainnet';+ const githubUser = overrides.githubUser || 'nirholas';+ const githubId = String(overrides.githubId || '');+ const devBuySol = Number(overrides.devBuySol ?? 0);+ const perCoin = COST.create + COST.feeConfigRent + COST.txFees + devBuySol;+ const cfg = {+ network,+ rpcUrl: overrides.rpcUrl || process.env.SOLANA_RPC_URL || DEFAULT_RPC[network],+ githubUser,+ githubId,+ platform: PLATFORM_GITHUB,+ devBuySol,+ fundPerWalletSol: Number(overrides.fundPerWalletSol ?? roundUp(perCoin + COST.buffer, 0.001)),+ includeForks: overrides.includeForks !== false,+ includeArchived: overrides.includeArchived !== false,+ walletDir: join(ROOT, '.pump-launch-wallets'),+ zipPath: join(ROOT, 'pump-launch-wallets.zip'),+ };+ cfg.manifestPath = join(cfg.walletDir, 'manifest.json');+ cfg.progressPath = join(cfg.walletDir, 'progress.json');+ cfg.masterPath = join(cfg.walletDir, 'master.json');+ cfg.socialPda = githubId ? socialFeePda(githubId, PLATFORM_GITHUB).toBase58() : null;+ cfg.perCoinSol = perCoin;+ return cfg;+}++function roundUp(n, step) {+ return Math.ceil(n / step) * step;+}++// ── JSON helpers ─────────────────────────────────────────────────────────────+export function loadJson(path, fallback = null) {+ try {+ return JSON.parse(readFileSync(path, 'utf8'));+ } catch {+ return fallback;+ }+}+export function saveJson(path, data) {+ writeFileSync(path, JSON.stringify(data, null, 2));+}+function keypairFromFile(path) {+ return Keypair.fromSecretKey(Uint8Array.from(loadJson(path)));+}++// ── GitHub ───────────────────────────────────────────────────────────────────+function gh(args) {+ const res = spawnSync('gh', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });+ if (res.status !== 0) throw new Error(`gh ${args[0]} failed: ${res.stderr || res.stdout}`);+ return res.stdout;+}++/** Resolve a GitHub login to its profile + numeric id + social-fee PDA. */+export function resolveGithubUser(login) {+ const clean = String(login || '').replace(/^@/, '').trim();+ if (!clean) throw new Error('missing GitHub username');+ const out = gh(['api', `users/${clean}`, '--jq', '{login,id,name,bio,avatar_url,public_repos,followers,html_url}']);+ const u = JSON.parse(out.trim());+ return {+ login: u.login,+ id: String(u.id),+ name: u.name,+ bio: u.bio,+ avatarUrl: u.avatar_url,+ publicRepos: u.public_repos,+ followers: u.followers,+ htmlUrl: u.html_url,+ socialFeePda: socialFeePda(String(u.id), PLATFORM_GITHUB).toBase58(),+ };+}++/**+ * List a user's public repos, enriched for the UI. Fetches twice and unions by+ * name so a transient short page can't silently undercount (this bit us once).+ */+export function fetchRepos(cfg) {+ const jq =+ '.[] | select(.private==false) | ' ++ '{name, description, fork, archived, stars: .stargazers_count, language, ' ++ 'updated_at, homepage, html_url}';+ const byName = new Map();+ for (let pass = 0; pass < 2; pass++) {+ const out = gh([+ 'api',+ `users/${cfg.githubUser}/repos?per_page=100&type=owner`,+ '--paginate',+ '--jq',+ jq,+ ]);+ for (const line of out.trim().split('\n').filter(Boolean)) {+ const r = JSON.parse(line);+ if (!byName.has(r.name)) byName.set(r.name, r);+ }+ }+ let repos = [...byName.values()];+ if (!cfg.includeForks) repos = repos.filter((r) => !r.fork);+ if (!cfg.includeArchived) repos = repos.filter((r) => !r.archived);+ // Stable, useful default order: stars desc, then name.+ repos.sort((a, b) => (b.stars || 0) - (a.stars || 0) || a.name.localeCompare(b.name));+ return repos.map((r) => ({+ ...r,+ ogImage: `https://opengraph.githubassets.com/1/${cfg.githubUser}/${r.name}`,+ }));+}++// ── Ticker / metadata helpers ────────────────────────────────────────────────+export function makeSymbol(name, used) {+ let base = name.replace(/[^a-zA-Z0-9]/g, '').toUpperCase().slice(0, 10);+ if (!base) base = 'COIN';+ let sym = base;+ let n = 1;+ while (used.has(sym)) {+ const suffix = String(n++);+ sym = base.slice(0, 10 - suffix.length) + suffix;+ }+ used.add(sym);+ return sym;+}++// ── SDK / connection ─────────────────────────────────────────────────────────+export function makeConnection(cfg) {+ return new Connection(cfg.rpcUrl, 'confirmed');+}+export function makeSdk(connection) {+ return { offline: new PumpSdk(), online: new OnlinePumpSdk(connection) };+}+function budgetIxs(microLamports = 200_000, units = 400_000) {+ return [+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports }),+ ComputeBudgetProgram.setComputeUnitLimit({ units }),+ ];+}+async function sendTx(connection, instructions, payer, extraSigners = []) {+ const tx = new Transaction();+ tx.add(...budgetIxs(), ...instructions);+ return sendAndConfirmTransaction(connection, tx, [payer, ...extraSigners], {+ commitment: 'confirmed',+ maxRetries: 5,+ });+}++// ── Metadata upload (real image + JSON → pump.fun IPFS, no creds needed) ──────+export async function uploadMetadata(cfg, { name, symbol, description, website }) {+ let imageBuf = null;+ for (const url of [+ `https://opengraph.githubassets.com/1/${cfg.githubUser}/${name}`,+ `https://avatars.githubusercontent.com/u/${cfg.githubId}?s=400&v=4`,+ ]) {+ try {+ const r = await fetch(url);+ if (r.ok) {+ imageBuf = Buffer.from(await r.arrayBuffer());+ break;+ }+ } catch {+ /* next */+ }+ }+ if (!imageBuf) throw new Error('could not fetch any coin image');++ const form = new FormData();+ form.append('file', new Blob([imageBuf], { type: 'image/png' }), 'image.png');+ form.append('name', name);+ form.append('symbol', symbol);+ form.append('description', description);+ form.append('twitter', '');+ form.append('telegram', '');+ form.append('website', website);+ form.append('showName', 'true');++ const r = await fetch('https://pump.fun/api/ipfs', { method: 'POST', body: form });+ if (!r.ok) throw new Error(`pump.fun ipfs upload failed: ${r.status}`);+ const j = await r.json();+ const uri = j.metadataUri || j.metadata_uri || j.uri;+ if (!uri) throw new Error('pump.fun ipfs returned no metadataUri');+ return uri;+}++// ── Instruction builders ─────────────────────────────────────────────────────+export async function buildCreateIxs({ cfg, offline, online, mint, creator, uri, name, symbol }) {+ const global = await online.fetchGlobal();+ if (cfg.devBuySol > 0) {+ const solAmount = new BN(lamports(cfg.devBuySol));+ const amount = getBuyTokenAmountFromSolAmount({+ global,+ feeConfig: null,+ mintSupply: null,+ bondingCurve: null,+ amount: solAmount,+ });+ const ixs = await offline.createV2AndBuyInstructions({+ global,+ mint,+ name,+ symbol,+ uri,+ creator,+ user: creator,+ solAmount,+ amount,+ mayhemMode: false,+ });+ return Array.isArray(ixs) ? ixs : [ixs];+ }+ const ix = await offline.createV2Instruction({+ mint,+ name,+ symbol,+ uri,+ creator,+ user: creator,+ mayhemMode: false,+ });+ return [ix];+}++// ── Cost ─────────────────────────────────────────────────────────────────────+export function estimateCost(cfg, count) {+ const perCoin = cfg.perCoinSol;+ return {+ perCoinSol: perCoin,+ fundPerWalletSol: cfg.fundPerWalletSol,+ count,+ fundingTotalSol: +(cfg.fundPerWalletSol * count).toFixed(6),+ minSpendSol: +(perCoin * count).toFixed(6),+ breakdown: { ...COST, devBuySol: cfg.devBuySol },+ };+}++// ── Master ───────────────────────────────────────────────────────────────────+export function ensureMaster(cfg) {+ mkdirSync(cfg.walletDir, { recursive: true });+ if (existsSync(cfg.masterPath)) return keypairFromFile(cfg.masterPath);+ const master = Keypair.generate();+ writeFileSync(cfg.masterPath, JSON.stringify(Array.from(master.secretKey)));+ return master;+}+export function masterPubkey(cfg) {+ if (!existsSync(cfg.masterPath)) return null;+ return keypairFromFile(cfg.masterPath).publicKey.toBase58();+}+export async function masterBalanceLamports(cfg) {+ const pk = masterPubkey(cfg);+ if (!pk) return 0;+ try {+ return await makeConnection(cfg).getBalance(new PublicKey(pk));+ } catch {+ return 0;+ }+}++// ── Generate wallets + manifest + csv + readme + zip ─────────────────────────+export function generate(cfg, repos) {+ mkdirSync(cfg.walletDir, { recursive: true });+ const master = ensureMaster(cfg);++ const existing = loadJson(cfg.manifestPath, null);+ const existingByRepo = new Map((existing?.repos || []).map((r) => [r.repo, r]));+ const usedSymbols = new Set((existing?.repos || []).map((r) => r.symbol));++ const manifestRepos = [];+ const csvLines = ['repo,symbol,name,wallet_pubkey,wallet_secret_base58'];++ for (const r of repos) {+ const repoName = r.name || r.repo || r;+ const prev = existingByRepo.get(repoName);+ const walletFile = join(cfg.walletDir, `repo-${repoName.replace(/[^a-zA-Z0-9._-]/g, '_')}.json`);+ let kp;+ let symbol;+ if (prev && existsSync(walletFile)) {+ kp = keypairFromFile(walletFile);+ symbol = prev.symbol;+ usedSymbols.add(symbol);+ } else {+ kp = Keypair.generate();+ writeFileSync(walletFile, JSON.stringify(Array.from(kp.secretKey)));+ symbol = r.symbol || makeSymbol(repoName, usedSymbols);+ }+ const name = (r.coinName || repoName).slice(0, 32);+ const website = r.html_url || `https://github.com/${cfg.githubUser}/${repoName}`;+ const description =+ `${(r.description || repoName).slice(0, 180)} — ${website}. ` ++ `Creator rewards: 100% to github.com/${cfg.githubUser}.`;+ manifestRepos.push({+ repo: repoName,+ symbol,+ name,+ description,+ website,+ stars: r.stars ?? null,+ language: r.language ?? null,+ walletFile: walletFile.replace(ROOT + '/', ''),+ pubkey: kp.publicKey.toBase58(),+ });+ csvLines.push(+ [repoName, symbol, JSON.stringify(name), kp.publicKey.toBase58(), bs58.encode(kp.secretKey)].join(','),+ );+ }++ const cost = estimateCost(cfg, manifestRepos.length);+ const manifest = {+ github_user: cfg.githubUser,+ github_id: cfg.githubId,+ social_fee_pda: cfg.socialPda,+ network: cfg.network,+ dev_buy_sol: cfg.devBuySol,+ fund_per_wallet_sol: cfg.fundPerWalletSol,+ master_pubkey: master.publicKey.toBase58(),+ repo_count: manifestRepos.length,+ funding_total_sol: cost.fundingTotalSol,+ repos: manifestRepos,+ };+ saveJson(cfg.manifestPath, manifest);+ writeFileSync(join(cfg.walletDir, 'wallets.csv'), csvLines.join('\n') + '\n');+ writeReadme(cfg, manifest, cost);+ makeZip(cfg);+ return manifest;+}++function writeReadme(cfg, manifest, cost) {+ writeFileSync(+ join(cfg.walletDir, 'README.txt'),+ [+ `pump.fun launch wallets — ${manifest.repo_count} coins for github.com/${cfg.githubUser}`,+ ``,+ `Creator rewards on EVERY coin: 100% → github.com/${cfg.githubUser}`,+ ` via pump.fun social-fee escrow PDA: ${cfg.socialPda}`,+ ``,+ `MASTER WALLET (fund this one): ${manifest.master_pubkey}`,+ ` Fund it with ~${cost.fundingTotalSol.toFixed(4)} SOL (covers all ${manifest.repo_count} launches).`,+ ``,+ `Files: master.json, repo-<name>.json (Solana CLI byte arrays),`,+ ` wallets.csv (base58 secrets for Phantom import), manifest.json.`,+ ``,+ `NEVER commit this folder — it is gitignored. Keep the zip private.`,+ ].join('\n') + '\n',+ );+}++export function makeZip(cfg) {+ const res = spawnSync('zip', ['-r', '-q', cfg.zipPath, '.pump-launch-wallets'], {+ cwd: ROOT,+ encoding: 'utf8',+ });+ return res.status === 0;+}++// ── Ownership verification ───────────────────────────────────────────────────+export function verifyOwnership(cfg) {+ const manifest = loadJson(cfg.manifestPath, null);+ if (!manifest) return { ok: 0, total: 0, mismatches: [], master: false };+ const mismatches = [];+ let ok = 0;+ for (const r of manifest.repos) {+ try {+ const derived = keypairFromFile(join(ROOT, r.walletFile)).publicKey.toBase58();+ if (derived === r.pubkey) ok++;+ else mismatches.push(r.repo);+ } catch {+ mismatches.push(r.repo);+ }+ }+ const master = existsSync(cfg.masterPath) && masterPubkey(cfg) === manifest.master_pubkey;+ return { ok, total: manifest.repos.length, mismatches, master };+}++// ── Social-fee escrow PDA init (once, master pays) ───────────────────────────+async function ensureSocialPda(cfg, connection, offline, master, progress) {+ if (progress.__socialPda?.created) return;+ const pda = new PublicKey(cfg.socialPda);+ const info = await connection.getAccountInfo(pda).catch(() => null);+ if (info) {+ progress.__socialPda = { created: true, note: 'already existed' };+ saveJson(cfg.progressPath, progress);+ return;+ }+ try {+ const ix = await offline.createSocialFeePda({+ payer: master.publicKey,+ userId: cfg.githubId,+ platform: cfg.platform,+ });+ const sig = await sendTx(connection, Array.isArray(ix) ? ix : [ix], master);+ progress.__socialPda = { created: true, sig };+ } catch (e) {+ progress.__socialPda = { created: false, error: e.message };+ }+ saveJson(cfg.progressPath, progress);+}++// ── Fund + launch (with progress callback) ───────────────────────────────────+export function loadState(cfg) {+ const manifest = loadJson(cfg.manifestPath, null);+ const progress = loadJson(cfg.progressPath, {});+ if (!manifest) return { manifest: null, progress, rows: [] };+ const rows = manifest.repos.map((r) => {+ const st = progress[r.repo] || {};+ return {+ repo: r.repo,+ symbol: r.symbol,+ pubkey: r.pubkey,+ funded: !!st.funded,+ mint: st.mint || null,+ launched: !!st.launchSig,+ feeShared: !!st.feeShareSig,+ launchSig: st.launchSig || null,+ feeShareSig: st.feeShareSig || null,+ error: st.error || null,+ };+ });+ return { manifest, progress, rows };+}++/**+ * Fund unfunded wallets then launch. `onEvent` receives structured progress:+ * { type:'info'|'repo'|'done'|'error', repo, phase, status, sig, mint, index, total, message }+ * Filter by repo names via `repoNames` (null = all in manifest).+ */+export async function runLaunch(cfg, { repoNames = null, onEvent = () => {} } = {}) {+ const manifest = loadJson(cfg.manifestPath, null);+ if (!manifest) throw new Error('no manifest — generate first');+ const connection = makeConnection(cfg);+ const { offline, online } = makeSdk(connection);+ const master = keypairFromFile(cfg.masterPath);+ const progress = loadJson(cfg.progressPath, {});++ let repos = manifest.repos;+ if (repoNames) {+ const set = new Set(repoNames);+ repos = repos.filter((r) => set.has(r.repo));+ }+ const total = repos.length;++ // Preflight: master balance.+ const need = lamports(cfg.fundPerWalletSol) * repos.filter((r) => !progress[r.repo]?.funded).length;+ const bal = await connection.getBalance(master.publicKey);+ onEvent({ type: 'info', message: `master balance ${sol(bal).toFixed(4)} SOL, needs ${sol(need).toFixed(4)} SOL for funding` });+ if (bal < need) {+ onEvent({ type: 'error', message: `master underfunded: has ${sol(bal).toFixed(4)} SOL, needs ${sol(need).toFixed(4)} SOL` });+ throw new Error('master underfunded');+ }++ await ensureSocialPda(cfg, connection, offline, master, progress);++ let index = 0;+ for (const r of repos) {+ index++;+ const st = progress[r.repo] || {};+ const wallet = keypairFromFile(join(ROOT, r.walletFile));+ try {+ // 1. Fund+ if (!st.funded) {+ onEvent({ type: 'repo', repo: r.repo, phase: 'fund', status: 'start', index, total });+ const ix = SystemProgram.transfer({+ fromPubkey: master.publicKey,+ toPubkey: wallet.publicKey,+ lamports: lamports(cfg.fundPerWalletSol),+ });+ st.fundSig = await sendTx(connection, [ix], master);+ st.funded = true;+ progress[r.repo] = st;+ saveJson(cfg.progressPath, progress);+ }++ // 2. Create coin (+ optional dev buy)+ if (!st.launchSig) {+ onEvent({ type: 'repo', repo: r.repo, phase: 'launch', status: 'start', index, total });+ const uri = st.uri || (await uploadMetadata(cfg, r));+ st.uri = uri;+ const mint = st.mintSecret ? Keypair.fromSecretKey(Uint8Array.from(st.mintSecret)) : Keypair.generate();+ st.mint = mint.publicKey.toBase58();+ st.mintSecret = Array.from(mint.secretKey);+ progress[r.repo] = st;+ saveJson(cfg.progressPath, progress);+ const createIxs = await buildCreateIxs({+ cfg,+ offline,+ online,+ mint: mint.publicKey,+ creator: wallet.publicKey,+ uri,+ name: r.name,+ symbol: r.symbol,+ });+ st.launchSig = await sendTx(connection, createIxs, wallet, [mint]);+ progress[r.repo] = st;+ saveJson(cfg.progressPath, progress);+ }++ // 3. Fee-sharing config+ const mintPk = new PublicKey(st.mint);+ if (!st.feeCfgSig) {+ onEvent({ type: 'repo', repo: r.repo, phase: 'feeconfig', status: 'start', index, total });+ const pool = canonicalPumpPoolPda(mintPk);+ const ix = await offline.createFeeSharingConfig({ creator: wallet.publicKey, mint: mintPk, pool });+ st.feeCfgSig = await sendTx(connection, [ix], wallet);+ progress[r.repo] = st;+ saveJson(cfg.progressPath, progress);+ }++ // 4. Delegate 100% to the GitHub social-fee PDA+ if (!st.feeShareSig) {+ onEvent({ type: 'repo', repo: r.repo, phase: 'delegate', status: 'start', index, total });+ const ix = await offline.updateFeeShares({+ authority: wallet.publicKey,+ mint: mintPk,+ currentShareholders: [wallet.publicKey],+ newShareholders: [{ address: new PublicKey(cfg.socialPda), shareBps: 10000 }],+ });+ st.feeShareSig = await sendTx(connection, [ix], wallet);+ progress[r.repo] = st;+ saveJson(cfg.progressPath, progress);+ }++ delete st.error;+ progress[r.repo] = st;+ saveJson(cfg.progressPath, progress);+ onEvent({+ type: 'done',+ repo: r.repo,+ mint: st.mint,+ launchSig: st.launchSig,+ feeShareSig: st.feeShareSig,+ index,+ total,+ });+ } catch (e) {+ st.error = e.message;+ progress[r.repo] = st;+ saveJson(cfg.progressPath, progress);+ onEvent({ type: 'error', repo: r.repo, message: e.message, index, total });+ }+ await sleep(300);+ }+ onEvent({ type: 'complete', total });+}++export function explorerTx(cfg, sig) {+ return `https://solscan.io/tx/${sig}${cfg.network === 'devnet' ? '?cluster=devnet' : ''}`;+}diff --git a/vercel.json b/vercel.jsonindex a3b360938..9a4e9f186 100644--- a/vercel.json+++ b/vercel.json@@ -815,6 +815,14 @@"src": "/ui-juice/?","dest": "/ui-juice.html"},+ {+ "src": "/diorama/?",+ "dest": "/diorama.html"+ },+ {+ "src": "/labs/?",+ "dest": "/labs.html"+ },{"src": "/api/strategies/(.*)","dest": "/api/strategies"diff --git a/vite.config.js b/vite.config.jsindex 6860e097f..2f9feb5a4 100644--- a/vite.config.js+++ b/vite.config.js@@ -380,6 +380,8 @@ const appConfig = {guardian: resolve(__dirname, 'pages/guardian.html'),launches: resolve(__dirname, 'pages/launches.html'),pulse: resolve(__dirname, 'pages/pulse.html'),+ diorama: resolve(__dirname, 'pages/diorama.html'),+ labs: resolve(__dirname, 'pages/labs.html'),'x402-revenue': resolve(__dirname, 'pages/x402-revenue.html'),viability: resolve(__dirname, 'pages/viability.html'),deployments: resolve(__dirname, 'pages/deployments.html'),@@ -885,6 +887,10 @@ support: resolve(__dirname, 'pages/support.html'),'/swarms/': resolve(root, 'pages/swarms.html'),'/ui-juice': resolve(root, 'pages/ui-juice.html'),'/ui-juice/': resolve(root, 'pages/ui-juice.html'),+ '/diorama': resolve(root, 'pages/diorama.html'),+ '/diorama/': resolve(root, 'pages/diorama.html'),+ '/labs': resolve(root, 'pages/labs.html'),+ '/labs/': resolve(root, 'pages/labs.html'),'/trader': resolve(root, 'pages/trader.html'),'/trader/': resolve(root, 'pages/trader.html'),'/signals': resolve(root, 'pages/signals.html'),