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(fee-bridge): pay a coin's creator fees to any X handle in USDC, with a 10-minute crank, claim page, and a wallet sweepback never touches
nirholas3d97f5d8fdec
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 020c13355..1803dcf82 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,7 +6,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-09-17+- **Docs · Fee Bridge** (`/docs/fee-bridge`): How the Fee Bridge pays a coin's creator fees to an X handle in USDC: routing a coin, the 80/20 conversion, claiming with X, the API, and the exactly-once safety model.+- **Fee Bridge** (`/fee-bridge`): Route a pump.fun coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana, no wallet needed up front; 20% of every converted dollar buys $THREE for the treasury.+- **Agent wallets that cannot sign no longer look tradeable**: A small number of agent wallets hold a balance that three.ws cannot currently sign for. Their Portfolio tab used to show a live net worth with Trade buttons, and the Trade tab showed a working form, so the first sign of trouble was a failed withdrawal. Portfolio and Trade now say up front that trading and withdrawals are paused for that wallet, hide the actions that cannot work, and link straight to support. The explanation is also clearer: the balance has not moved, it is still on chain at the same address, and you should not create a replacement wallet while access is being restored. (`/agents`) `[fix]`- **Ask your AI assistant to show the picture inside a Solana transaction**: Some Solana transactions carry a small image written straight into their memo, which explorers show as thousands of characters of unreadable text. A new free MCP server, @three-ws/solana-memo-media-mcp, lets Claude, Cursor or any other MCP client fetch a transaction by its signature and show you the image directly, alongside who signed it and a fingerprint of the exact bytes. It can also scan an account's recent history and pick out only the transactions that carry images. It needs no account, key or wallet, never writes anything, and only shows PNG, JPEG, WebP and GIF files whose contents match their label. The Onchain Viewer at /onchain was also fixed: it only recognised the newest memo program, so memos written through the standard Solana memo program were reported as missing. It now reads all three. (`/docs/mcp-solana-memo-media`) `[feature, fix]`+- **Fee Bridge: pay a coin's creator fees to any X account in USDC**: A coin's creator fees can now go to a person by their X handle instead of a wallet address. Route the fees to the Fee Bridge from a coin's Fees & rewards panel (or register any pump.fun coin on /fee-bridge), and every ten minutes the bridge converts them to USDC: 80% is credited to the handle and 20% buys $THREE for the treasury. The handle's owner signs in with X, links a Solana wallet and withdraws, and balances over $5 are then paid automatically. Anyone can look up what a handle has earned, and every payout links to its transaction. (`/fee-bridge`) `[feature]`## 2026-09-16diff --git a/CLAUDE.md b/CLAUDE.mdindex f84ef6eef..060731d4c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -311,7 +311,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).- 3D: Three.js with glTF/GLB.- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (118 as of 2026-09-16, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (119 as of 2026-09-17, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.diff --git a/README.md b/README.mdindex 837a85526..7e629825c 100644--- a/README.md+++ b/README.md@@ -9996,7 +9996,7 @@ The full OpenAPI 3.1 spec is available at `/openapi.json`. The key API surface iCron schedules are declared in `vercel.json` (still the live cron/route config the server reads) and executed in production by **Google Cloud Scheduler**, which calls each endpoint on its schedule. All cron endpoints are fail-closed — a missing auth token aborts with an error rather than silently skipping (see [Security Hardening](#security-hardening)).-The crons in `vercel.json` (118 entries on 2026-09-16) are routed through a single dynamic handler at [`api/cron/[name].js`](api/cron/[name].js); the `name` segment selects the handler function. Scheduler jobs are provisioned from the `vercel.json` cron list via [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs). The table below is a selection of the notable jobs, each schedule quoted verbatim from `vercel.json`; that file is the complete list.+The crons in `vercel.json` (119 entries on 2026-09-17) are routed through a single dynamic handler at [`api/cron/[name].js`](api/cron/[name].js); the `name` segment selects the handler function. Scheduler jobs are provisioned from the `vercel.json` cron list via [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs). The table below is a selection of the notable jobs, each schedule quoted verbatim from `vercel.json`; that file is the complete list.| Schedule | Endpoint | Purpose || -------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 8fc615fdf..8f32bad25 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -207,6 +207,7 @@ bottom.| Generative 3D drops (supply-capped collections) | engine [api/_lib/drops.js](api/_lib/drops.js), store [api/_lib/drop-store.js](api/_lib/drop-store.js), routes [api/drops/[action].js](api/drops/%5Baction%5D.js) `→ /api/drops/{list,get,items,verify,create,publish,reveal}`, index [pages/drops.html](pages/drops.html) + [src/drops.js](src/drops.js) `→ /drops`, collection [pages/drop-collection.html](pages/drop-collection.html) + [src/drop-collection.js](src/drop-collection.js) `→ /drops/:slug`, styles [src/drops.css](src/drops.css) | In-repo | A drop stores its SPEC, not its art: every item's traits derive from (seed, index, layers) alone, so the whole supply is a pure function and a holder can recompute it. Creator gives a base style plus weighted trait layers; the roll is instant and free at any supply up to 10,000 because no art is generated at create time. Rarity is scored from the ACTUAL rolled distribution (sum of supply/occurrences per trait), ranked, and bucketed into the platform's common/rare/epic/legendary tiers. A published sha256 over the canonical spec is the commitment; the seed stays withheld until publish, which freezes the spec one-way. Art is forged per item on reveal through [api/forge.js](api/forge.js) (claim-then-poll, conditional UPDATE so a double click cannot start two jobs, stale claims self-release after 15 min), which is what keeps a 10k collection economically possible. Reveals inherit the universal animation retarget and the GLB/VRM/USDZ export path. Distinct from `/drop/:id` (the unrelated sealed wallet gift claim page); the routes are ordered so they cannot shadow each other. Schema: [drops + drop_items](api/_lib/migrations/20260901120000_generative_drops.sql). Docs: [docs/drops.md](docs/drops.md). Tests: [tests/drops-engine.test.js](tests/drops-engine.test.js) || Token-gated 3D embeds (holder-only interactive scenes) | Gate config + on-chain verify [api/_lib/embed-gate.js](api/_lib/embed-gate.js), access tokens [api/_lib/embed-gate-token.js](api/_lib/embed-gate-token.js), endpoints [api/embed/gate-create.js](api/embed/gate-create.js) + [api/embed/gate-verify.js](api/embed/gate-verify.js), gate-aware resolver [api/embed/resolve.js](api/embed/resolve.js), MCP tool [api/_mcp/tools/embed.js](api/_mcp/tools/embed.js) (`create_gated_embed`), widget [public/embed/v1.js](public/embed/v1.js) (`<three-d>`) + standalone host [public/embed/v1/gated.html](public/embed/v1/gated.html) `→ /embed/v1/gated` | In-repo | `create_gated_embed(asset_id, gate)` turns an avatar or on-chain agent you own into a holder-only interactive `<three-d>` embed — visitors must prove a real, server-verified SPL balance (SIWS challenge → nonce → signature → Solana RPC read, never a client-reported number) before the live scene renders; below the bar they see a designed locked teaser + connect-wallet CTA. `mint` defaults to $THREE but is a runtime parameter (coin-agnostic plumbing). Anti-abuse: short-lived signed access tokens (auto re-verify on expiry) + per-IP/per-wallet rate limits. Storage: [embed_gates + embed_gate_nonces](api/_lib/migrations/20260708120000_embed_gates.sql). Spec: [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md#token-gating). Docs: [docs/token-gated-3d-embeds.md](docs/token-gated-3d-embeds.md). Tests: [tests/embed-gate.test.js](tests/embed-gate.test.js) || Agent token plans (the coin an agent will become) | Rules + storage [api/_lib/agent-token-plan.js](api/_lib/agent-token-plan.js) (migration [api/_lib/migrations/20260811130000_agent_token_plans.sql](api/_lib/migrations/20260811130000_agent_token_plans.sql)), API actions `plan` + `plan-dry-run` in [api/agents/tokens/[action].js](api/agents/tokens/%5Baction%5D.js) `→ /api/agents/tokens/{plan,plan-dry-run}`, profile panel [src/agent-token-plan.js](src/agent-token-plan.js) on `/agents/:id` | In-repo · Live | The launch configuration bound to the agent record: one saved, editable plan per (agent, network) carrying the coin's name, ticker, story, artwork, pairing, buyback share and dev buy, with a derived readiness verdict and SOL cost estimate. Saving costs nothing and mints nothing. `plan-dry-run` is the free proof lane: it builds the SAME pump.fun create instructions the real launch builds from the SAME plan, compiles them against a real blockhash and simulates them on the cluster (devnet by default), never signing and never broadcasting, and separates `funding_required` from a genuinely broken plan. Both launch paths (`/api/agents/tokens/launch-confirm` from the owner's wallet, `/api/pump/launch-agent` from the agent's custodial wallet) call `markPlanLaunched` and write a `pump_agent_mints` row, which is also what finally puts user-wallet launches into `/launches` and the profile's launch history. Docs: [docs/agent-tokens.md](docs/agent-tokens.md). Tests: [tests/agent-token-plan.test.js](tests/agent-token-plan.test.js), [tests/agent-token-plan-api.test.js](tests/agent-token-plan-api.test.js), [tests/agent-token-plan-render.test.js](tests/agent-token-plan-render.test.js) |+| Fee Bridge (creator fees to an X account in USDC) | Page [pages/fee-bridge.html](pages/fee-bridge.html) `→ /fee-bridge` + [src/fee-bridge.js](src/fee-bridge.js) + [src/fee-bridge.css](src/fee-bridge.css), API [api/fee-bridge/[action].js](api/fee-bridge/%5Baction%5D.js) `→ /api/fee-bridge/*`, engine [api/_lib/fee-bridge/](api/_lib/fee-bridge/engine.js) (config, chain, ledger, math), cron [api/cron/fee-bridge.js](api/cron/fee-bridge.js) (every 10 min), migration [api/_lib/migrations/20260917150000_fee_bridge.sql](api/_lib/migrations/20260917150000_fee_bridge.sql), studio option in [public/studio/fees-panel.js](public/studio/fees-panel.js) | In-repo | A coin routes 100% of its pump.fun creator fees to the bridge wallet (`FEE_BRIDGE_SECRET_KEY_B64`, signer `fee-bridge`, exempt from economy sweeps via `holdsUserFunds`) and is registered to an X handle after an on-chain routing and ownership check. The cron cranks distribution, swaps SOL to USDC on Jupiter, buys $THREE for the treasury with 20% and credits 80% to the handle. The owner connects X (read scope, `return_to=/fee-bridge`), links a Solana wallet and withdraws; balances past $5 auto-pay. Every send persists its signature before broadcast so passes resume from chain state. Off until `FEE_BRIDGE_ENABLED`. Docs: [docs/fee-bridge.md](docs/fee-bridge.md). Tests: [tests/fee-bridge-math.test.js](tests/fee-bridge-math.test.js) || Agent token market data (what the coin looks like on the profile) | Cluster read [api/_lib/pump-curve-view.js](api/_lib/pump-curve-view.js) `→ GET /api/pump/curve` + `GET /api/v1/pump/curve`, view model [src/widgets/bonding-curve.js](src/widgets/bonding-curve.js) (`computeView`), normalization + widget [src/pump/coin-status-card.js](src/pump/coin-status-card.js) (`mapCoin` / `mapCurve` / `mountCoinStatus`), profile wiring [src/agent-detail.js](src/agent-detail.js) (token chip + launch history) | In-repo · Live | The live market half of an agent token. Two sources, one normalized shape: pump.fun's indexer (`/api/pump/coin`, mainnet, carries logo + 24h volume) and the bonding curve read straight off the cluster (`/api/pump/curve`), which is the ONLY source on devnet and the fallback whenever the indexer has not indexed a fresh mint or cannot be reached. A devnet coin renders in SOL and is badged `DEVNET` (devnet SOL has no dollar value) and links to the explorer instead of a pump.fun page that does not exist for that cluster, so the free rehearsal path renders exactly like a real launch. The curve gate accepts a pump.fun-ground `pump` suffix, a three.ws `3ws` mark, any plausible devnet address, and otherwise asks `pump_agent_mints` whether the mint is one of ours: a coin launched from a user's own wallet carries no mark and used to be refused with a cached `not_a_pump_mint` 404. Market cap is derived as price × supply because the SDK's `price.marketCap` goes negative on live curves. Free proof: [scripts/agent-token-market-proof.mjs](scripts/agent-token-market-proof.mjs) (reads only, signs nothing). Docs: [docs/agent-tokens.md](docs/agent-tokens.md). Tests: [tests/pump-curve-mint-gate.test.js](tests/pump-curve-mint-gate.test.js), [tests/agent-detail-launch-history.test.js](tests/agent-detail-launch-history.test.js), [src/pump/coin-status-card.curve.dom.test.js](src/pump/coin-status-card.curve.dom.test.js) || Launch Studio (coin-launch use cases) | [api/_lib/launch/](api/_lib/launch) `→ /launch-studio`, [api/pump/launch-studio.js](api/pump/launch-studio.js), [public/launch-studio/launch-studio.js](public/launch-studio/launch-studio.js) | In-repo | Engine + catalog of 50 declarative launch recipes: reward coins for trending GitHub repos/creators ([github-trending.js](api/_lib/github-trending.js)) and coins riding live narratives ([launcher-trends.js](api/_lib/launcher-trends.js)). Live preview, then a `/launch` handoff that carries the recipe's fee routing as `?reward=` and pre-fills the fee split after the mint. Docs: [docs/launch-usecases.md](docs/launch-usecases.md), [api/_lib/launch/README.md](api/_lib/launch/README.md) || Coin launchpad for 3D agents (`/launch`) | [pages/launch.html](pages/launch.html) + [src/launch/launch-page.js](src/launch/launch-page.js) `→ /launch`, logic [src/launch/launch-model.js](src/launch/launch-model.js), wallet signing [src/launch/launch-wallet.js](src/launch/launch-wallet.js), tx assembly [api/_lib/pump-launch-tx.js](api/_lib/pump-launch-tx.js), endpoints in [api/pump/[action].js](api/pump/%5Baction%5D.js) (`launch-config`, `my-coins`, `build-metadata`, `launch-prep`, `launch-confirm`, `launch-agent`, `collect-creator-fee-*`) | Live | Pick one of your agents, name the coin, launch on pump.fun from your wallet or the agent's wallet, then claim creator rewards under My coins. Metadata links the agent page and (for public avatars) its GLB. A disclosed 1% fee on the dev buy rides in the launch transaction and is verified at confirm. Transactions compile v0 against pump.fun's lookup table, or Solana transaction v1 when v0 overflows and the wallet supports it. `?reward=` recipe links mount the studio launch panel ([public/launch/launch.js](public/launch/launch.js)). Docs: [docs/launchpad.md](docs/launchpad.md) |diff --git a/api/_lib/economy-sweepback.js b/api/_lib/economy-sweepback.jsindex 206efe3f6..f5c397adf 100644--- a/api/_lib/economy-sweepback.js+++ b/api/_lib/economy-sweepback.js@@ -215,6 +215,12 @@ export async function sweepBack({ connection, mode = 'excess', includeTokens = tconst wallets = new Map();for (const spec of SOLANA_SIGNERS) {if (spec.isMaster || spec.network === 'devnet') continue;+ // Money held for third parties (unpaid Fee Bridge recipients) is not platform+ // float: no mode, not even drain, may consolidate it.+ if (spec.holdsUserFunds) {+ skipped.push({ name: spec.name, reason: 'holds_user_funds' });+ continue;+ }const { keypair, configured, decodeError } = await loadSignerKeypair(spec);if (!configured) continue;if (decodeError || !keypair) {@@ -426,6 +432,12 @@ export async function reclaimIdleSol({ connection, network = 'mainnet', dryRun =const wallets = new Map();for (const spec of SOLANA_SIGNERS) {if (spec.isMaster || spec.network === 'devnet') continue;+ // Money held for third parties (unpaid Fee Bridge recipients) is not platform+ // float: no mode, not even drain, may consolidate it.+ if (spec.holdsUserFunds) {+ skipped.push({ name: spec.name, reason: 'holds_user_funds' });+ continue;+ }const { keypair, configured, decodeError } = await loadSignerKeypair(spec);if (!configured) continue;if (decodeError || !keypair) {diff --git a/api/_lib/fee-bridge/chain.js b/api/_lib/fee-bridge/chain.jsnew file mode 100644index 000000000..7520cf20a--- /dev/null+++ b/api/_lib/fee-bridge/chain.js@@ -0,0 +1,222 @@+// @ts-check+// On-chain primitives for the Fee Bridge: read a coin's fee-sharing state, and+// send transactions exactly once.+//+// Exactly-once sending: the caller persists a transaction's signature and+// blockhash BEFORE it is broadcast. If the process dies after that, the next tick+// asks the chain what happened (resolveTracked): landed, reverted, still pending,+// or dropped because its blockhash expired without it landing. Only a dropped or+// reverted transaction is ever rebuilt, so no swap, payout, or crank can be sent+// twice.++import {+ ComputeBudgetProgram,+ PublicKey,+ TransactionInstruction,+ TransactionMessage,+ VersionedTransaction,+} from '@solana/web3.js';+import {+ createAssociatedTokenAccountIdempotentInstruction,+ createTransferCheckedInstruction,+ getAssociatedTokenAddressSync,+} from '@solana/spl-token';+import bs58 from 'bs58';++import { getConnection, getPumpSdkV2 } from '../pump.js';+import { confirmOrThrow } from '../solana/confirm.js';+import { tokenProgramIdForMint } from '../token/token-program.js';+import { NATIVE_SOL_MINT, SUPPORTED_QUOTE_MINTS } from './config.js';++const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');+const PRIORITY_MICRO_LAMPORTS = 100_000;++export function connection() {+ return getConnection({ network: 'mainnet' });+}++/** Base58 signature of a signed transaction (its first signature). */+export function signatureOf(tx) {+ const sig = tx.signatures?.[0];+ if (!sig) throw new Error('transaction is not signed');+ return bs58.encode(sig);+}++/**+ * Build and sign a v0 transaction paid by `signer`.+ * @param {import('@solana/web3.js').Keypair} signer+ * @param {TransactionInstruction[]} instructions+ */+export async function buildSigned(signer, instructions) {+ const conn = connection();+ const { blockhash } = await conn.getLatestBlockhash('confirmed');+ const message = new TransactionMessage({+ payerKey: signer.publicKey,+ recentBlockhash: blockhash,+ instructions: [ComputeBudgetProgram.setComputeUnitPrice({ microLamports: PRIORITY_MICRO_LAMPORTS }), ...instructions],+ }).compileToV0Message();+ const tx = new VersionedTransaction(message);+ tx.sign([signer]);+ return { tx, signature: signatureOf(tx), blockhash };+}++/**+ * Sign a pre-built transaction (a Jupiter swap) and read its identity.+ * @param {import('@solana/web3.js').Keypair} signer+ * @param {string} base64+ */+export function signPrebuilt(signer, base64) {+ const tx = VersionedTransaction.deserialize(Buffer.from(base64, 'base64'));+ tx.sign([signer]);+ return { tx, signature: signatureOf(tx), blockhash: tx.message.recentBlockhash };+}++/**+ * Broadcast an already-persisted transaction and wait for it. Throws on revert or+ * timeout; either way the persisted signature is what the resolver checks next.+ * @param {VersionedTransaction} tx+ * @param {string} signature+ */+export async function broadcast(tx, signature) {+ const conn = connection();+ await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 5 });+ await confirmOrThrow(conn, signature, 'confirmed', { timeoutMs: 60_000 });+ return signature;+}++/**+ * What became of a persisted transaction.+ * @param {string} signature+ * @param {string} blockhash+ * @returns {Promise<'landed'|'reverted'|'pending'|'dropped'>}+ */+export async function resolveTracked(signature, blockhash) {+ const conn = connection();+ const { value } = await conn.getSignatureStatuses([signature], { searchTransactionHistory: true });+ const st = value?.[0];+ if (st) {+ if (st.err) return 'reverted';+ if (st.confirmationStatus === 'confirmed' || st.confirmationStatus === 'finalized') return 'landed';+ return 'pending';+ }+ // Unknown to the cluster. While its blockhash is still valid it may yet land;+ // once the blockhash has expired it never can.+ const valid = await conn.isBlockhashValid(blockhash, { commitment: 'confirmed' });+ return valid.value ? 'pending' : 'dropped';+}++/** Landed transaction meta, retried briefly because RPCs index a moment behind confirmation. */+export async function landedMeta(signature) {+ const conn = connection();+ for (let i = 0; i < 6; i++) {+ const tx = await conn.getTransaction(signature, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 });+ if (tx?.meta) {+ const keys = tx.transaction.message.getAccountKeys({ accountKeysFromLookups: tx.meta.loadedAddresses ?? undefined });+ return { meta: tx.meta, accountKeys: keys.staticAccountKeys.map((k) => k.toBase58()) };+ }+ await new Promise((r) => setTimeout(r, 1500));+ }+ throw Object.assign(new Error(`transaction ${signature} confirmed but its details are not yet available`), {+ code: 'meta_unavailable',+ });+}++/**+ * A coin's creator-fee routing as it stands on chain.+ * @param {string} mint+ * @returns {Promise<{ exists: boolean, quoteMint: string, supportedQuote: boolean, hasSharingConfig: boolean, admin: string|null, adminRevoked: boolean, shareholders: Array<{ address: string, bps: number }> }>}+ */+export async function readSharingState(mint) {+ const conn = connection();+ const mintPk = new PublicKey(mint);+ const [{ OnlinePumpSdk, PumpSdk, feeSharingConfigPda }, v2] = await Promise.all([+ import('@pump-fun/pump-sdk'),+ getPumpSdkV2({ network: 'mainnet' }),+ ]);+ const online = new OnlinePumpSdk(conn);+ const bc = await online.fetchBondingCurve(mintPk).catch(() => null);+ if (!bc) {+ return { exists: false, quoteMint: NATIVE_SOL_MINT, supportedQuote: false, hasSharingConfig: false, admin: null, adminRevoked: false, shareholders: [] };+ }+ const rawQuote = /** @type {any} */ (bc).quoteMint;+ const quoteMint = rawQuote && !v2.isLegacyQuoteMint(rawQuote) ? rawQuote.toBase58() : NATIVE_SOL_MINT;++ const cfgInfo = await conn.getAccountInfo(feeSharingConfigPda(mintPk));+ if (!cfgInfo) {+ return { exists: true, quoteMint, supportedQuote: SUPPORTED_QUOTE_MINTS.has(quoteMint), hasSharingConfig: false, admin: null, adminRevoked: false, shareholders: [] };+ }+ const cfg = new PumpSdk().decodeSharingConfig(cfgInfo);+ return {+ exists: true,+ quoteMint,+ supportedQuote: SUPPORTED_QUOTE_MINTS.has(quoteMint),+ hasSharingConfig: true,+ admin: cfg.admin.toBase58(),+ adminRevoked: !!cfg.adminRevoked,+ shareholders: cfg.shareholders.map((s) => ({ address: s.address.toBase58(), bps: Number(s.shareBps) })),+ };+}++/** True when the bridge is the one and only shareholder, at 100%. */+export function routesOnlyTo(state, bridge) {+ return (+ state.hasSharingConfig &&+ state.shareholders.length === 1 &&+ state.shareholders[0].address === bridge &&+ state.shareholders[0].bps === 10_000+ );+}++/**+ * Whether a coin has enough accrued fees to distribute, and the instructions to do it.+ * @param {string} mint+ * @param {string} quoteMint+ * @param {PublicKey} payer+ */+export async function planDistribution(mint, quoteMint, payer) {+ const { OnlinePumpSdk } = await import('@pump-fun/pump-sdk');+ const online = new OnlinePumpSdk(connection());+ const mintPk = new PublicKey(mint);+ const quotePk = new PublicKey(quoteMint);+ const min = await online.getMinimumDistributableFee(mintPk, payer, { quoteMint: quotePk, payer });+ if (!min.canDistribute) {+ return { canDistribute: false, distributable: BigInt(min.distributableFees?.toString?.() ?? '0'), instructions: [] };+ }+ const { instructions } = await online.buildDistributeCreatorFeesInstructions(mintPk, { quoteMint: quotePk, payer });+ return { canDistribute: true, distributable: BigInt(min.distributableFees?.toString?.() ?? '0'), instructions };+}++/**+ * Instructions for an SPL transfer to `owner`, creating their token account when needed.+ * @param {object} a+ * @param {PublicKey} a.from sender and fee payer+ * @param {string} a.to recipient wallet+ * @param {string} a.mint+ * @param {number} a.decimals+ * @param {bigint} a.amount+ * @param {string} a.memo+ */+export async function splTransferInstructions({ from, to, mint, decimals, amount, memo }) {+ const conn = connection();+ const mintPk = new PublicKey(mint);+ const toPk = new PublicKey(to);+ const programId = await tokenProgramIdForMint(conn, mintPk);+ const fromAta = getAssociatedTokenAddressSync(mintPk, from, true, programId);+ const toAta = getAssociatedTokenAddressSync(mintPk, toPk, true, programId);+ return [+ createAssociatedTokenAccountIdempotentInstruction(from, toAta, toPk, mintPk, programId),+ createTransferCheckedInstruction(fromAta, mintPk, toAta, from, amount, decimals, [], programId),+ new TransactionInstruction({ keys: [], programId: MEMO_PROGRAM_ID, data: Buffer.from(memo.slice(0, 180), 'utf8') }),+ ];+}++/** Base-unit balance of one SPL mint held by `owner` (0 when it holds none). */+export async function splBalance(owner, mint) {+ const conn = connection();+ const res = await conn.getParsedTokenAccountsByOwner(new PublicKey(owner), { mint: new PublicKey(mint) });+ return res.value.reduce((a, acc) => a + BigInt(acc.account.data.parsed?.info?.tokenAmount?.amount ?? '0'), 0n);+}++export async function lamports(owner) {+ return BigInt(await connection().getBalance(new PublicKey(owner), 'confirmed'));+}diff --git a/api/_lib/fee-bridge/config.js b/api/_lib/fee-bridge/config.jsnew file mode 100644index 000000000..97dd29b5d--- /dev/null+++ b/api/_lib/fee-bridge/config.js@@ -0,0 +1,108 @@+// @ts-check+// Fee Bridge knobs and the bridge signer. Every knob is an env var with a safe+// default; execution stays off until FEE_BRIDGE_ENABLED is truthy AND the signer+// secret is present, so a deploy without them is a clean, recorded no-op.++import { SOLANA_SIGNERS, loadSignerKeypair, resolveSignerPubkey } from '../solana-signers.js';+import { SOLANA_USDC_MINT } from '../../payments/_config.js';+import { TOKEN_MINT } from '../token/config.js';+import { usdToUsdcAtomics } from '../token/buyback-math.js';++export const NATIVE_SOL_MINT = 'So11111111111111111111111111111111111111112';+export const USDC_MINT = SOLANA_USDC_MINT;+export const THREE_MINT = TOKEN_MINT;+export const SUPPORTED_QUOTE_MINTS = new Set([NATIVE_SOL_MINT, USDC_MINT]);++function num(name, fallback, { min = -Infinity, max = Infinity } = {}) {+ const n = Number(process.env[name]);+ if (!Number.isFinite(n)) return fallback;+ return Math.min(max, Math.max(min, n));+}++export function isEnabled() {+ return /^(1|true|yes|on)$/i.test(String(process.env.FEE_BRIDGE_ENABLED || ''));+}++/** Share of every converted dollar credited to the handle (the rest buys $THREE). */+export function recipientBps() {+ return Math.round(num('FEE_BRIDGE_RECIPIENT_BPS', 8000, { min: 5000, max: 10_000 }));+}++/** Balance at which a linked recipient is paid without asking. */+export function autoPayoutAtomics() {+ return usdToUsdcAtomics(num('FEE_BRIDGE_AUTO_PAYOUT_USD', 5, { min: 1, max: 10_000 }));+}++/** Smallest manual withdrawal. */+export function withdrawMinAtomics() {+ return usdToUsdcAtomics(num('FEE_BRIDGE_WITHDRAW_MIN_USD', 1, { min: 0.1, max: 1000 }));+}++/** A conversion waits until the pending fees are worth at least this much. */+export function minBatchAtomics() {+ return usdToUsdcAtomics(num('FEE_BRIDGE_MIN_BATCH_USD', 5, { min: 0.5, max: 10_000 }));+}++export function slippageBps() {+ return Math.round(num('FEE_BRIDGE_SLIPPAGE_BPS', 100, { min: 10, max: 500 }));+}++/** SOL the bridge keeps back for gas and rent; never swapped. */+export function gasReserveLamports() {+ return BigInt(Math.round(num('FEE_BRIDGE_GAS_RESERVE_SOL', 0.03, { min: 0.005, max: 5 }) * 1e9));+}++/** Minutes between cranks of the same coin. */+export function crankIntervalMinutes() {+ return Math.round(num('FEE_BRIDGE_CRANK_INTERVAL_MIN', 30, { min: 5, max: 1440 }));+}++export function crankPerTick() {+ return Math.round(num('FEE_BRIDGE_CRANK_PER_TICK', 10, { min: 1, max: 50 }));+}++export function payoutsPerTick() {+ return Math.round(num('FEE_BRIDGE_PAYOUTS_PER_TICK', 10, { min: 1, max: 50 }));+}++export const SIGNER_SPEC = /** @type {any} */ (SOLANA_SIGNERS.find((s) => s.name === 'fee-bridge'));++let _pubkey;+/** Bridge wallet address, or null when the signer is not configured. */+export async function bridgeAddress() {+ if (_pubkey !== undefined) return _pubkey;+ const r = await resolveSignerPubkey(SIGNER_SPEC);+ _pubkey = r.pubkey;+ return _pubkey;+}++/** Bridge keypair; throws a typed 503 when unconfigured so callers render cleanly. */+export async function loadBridgeSigner() {+ const r = await loadSignerKeypair(SIGNER_SPEC);+ if (!r.keypair) {+ throw Object.assign(+ new Error(+ r.decodeError+ ? `${SIGNER_SPEC.env} is set but does not decode to a Solana keypair`+ : `${SIGNER_SPEC.env} is not configured`,+ ),+ { status: 503, code: 'fee_bridge_unconfigured' },+ );+ }+ return r.keypair;+}++export function publicConfig(address) {+ const bps = recipientBps();+ return {+ enabled: isEnabled() && !!address,+ bridge_wallet: address,+ recipient_bps: bps,+ buyback_bps: 10_000 - bps,+ auto_payout_usd: Number(autoPayoutAtomics()) / 1e6,+ withdraw_min_usd: Number(withdrawMinAtomics()) / 1e6,+ payout_asset: { symbol: 'USDC', chain: 'solana', mint: USDC_MINT },+ buyback_asset: { symbol: '$THREE', chain: 'solana', mint: THREE_MINT },+ supported_quotes: ['SOL', 'USDC'],+ };+}diff --git a/api/_lib/fee-bridge/engine.js b/api/_lib/fee-bridge/engine.jsnew file mode 100644index 000000000..54097adde--- /dev/null+++ b/api/_lib/fee-bridge/engine.js@@ -0,0 +1,592 @@+// @ts-check+// The Fee Bridge engine. One tick (api/cron/fee-bridge.js) runs, in order:+//+// 1. settle : resolve every crank and payout sent by an earlier tick.+// 2. crank : distribute each registered coin's accrued creator fees into the+// bridge wallet, recording what landed per coin.+// 3. convert : advance one batch claimed -> swapped (SOL to USDC on Jupiter)+// -> bought ($THREE with the buyback share) -> swept (the $THREE+// to the treasury) -> credited (USDC credited to each handle).+// 4. payout : send USDC to every linked recipient past the auto-payout floor.+//+// Every broadcast is persisted first (see chain.js), so each step is resumable+// and nothing is ever sent twice. $THREE bought here goes to the treasury; the+// platform never burns supply (api/_lib/token/config.js economy policy).++import { sql } from '../db.js';+import { logger } from '../usage.js';+import { jupiterQuote, jupiterSwapTx } from '../token/jupiter.js';+import { treasuryWallet } from '../token/config.js';+import { TOKEN_DECIMALS } from '../token/config.js';+import {+ NATIVE_SOL_MINT,+ USDC_MINT,+ THREE_MINT,+ isEnabled,+ recipientBps,+ autoPayoutAtomics,+ withdrawMinAtomics,+ minBatchAtomics,+ slippageBps,+ gasReserveLamports,+ crankIntervalMinutes,+ crankPerTick,+ payoutsPerTick,+ bridgeAddress,+ loadBridgeSigner,+} from './config.js';+import {+ broadcast,+ buildSigned,+ landedMeta,+ lamports,+ planDistribution,+ readSharingState,+ resolveTracked,+ routesOnlyTo,+ signPrebuilt,+ splBalance,+ splTransferInstructions,+} from './chain.js';+import { computeBatchCredits, lamportDelta, netOfGas, parseXHandle, payoutDecision, tokenDelta } from './math.js';+import { handleBalance, handlesAtOrAbove, resolveClaimant, solanaWallets } from './ledger.js';++const log = logger('fee-bridge');+const USDC_DECIMALS = 6;+const big = (v) => BigInt(v ?? 0);+const fail = (status, code, message) => Object.assign(new Error(message), { status, code });++// ── registration ────────────────────────────────────────────────────────────++/**+ * Register a coin whose creator fees already route 100% to the bridge. The route is+ * read from chain, never trusted from the caller, and the caller must control the+ * coin: either it launched it through a three.ws agent, or the fee-sharing admin+ * wallet is one of its linked wallets.+ *+ * @param {{ userId: string, mint: string, handle: string }} args+ */+export async function registerCoin({ userId, mint, handle }) {+ const bridge = await bridgeAddress();+ if (!bridge) throw fail(503, 'fee_bridge_unconfigured', 'The Fee Bridge is not configured on this deployment.');+ const clean = parseXHandle(handle);+ if (!clean) throw fail(400, 'invalid_handle', 'Enter a valid X handle (letters, digits, underscore; up to 15 characters).');++ const state = await readSharingState(mint);+ if (!state.exists) throw fail(404, 'coin_not_found', 'No pump.fun coin exists at that mint.');+ if (!state.supportedQuote) throw fail(422, 'unsupported_quote', 'The Fee Bridge supports coins quoted in SOL or USDC.');+ if (!routesOnlyTo(state, bridge)) {+ throw fail(+ 409,+ 'not_routed',+ `This coin's creator fees do not route 100% to the Fee Bridge wallet (${bridge}) yet. Save that split on chain first.`,+ );+ }++ const [launched] = await sql`+ select agent_id from pump_agent_mints+ where mint = ${mint} and network = 'mainnet' and user_id = ${userId}+ limit 1+ `;+ const [adminLinked] = state.admin+ ? await sql`select 1 as ok from user_wallets where user_id = ${userId} and address = ${state.admin} limit 1`+ : [];+ if (!launched && !adminLinked) {+ throw fail(403, 'not_coin_owner', 'Only the account that launched this coin, or that holds its fee-sharing admin wallet, can register it.');+ }++ const [existing] = await sql`select handle, handle_lc from fee_bridge_coins where mint = ${mint}`;+ if (existing && existing.handle_lc !== clean.toLowerCase()) {+ throw fail(409, 'handle_locked', `This coin already pays @${existing.handle}. A coin's recipient cannot be changed once fees are credited to it.`);+ }++ const [row] = await sql`+ insert into fee_bridge_coins (mint, handle, handle_lc, quote_mint, registered_by, agent_id, admin_wallet, status)+ values (${mint}, ${clean}, ${clean.toLowerCase()}, ${state.quoteMint}, ${userId}, ${launched?.agent_id ?? null}, ${state.admin}, 'active')+ on conflict (mint) do update set status = 'active', admin_wallet = excluded.admin_wallet, updated_at = now()+ returning mint, handle, quote_mint, created_at, (xmax = 0) as inserted+ `;+ log.info('coin registered', { mint, handle: clean, inserted: row.inserted });+ return {+ mint: row.mint,+ handle: row.handle,+ quote: row.quote_mint === NATIVE_SOL_MINT ? 'SOL' : 'USDC',+ registered_at: row.created_at,+ created: !!row.inserted,+ admin_revoked: state.adminRevoked,+ };+}++// ── settle ──────────────────────────────────────────────────────────────────++async function settleInflows(bridge) {+ const rows = await sql`+ select id, mint, quote_mint, signature, blockhash from fee_bridge_inflows+ where status = 'sent' order by created_at limit 25+ `;+ let landed = 0;+ for (const r of rows) {+ const outcome = await resolveTracked(r.signature, r.blockhash);+ if (outcome === 'pending') continue;+ if (outcome === 'dropped' || outcome === 'reverted') {+ await sql`update fee_bridge_inflows set status = 'dropped' where id = ${r.id} and status = 'sent'`;+ continue;+ }+ const { meta, accountKeys } = await landedMeta(r.signature);+ const idx = accountKeys.indexOf(bridge);+ const fee = big(meta.fee);+ let amount;+ let gas;+ if (r.quote_mint === NATIVE_SOL_MINT) {+ amount = lamportDelta(meta, idx, idx === 0);+ gas = fee;+ } else {+ amount = tokenDelta(meta, bridge, r.quote_mint);+ gas = -lamportDelta(meta, idx, false);+ }+ await sql`+ update fee_bridge_inflows+ set status = 'landed', amount_raw = ${(amount > 0n ? amount : 0n).toString()},+ gas_lamports = ${(gas > 0n ? gas : 0n).toString()}, landed_at = now()+ where id = ${r.id} and status = 'sent'+ `;+ landed++;+ }+ return { checked: rows.length, landed };+}++async function settlePayouts() {+ const rows = await sql`+ select id, signature, blockhash from fee_bridge_payouts+ where status = 'pending' and signature is not null order by created_at limit 25+ `;+ let confirmed = 0;+ for (const r of rows) {+ const outcome = await resolveTracked(r.signature, r.blockhash);+ if (outcome === 'landed') {+ await sql`update fee_bridge_payouts set status = 'confirmed', confirmed_at = now() where id = ${r.id} and status = 'pending'`;+ confirmed++;+ } else if (outcome === 'dropped' || outcome === 'reverted') {+ await sql`update fee_bridge_payouts set status = 'failed', error = ${`transaction ${outcome}`} where id = ${r.id} and status = 'pending'`;+ }+ }+ // A payout row that never got as far as a signature died before broadcast.+ await sql`+ update fee_bridge_payouts set status = 'failed', error = 'interrupted before broadcast'+ where status = 'pending' and signature is null and created_at < now() - interval '5 minutes'+ `;+ return { checked: rows.length, confirmed };+}++// ── crank ───────────────────────────────────────────────────────────────────++async function crankCoins(signer, bridge, { dryRun, deadline }) {+ const due = await sql`+ select mint, quote_mint from fee_bridge_coins+ where status = 'active'+ and (last_crank_at is null or last_crank_at < now() - make_interval(mins => ${crankIntervalMinutes()}))+ and not exists (select 1 from fee_bridge_inflows i where i.mint = fee_bridge_coins.mint and i.status = 'sent')+ order by last_crank_at nulls first+ limit ${crankPerTick()}+ `;+ const results = [];+ for (const coin of due) {+ if (Date.now() > deadline) break;+ try {+ const state = await readSharingState(coin.mint);+ if (!routesOnlyTo(state, bridge)) {+ if (!dryRun) {+ await sql`update fee_bridge_coins set status = 'unrouted', last_error = 'fees no longer route 100% to the bridge', updated_at = now() where mint = ${coin.mint}`;+ }+ results.push({ mint: coin.mint, outcome: 'unrouted' });+ continue;+ }+ const plan = await planDistribution(coin.mint, coin.quote_mint, signer.publicKey);+ if (!plan.canDistribute || dryRun) {+ if (!dryRun) await sql`update fee_bridge_coins set last_crank_at = now(), last_error = null where mint = ${coin.mint}`;+ results.push({ mint: coin.mint, outcome: plan.canDistribute ? 'would_distribute' : 'below_minimum', distributable: plan.distributable.toString() });+ continue;+ }+ const { tx, signature, blockhash } = await buildSigned(signer, plan.instructions);+ await sql`+ insert into fee_bridge_inflows (mint, quote_mint, signature, blockhash)+ values (${coin.mint}, ${coin.quote_mint}, ${signature}, ${blockhash})+ `;+ await sql`update fee_bridge_coins set last_crank_at = now(), last_error = null where mint = ${coin.mint}`;+ await broadcast(tx, signature).catch((e) => log.warn('crank broadcast unresolved', { mint: coin.mint, signature, err: e?.message }));+ results.push({ mint: coin.mint, outcome: 'sent', signature });+ } catch (e) {+ log.warn('crank failed', { mint: coin.mint, err: e?.message });+ if (!dryRun) {+ await sql`update fee_bridge_coins set last_crank_at = now(), last_error = ${String(e?.message || e).slice(0, 500)} where mint = ${coin.mint}`;+ }+ results.push({ mint: coin.mint, outcome: 'error', error: e?.message });+ }+ }+ return results;+}++// ── convert ─────────────────────────────────────────────────────────────────++/** Per-coin inputs of a batch, deterministic from its rows (so a resumed credit recomputes identically). */+async function batchCoins(batchId, usdcFromSol, solNet) {+ const rows = await sql`+ select i.mint, c.handle_lc, i.quote_mint,+ sum(i.amount_raw)::text as amount, sum(i.gas_lamports)::text as gas+ from fee_bridge_inflows i join fee_bridge_coins c on c.mint = i.mint+ where i.batch_id = ${batchId}+ group by i.mint, c.handle_lc, i.quote_mint+ order by i.mint+ `;+ return rows.map((r) => {+ const amount = big(r.amount);+ const gas = big(r.gas);+ if (r.quote_mint === NATIVE_SOL_MINT) {+ return { mint: r.mint, handle_lc: r.handle_lc, sol_net: netOfGas(amount, gas), usdc_in: 0n };+ }+ // A USDC-quoted coin's gas was paid in SOL: charge it back at this batch's own+ // SOL->USDC rate when the batch swapped SOL, otherwise the bridge absorbs it.+ const gasUsdc = solNet > 0n ? (gas * usdcFromSol) / solNet : 0n;+ return { mint: r.mint, handle_lc: r.handle_lc, sol_net: 0n, usdc_in: netOfGas(amount, gasUsdc) };+ });+}++async function openBatch(signer, { dryRun }) {+ const pending = await sql`+ select i.id, i.quote_mint, i.amount_raw::text as amount, i.gas_lamports::text as gas+ from fee_bridge_inflows i+ where i.status = 'landed' and i.batch_id is null+ order by i.created_at limit 500+ `;+ if (!pending.length) return { outcome: 'nothing_pending' };++ let solNet = 0n;+ let usdcIn = 0n;+ for (const p of pending) {+ if (p.quote_mint === NATIVE_SOL_MINT) solNet += netOfGas(big(p.amount), big(p.gas));+ else usdcIn += big(p.amount);+ }++ let quotedUsdc = 0n;+ if (solNet > 0n) {+ const q = await jupiterQuote({ inputMint: NATIVE_SOL_MINT, outputMint: USDC_MINT, amount: solNet, slippageBps: slippageBps() });+ quotedUsdc = big(q.outAmount);+ }+ const worth = quotedUsdc + usdcIn;+ if (worth < minBatchAtomics()) {+ return { outcome: 'below_batch_floor', worth_usdc_atomics: worth.toString(), floor_usdc_atomics: minBatchAtomics().toString() };+ }++ const bridge = signer.publicKey.toBase58();+ const [sol, usdc] = await Promise.all([lamports(bridge), splBalance(bridge, USDC_MINT)]);+ if (sol < solNet + gasReserveLamports()) {+ return { outcome: 'awaiting_gas', sol_lamports: sol.toString(), need_lamports: (solNet + gasReserveLamports()).toString() };+ }+ if (usdc < usdcIn) {+ log.error('bridge USDC below recorded USDC inflows', { usdc: usdc.toString(), usdcIn: usdcIn.toString() });+ return { outcome: 'usdc_mismatch' };+ }+ if (dryRun) return { outcome: 'would_convert', inflows: pending.length, sol_net_lamports: solNet.toString(), usdc_in_atomics: usdcIn.toString(), quoted_usdc_atomics: quotedUsdc.toString() };++ let batch;+ try {+ [batch] = await sql`+ insert into fee_bridge_batches (stage, sol_net_lamports, usdc_in_atomics)+ values ('claimed', ${solNet.toString()}, ${usdcIn.toString()})+ returning *+ `;+ } catch (e) {+ if (String(e?.code) === '23505') return { outcome: 'batch_in_flight' };+ throw e;+ }+ const ids = pending.map((p) => p.id);+ await sql`update fee_bridge_inflows set batch_id = ${batch.id} where id = any(${ids}::uuid[]) and batch_id is null`;+ return { outcome: 'opened', batch };+}++async function swapSolToUsdc(signer, batch) {+ const solNet = big(batch.sol_net_lamports);+ if (solNet === 0n) {+ const [b] = await sql`update fee_bridge_batches set stage = 'swapped', updated_at = now() where id = ${batch.id} and stage = 'claimed' returning *`;+ return b;+ }+ if (batch.swap_sig) {+ const outcome = await resolveTracked(batch.swap_sig, batch.swap_blockhash);+ if (outcome === 'pending') return null;+ if (outcome === 'landed') {+ const { meta } = await landedMeta(batch.swap_sig);+ const got = tokenDelta(meta, signer.publicKey.toBase58(), USDC_MINT);+ const [b] = await sql`+ update fee_bridge_batches set stage = 'swapped', usdc_from_sol_atomics = ${(got > 0n ? got : 0n).toString()}, updated_at = now()+ where id = ${batch.id} and stage = 'claimed' returning *+ `;+ return b;+ }+ await sql`update fee_bridge_batches set swap_sig = null, swap_blockhash = null, error = ${`swap ${outcome}, retrying`}, updated_at = now() where id = ${batch.id}`;+ return null;+ }+ const quote = await jupiterQuote({ inputMint: NATIVE_SOL_MINT, outputMint: USDC_MINT, amount: solNet, slippageBps: slippageBps() });+ const b64 = await jupiterSwapTx({ quote, userPublicKey: signer.publicKey.toBase58(), wrapAndUnwrapSol: true });+ const { tx, signature, blockhash } = signPrebuilt(signer, b64);+ await sql`update fee_bridge_batches set swap_sig = ${signature}, swap_blockhash = ${blockhash}, updated_at = now() where id = ${batch.id}`;+ await broadcast(tx, signature);+ const [fresh] = await sql`select * from fee_bridge_batches where id = ${batch.id}`;+ return swapSolToUsdc(signer, fresh);+}++async function buyThree(signer, batch) {+ // Fix the split the first time this stage runs, from the batch's own rows.+ if (big(batch.recipient_usdc_atomics) === 0n && big(batch.buyback_usdc_atomics) === 0n) {+ const coins = await batchCoins(batch.id, big(batch.usdc_from_sol_atomics), big(batch.sol_net_lamports));+ const { recipientTotal, buybackTotal } = computeBatchCredits({ coins, usdcFromSol: big(batch.usdc_from_sol_atomics), recipientBps: recipientBps() });+ [batch] = await sql`+ update fee_bridge_batches set recipient_usdc_atomics = ${recipientTotal.toString()}, buyback_usdc_atomics = ${buybackTotal.toString()}, updated_at = now()+ where id = ${batch.id} returning *+ `;+ }+ const spend = big(batch.buyback_usdc_atomics);+ if (spend === 0n) {+ const [b] = await sql`update fee_bridge_batches set stage = 'swept', updated_at = now() where id = ${batch.id} and stage = 'swapped' returning *`;+ return b;+ }+ if (batch.buy_sig) {+ const outcome = await resolveTracked(batch.buy_sig, batch.buy_blockhash);+ if (outcome === 'pending') return null;+ if (outcome === 'landed') {+ const { meta } = await landedMeta(batch.buy_sig);+ const got = tokenDelta(meta, signer.publicKey.toBase58(), THREE_MINT);+ const [b] = await sql`+ update fee_bridge_batches set stage = 'bought', three_bought_atomics = ${(got > 0n ? got : 0n).toString()}, updated_at = now()+ where id = ${batch.id} and stage = 'swapped' returning *+ `;+ return b;+ }+ await sql`update fee_bridge_batches set buy_sig = null, buy_blockhash = null, error = ${`buyback ${outcome}, retrying`}, updated_at = now() where id = ${batch.id}`;+ return null;+ }+ const quote = await jupiterQuote({ inputMint: USDC_MINT, outputMint: THREE_MINT, amount: spend, slippageBps: slippageBps() });+ const b64 = await jupiterSwapTx({ quote, userPublicKey: signer.publicKey.toBase58() });+ const { tx, signature, blockhash } = signPrebuilt(signer, b64);+ await sql`update fee_bridge_batches set buy_sig = ${signature}, buy_blockhash = ${blockhash}, updated_at = now() where id = ${batch.id}`;+ await broadcast(tx, signature);+ const [fresh] = await sql`select * from fee_bridge_batches where id = ${batch.id}`;+ return buyThree(signer, fresh);+}++async function sweepThree(signer, batch) {+ const amount = big(batch.three_bought_atomics);+ const treasury = treasuryWallet();+ if (amount === 0n || treasury === signer.publicKey.toBase58()) {+ const [b] = await sql`update fee_bridge_batches set stage = 'swept', updated_at = now() where id = ${batch.id} and stage = 'bought' returning *`;+ return b;+ }+ if (batch.sweep_sig) {+ const outcome = await resolveTracked(batch.sweep_sig, batch.sweep_blockhash);+ if (outcome === 'pending') return null;+ if (outcome === 'landed') {+ const [b] = await sql`update fee_bridge_batches set stage = 'swept', updated_at = now() where id = ${batch.id} and stage = 'bought' returning *`;+ return b;+ }+ await sql`update fee_bridge_batches set sweep_sig = null, sweep_blockhash = null, error = ${`sweep ${outcome}, retrying`}, updated_at = now() where id = ${batch.id}`;+ return null;+ }+ const ixs = await splTransferInstructions({+ from: signer.publicKey,+ to: treasury,+ mint: THREE_MINT,+ decimals: TOKEN_DECIMALS,+ amount,+ memo: `three.ws fee bridge buyback to treasury (batch ${batch.id})`,+ });+ const { tx, signature, blockhash } = await buildSigned(signer, ixs);+ await sql`update fee_bridge_batches set sweep_sig = ${signature}, sweep_blockhash = ${blockhash}, updated_at = now() where id = ${batch.id}`;+ await broadcast(tx, signature);+ const [fresh] = await sql`select * from fee_bridge_batches where id = ${batch.id}`;+ return sweepThree(signer, fresh);+}++async function creditBatch(batch) {+ const usdcFromSol = big(batch.usdc_from_sol_atomics);+ const coins = await batchCoins(batch.id, usdcFromSol, big(batch.sol_net_lamports));+ const { credits } = computeBatchCredits({ coins, usdcFromSol, recipientBps: recipientBps() });+ for (const c of credits) {+ await sql`+ insert into fee_bridge_credits (batch_id, mint, handle_lc, usdc_atomics)+ values (${batch.id}, ${c.mint}, ${c.handle_lc}, ${c.usdc_atomics.toString()})+ on conflict (batch_id, mint) do nothing+ `;+ }+ const [b] = await sql`+ update fee_bridge_batches set stage = 'credited', error = null, completed_at = now(), updated_at = now()+ where id = ${batch.id} and stage = 'swept' returning *+ `;+ return b;+}++async function convert(signer, { dryRun, deadline }) {+ let [batch] = await sql`+ select * from fee_bridge_batches where stage in ('claimed', 'swapped', 'bought', 'swept') order by created_at limit 1+ `;+ if (!batch) {+ const opened = await openBatch(signer, { dryRun });+ if (opened.outcome !== 'opened') return opened;+ batch = opened.batch;+ } else if (dryRun) {+ return { outcome: 'would_resume', batch_id: batch.id, stage: batch.stage };+ }++ const steps = { claimed: swapSolToUsdc, swapped: buyThree, bought: sweepThree, swept: (_s, b) => creditBatch(b) };+ while (batch && batch.stage !== 'credited' && Date.now() < deadline) {+ const step = steps[batch.stage];+ try {+ const next = await step(signer, batch);+ if (!next) return { outcome: 'waiting', batch_id: batch.id, stage: batch.stage };+ batch = next;+ } catch (e) {+ await sql`update fee_bridge_batches set error = ${String(e?.message || e).slice(0, 500)}, updated_at = now() where id = ${batch.id}`;+ log.warn('conversion step failed', { batch: batch.id, stage: batch.stage, err: e?.message });+ return { outcome: 'step_error', batch_id: batch.id, stage: batch.stage, error: e?.message };+ }+ }+ return { outcome: batch?.stage === 'credited' ? 'credited' : 'paused', batch_id: batch?.id, stage: batch?.stage };+}++// ── payout ──────────────────────────────────────────────────────────────────++/**+ * Pay a handle's unpaid USDC to its owner's wallet.+ * @param {object} args+ * @param {import('@solana/web3.js').Keypair} args.signer+ * @param {{ handleLc: string, handle: string, xUserId: string, userId: string }} args.claimant+ * @param {'auto'|'withdraw'} args.trigger+ * @param {string} [args.wallet] a specific linked wallet; defaults to the primary+ */+export async function payClaimant({ signer, claimant, trigger, wallet }) {+ const wallets = await solanaWallets(claimant.userId);+ if (!wallets.length) throw fail(409, 'no_wallet', 'Link a Solana wallet to your three.ws account to receive payouts.');+ const dest = wallet ? wallets.find((w) => w.address === wallet)?.address : wallets[0].address;+ if (!dest) throw fail(400, 'wallet_not_linked', 'That wallet is not linked to your account.');++ const { unpaid } = await handleBalance(claimant.handleLc);+ const decision = payoutDecision({ balance: unpaid, trigger, autoFloor: autoPayoutAtomics(), withdrawFloor: withdrawMinAtomics() });+ if (!decision.pay) {+ throw fail(409, decision.reason, decision.reason === 'no_balance' ? 'There is nothing to withdraw yet.' : `Withdrawals start at $${(Number(decision.floor) / 1e6).toFixed(2)}.`);+ }+ const amount = /** @type {bigint} */ (decision.amount);+ const float = await splBalance(signer.publicKey.toBase58(), USDC_MINT);+ if (float < amount) {+ log.error('bridge USDC float below a credited balance', { handle: claimant.handleLc, amount: amount.toString(), float: float.toString() });+ throw fail(503, 'float_short', 'Payouts are briefly paused while the bridge settles. Try again shortly.');+ }++ // Bind the handle to this X account on its first payout.+ await sql`+ insert into fee_bridge_recipients (handle_lc, handle, x_user_id, user_id)+ values (${claimant.handleLc}, ${claimant.handle}, ${claimant.xUserId}, ${claimant.userId})+ on conflict (handle_lc) do nothing+ `;++ // The balance check and the insert are one statement, and the partial unique+ // index allows one pending payout per handle, so concurrent requests cannot+ // both spend the same balance.+ let payout;+ try {+ [payout] = await sql`+ insert into fee_bridge_payouts (handle_lc, user_id, wallet, usdc_atomics, trigger)+ select ${claimant.handleLc}, ${claimant.userId}, ${dest}, ${amount.toString()}::numeric, ${trigger}+ where (+ (select coalesce(sum(usdc_atomics), 0) from fee_bridge_credits where handle_lc = ${claimant.handleLc})+ - (select coalesce(sum(usdc_atomics), 0) from fee_bridge_payouts where handle_lc = ${claimant.handleLc} and status in ('pending', 'confirmed'))+ ) >= ${amount.toString()}::numeric+ returning id+ `;+ } catch (e) {+ if (String(e?.code) === '23505') throw fail(409, 'payout_in_flight', 'A payout for this account is already on its way.');+ throw e;+ }+ if (!payout) throw fail(409, 'balance_changed', 'Your balance changed. Refresh and try again.');++ try {+ const ixs = await splTransferInstructions({+ from: signer.publicKey,+ to: dest,+ mint: USDC_MINT,+ decimals: USDC_DECIMALS,+ amount,+ memo: `three.ws fee bridge payout to @${claimant.handle}`,+ });+ const { tx, signature, blockhash } = await buildSigned(signer, ixs);+ await sql`update fee_bridge_payouts set signature = ${signature}, blockhash = ${blockhash} where id = ${payout.id}`;+ try {+ await broadcast(tx, signature);+ await sql`update fee_bridge_payouts set status = 'confirmed', confirmed_at = now() where id = ${payout.id} and status = 'pending'`;+ return { id: payout.id, status: 'confirmed', signature, wallet: dest, usdc_atomics: amount.toString() };+ } catch (e) {+ // Sent but unconfirmed: the settle step resolves it from chain.+ log.warn('payout unconfirmed', { id: payout.id, signature, err: e?.message });+ if (e?.code === 'tx_reverted') {+ await sql`update fee_bridge_payouts set status = 'failed', error = ${String(e.message).slice(0, 500)} where id = ${payout.id} and status = 'pending'`;+ throw fail(502, 'payout_reverted', 'The payout transaction failed on chain. Your balance is unchanged; try again.');+ }+ return { id: payout.id, status: 'pending', signature, wallet: dest, usdc_atomics: amount.toString() };+ }+ } catch (e) {+ if (e?.status) throw e;+ await sql`update fee_bridge_payouts set status = 'failed', error = ${String(e?.message || e).slice(0, 500)} where id = ${payout.id} and status = 'pending' and signature is null`;+ throw fail(502, 'payout_failed', 'The payout could not be sent. Your balance is unchanged; try again.');+ }+}++async function autoPayouts(signer, { dryRun, deadline }) {+ const due = await handlesAtOrAbove(autoPayoutAtomics(), payoutsPerTick());+ const results = [];+ for (const d of due) {+ if (Date.now() > deadline) break;+ const claimant = await resolveClaimant({ handleLc: d.handleLc });+ if (!claimant) {+ results.push({ handle: d.handleLc, outcome: 'unclaimed' });+ continue;+ }+ const wallets = await solanaWallets(claimant.userId);+ if (!wallets.length) {+ results.push({ handle: d.handleLc, outcome: 'no_wallet' });+ continue;+ }+ if (dryRun) {+ results.push({ handle: d.handleLc, outcome: 'would_pay', usdc_atomics: d.unpaid.toString(), wallet: wallets[0].address });+ continue;+ }+ try {+ const r = await payClaimant({ signer, claimant, trigger: 'auto' });+ results.push({ handle: d.handleLc, outcome: r.status, signature: r.signature, usdc_atomics: r.usdc_atomics });+ } catch (e) {+ results.push({ handle: d.handleLc, outcome: 'error', error: e?.code || e?.message });+ }+ }+ return results;+}++// ── tick ────────────────────────────────────────────────────────────────────++/**+ * One full engine pass. `dryRun` reads chain and DB and reports what it would do+ * without signing anything.+ * @param {{ dryRun?: boolean, budgetMs?: number }} [opts]+ */+export async function runTick({ dryRun = false, budgetMs = 50_000 } = {}) {+ const deadline = Date.now() + budgetMs;+ if (!isEnabled() && !dryRun) return { ok: true, skipped: 'disabled' };+ const bridge = await bridgeAddress();+ if (!bridge) return { ok: true, skipped: 'signer_unconfigured' };+ const signer = dryRun ? { publicKey: new (await import('@solana/web3.js')).PublicKey(bridge) } : await loadBridgeSigner();++ const out = { ok: true, dry_run: dryRun, bridge };+ if (!dryRun) {+ out.settled_inflows = await settleInflows(bridge);+ out.settled_payouts = await settlePayouts();+ }+ out.cranks = await crankCoins(signer, bridge, { dryRun, deadline });+ out.conversion = Date.now() < deadline ? await convert(signer, { dryRun, deadline }) : { outcome: 'out_of_time' };+ out.payouts = Date.now() < deadline ? await autoPayouts(signer, { dryRun, deadline }) : [];+ return out;+}diff --git a/api/_lib/fee-bridge/ledger.js b/api/_lib/fee-bridge/ledger.jsnew file mode 100644index 000000000..881e1eece--- /dev/null+++ b/api/_lib/fee-bridge/ledger.js@@ -0,0 +1,182 @@+// @ts-check+// Fee Bridge ledger reads: balances, recipient identity, and the public numbers.+//+// A handle's unpaid balance is always derived, never stored: everything credited+// to it minus every pending or confirmed payout. There is no running total that+// can drift from the rows that justify it.++import { sql } from '../db.js';++const big = (v) => BigInt(v ?? 0);++/** Credited, paid, and unpaid USDC atomics for one handle. */+export async function handleBalance(handleLc) {+ const [row] = await sql`+ select+ (select coalesce(sum(usdc_atomics), 0)::text from fee_bridge_credits where handle_lc = ${handleLc}) as credited,+ (select coalesce(sum(usdc_atomics), 0)::text from fee_bridge_payouts+ where handle_lc = ${handleLc} and status in ('pending', 'confirmed')) as paid,+ (select coalesce(sum(usdc_atomics), 0)::text from fee_bridge_payouts+ where handle_lc = ${handleLc} and status = 'pending') as in_flight+ `;+ const credited = big(row?.credited);+ const paid = big(row?.paid);+ return { credited, paid, inFlight: big(row?.in_flight), unpaid: credited - paid };+}++/**+ * The X account allowed to withdraw a handle's balance, from a user's live X+ * connection. A handle already bound to an X account id only ever pays that id+ * (so a renamed-then-reclaimed handle cannot be claimed by its new owner); an+ * unbound handle is claimed by whoever holds it on X right now.+ *+ * @param {{ userId?: string, handleLc?: string }} q userId for a withdrawal,+ * handleLc for an automatic payout+ * @returns {Promise<{ handleLc: string, handle: string, xUserId: string, userId: string }|null>}+ */+export async function resolveClaimant({ userId, handleLc }) {+ if (userId) {+ const [conn] = await sql`+ select user_id, provider_uid, username from social_connections+ where user_id = ${userId} and provider = 'x' and disconnected_at is null+ limit 1+ `;+ if (!conn?.provider_uid || !conn.username) return null;+ const [bound] = await sql`+ select handle_lc, handle from fee_bridge_recipients where x_user_id = ${conn.provider_uid} limit 1+ `;+ if (bound) return { handleLc: bound.handle_lc, handle: bound.handle, xUserId: conn.provider_uid, userId: conn.user_id };+ const lc = String(conn.username).toLowerCase();+ const [taken] = await sql`select x_user_id from fee_bridge_recipients where handle_lc = ${lc} limit 1`;+ if (taken && taken.x_user_id !== conn.provider_uid) return null;+ return { handleLc: lc, handle: conn.username, xUserId: conn.provider_uid, userId: conn.user_id };+ }++ const lc = String(handleLc || '').toLowerCase();+ if (!lc) return null;+ const [bound] = await sql`select x_user_id, handle from fee_bridge_recipients where handle_lc = ${lc} limit 1`;+ const [conn] = bound+ ? await sql`+ select user_id, provider_uid, username from social_connections+ where provider = 'x' and provider_uid = ${bound.x_user_id} and disconnected_at is null+ order by updated_at desc nulls last limit 1+ `+ : await sql`+ select user_id, provider_uid, username from social_connections+ where provider = 'x' and lower(username) = ${lc} and disconnected_at is null+ order by updated_at desc nulls last limit 1+ `;+ if (!conn?.provider_uid) return null;+ return { handleLc: lc, handle: bound?.handle || conn.username, xUserId: conn.provider_uid, userId: conn.user_id };+}++/** A user's Solana wallets, primary first. */+export async function solanaWallets(userId) {+ const rows = await sql`+ select address, is_primary from user_wallets+ where user_id = ${userId} and chain_type = 'solana'+ order by is_primary desc, created_at asc+ `;+ return rows.map((r) => ({ address: r.address, primary: !!r.is_primary }));+}++/** Handles whose unpaid balance has reached `floor`, largest first. */+export async function handlesAtOrAbove(floor, limit) {+ const rows = await sql`+ with credited as (+ select handle_lc, sum(usdc_atomics) as amt from fee_bridge_credits group by handle_lc+ ), paid as (+ select handle_lc, sum(usdc_atomics) as amt from fee_bridge_payouts+ where status in ('pending', 'confirmed') group by handle_lc+ )+ select c.handle_lc, (c.amt - coalesce(p.amt, 0))::text as unpaid+ from credited c left join paid p using (handle_lc)+ where c.amt - coalesce(p.amt, 0) >= ${floor.toString()}::numeric+ and not exists (select 1 from fee_bridge_payouts x where x.handle_lc = c.handle_lc and x.status = 'pending')+ order by c.amt - coalesce(p.amt, 0) desc+ limit ${limit}+ `;+ return rows.map((r) => ({ handleLc: r.handle_lc, unpaid: big(r.unpaid) }));+}++/** Public totals for /fee-bridge. */+export async function publicStats() {+ const [row] = await sql`+ select+ (select count(*)::int from fee_bridge_coins where status = 'active') as coins,+ (select count(distinct handle_lc)::int from fee_bridge_coins) as handles,+ (select coalesce(sum(usdc_atomics), 0)::text from fee_bridge_credits) as credited,+ (select coalesce(sum(usdc_atomics), 0)::text from fee_bridge_payouts where status = 'confirmed') as paid,+ (select coalesce(sum(buyback_usdc_atomics), 0)::text from fee_bridge_batches where stage = 'credited') as buyback_usdc,+ (select coalesce(sum(three_bought_atomics), 0)::text from fee_bridge_batches where stage = 'credited') as three_bought,+ (select count(*)::int from fee_bridge_payouts where status = 'confirmed') as payouts+ `;+ const credited = big(row?.credited);+ const paid = big(row?.paid);+ return {+ coins: row?.coins ?? 0,+ handles: row?.handles ?? 0,+ payouts: row?.payouts ?? 0,+ credited_usdc_atomics: credited.toString(),+ paid_usdc_atomics: paid.toString(),+ unpaid_usdc_atomics: (credited - paid).toString(),+ buyback_usdc_atomics: big(row?.buyback_usdc).toString(),+ three_bought_atomics: big(row?.three_bought).toString(),+ };+}++/** Newest confirmed payouts, for the public ledger. */+export async function recentPayouts(limit = 20) {+ const rows = await sql`+ select p.id, coalesce(r.handle, p.handle_lc) as handle, p.usdc_atomics::text as usdc_atomics,+ p.signature, p.trigger, p.confirmed_at+ from fee_bridge_payouts p+ left join fee_bridge_recipients r on r.handle_lc = p.handle_lc+ where p.status = 'confirmed'+ order by p.confirmed_at desc+ limit ${limit}+ `;+ return rows.map((r) => ({+ id: r.id,+ handle: r.handle,+ usdc_atomics: r.usdc_atomics,+ signature: r.signature,+ trigger: r.trigger,+ confirmed_at: r.confirmed_at,+ }));+}++/** Registered coins with what each has earned its handle, newest first. */+export async function listCoins({ limit = 50, handleLc = null } = {}) {+ const rows = await sql`+ select c.mint, c.handle, c.handle_lc, c.status, c.quote_mint, c.created_at, c.last_crank_at,+ m.name, m.symbol,+ coalesce((select sum(usdc_atomics) from fee_bridge_credits k where k.mint = c.mint), 0)::text as credited+ from fee_bridge_coins c+ left join pump_agent_mints m on m.mint = c.mint and m.network = 'mainnet'+ where (${handleLc}::text is null or c.handle_lc = ${handleLc})+ order by c.created_at desc+ limit ${limit}+ `;+ return rows.map((r) => ({+ mint: r.mint,+ handle: r.handle,+ status: r.status,+ quote: r.quote_mint === 'So11111111111111111111111111111111111111112' ? 'SOL' : 'USDC',+ name: r.name || null,+ symbol: r.symbol || null,+ credited_usdc_atomics: r.credited,+ registered_at: r.created_at,+ last_crank_at: r.last_crank_at,+ }));+}++/** A handle's recent payouts (any status), for its owner. */+export async function payoutsFor(handleLc, limit = 20) {+ const rows = await sql`+ select id, wallet, usdc_atomics::text as usdc_atomics, trigger, status, signature, error, created_at, confirmed_at+ from fee_bridge_payouts where handle_lc = ${handleLc}+ order by created_at desc limit ${limit}+ `;+ return rows;+}diff --git a/api/_lib/fee-bridge/math.js b/api/_lib/fee-bridge/math.jsnew file mode 100644index 000000000..149fa6650--- /dev/null+++ b/api/_lib/fee-bridge/math.js@@ -0,0 +1,168 @@+// @ts-check+// Pure accounting for the Fee Bridge. No I/O, so every rule that decides who gets+// how much is unit-tested in tests/fee-bridge-math.test.js.+//+// All amounts are BigInt base units: lamports for SOL, atomics (6dp) for USDC.++export const BPS = 10_000n;++// X handles: 1-15 chars of letters, digits, underscore.+const HANDLE_RE = /^[A-Za-z0-9_]{1,15}$/;++/**+ * Parse "@handle", "handle", or an x.com / twitter.com profile URL into the bare+ * handle, or null when it is not a valid X handle.+ * @param {unknown} input+ * @returns {string|null}+ */+export function parseXHandle(input) {+ let s = String(input ?? '').trim();+ if (!s) return null;+ s = s.replace(/^https?:\/\//i, '').replace(/^(?:www\.|mobile\.)?(?:x|twitter)\.com\//i, '');+ s = s.replace(/^@/, '').split(/[/?#]/)[0];+ return HANDLE_RE.test(s) ? s : null;+}++/**+ * Split a USDC amount into the recipient share and the $THREE buyback share.+ * The recipient share is floored, so rounding dust always lands in the buyback+ * and the recipient is never credited more than the batch actually produced.+ * @param {bigint} usdcAtomics+ * @param {number|bigint} recipientBps+ * @returns {{ recipient: bigint, buyback: bigint }}+ */+export function splitRecipientBuyback(usdcAtomics, recipientBps) {+ const total = usdcAtomics > 0n ? usdcAtomics : 0n;+ const bps = clampBps(BigInt(recipientBps));+ const recipient = (total * bps) / BPS;+ return { recipient, buyback: total - recipient };+}++/**+ * Net SOL a coin contributes after the bridge's gas for landing it is charged back.+ * @param {bigint} grossLamports+ * @param {bigint} gasLamports+ */+export function netOfGas(grossLamports, gasLamports) {+ const net = grossLamports - (gasLamports > 0n ? gasLamports : 0n);+ return net > 0n ? net : 0n;+}++/**+ * Allocate `total` across weighted keys with the largest-remainder method, so the+ * parts sum to exactly `total` and no key is ever over-allocated by rounding.+ * @param {bigint} total+ * @param {Array<{ key: string, weight: bigint }>} parts+ * @returns {Map<string, bigint>}+ */+export function allocateProRata(total, parts) {+ const out = new Map();+ const live = parts.filter((p) => p.weight > 0n);+ for (const p of parts) out.set(p.key, 0n);+ const sum = live.reduce((a, p) => a + p.weight, 0n);+ if (total <= 0n || sum <= 0n) return out;++ let assigned = 0n;+ const remainders = [];+ for (const p of live) {+ const exact = total * p.weight;+ const share = exact / sum;+ out.set(p.key, (out.get(p.key) ?? 0n) + share);+ assigned += share;+ remainders.push({ key: p.key, rem: exact % sum });+ }+ remainders.sort((a, b) => (a.rem === b.rem ? a.key.localeCompare(b.key) : a.rem > b.rem ? -1 : 1));+ let left = total - assigned;+ for (let i = 0; left > 0n && i < remainders.length; i++, left--) {+ const k = remainders[i].key;+ out.set(k, (out.get(k) ?? 0n) + 1n);+ }+ return out;+}++/**+ * Per-coin USDC credit for a batch. SOL inflows share the USDC the SOL swap produced+ * pro rata to their net lamports; USDC inflows count at face value. Each coin's+ * total is then split recipient/buyback.+ *+ * @param {object} args+ * @param {Array<{ mint: string, handle_lc: string, sol_net: bigint, usdc_in: bigint }>} args.coins+ * @param {bigint} args.usdcFromSol USDC atomics the SOL swap actually delivered+ * @param {number|bigint} args.recipientBps+ * @returns {{ credits: Array<{ mint: string, handle_lc: string, usdc_atomics: bigint }>, recipientTotal: bigint, buybackTotal: bigint, usdcTotal: bigint }}+ */+export function computeBatchCredits({ coins, usdcFromSol, recipientBps }) {+ const fromSol = allocateProRata(+ usdcFromSol > 0n ? usdcFromSol : 0n,+ coins.map((c) => ({ key: c.mint, weight: c.sol_net })),+ );+ const credits = [];+ let recipientTotal = 0n;+ let buybackTotal = 0n;+ for (const c of coins) {+ const usdc = (fromSol.get(c.mint) ?? 0n) + (c.usdc_in > 0n ? c.usdc_in : 0n);+ const { recipient, buyback } = splitRecipientBuyback(usdc, recipientBps);+ recipientTotal += recipient;+ buybackTotal += buyback;+ if (recipient > 0n) credits.push({ mint: c.mint, handle_lc: c.handle_lc, usdc_atomics: recipient });+ }+ return { credits, recipientTotal, buybackTotal, usdcTotal: recipientTotal + buybackTotal };+}++/**+ * Whether a handle's balance should be paid now.+ * @param {object} args+ * @param {bigint} args.balance unpaid USDC atomics+ * @param {'auto'|'withdraw'} args.trigger+ * @param {bigint} args.autoFloor auto payouts wait for this much+ * @param {bigint} args.withdrawFloor manual withdrawals need at least this much+ */+export function payoutDecision({ balance, trigger, autoFloor, withdrawFloor }) {+ if (balance <= 0n) return { pay: false, reason: 'no_balance' };+ const floor = trigger === 'auto' ? autoFloor : withdrawFloor;+ if (balance < floor) return { pay: false, reason: 'below_floor', floor };+ return { pay: true, amount: balance };+}++/**+ * Balance change of one SPL mint for one owner across a landed transaction, from+ * its pre/post token balances. Missing entries count as zero (an account created+ * by the transaction has no pre balance).+ * @param {{ preTokenBalances?: any[]|null, postTokenBalances?: any[]|null }|null|undefined} meta+ * @param {string} owner+ * @param {string} mint+ * @returns {bigint}+ */+export function tokenDelta(meta, owner, mint) {+ const sum = (rows) =>+ (rows || [])+ .filter((r) => r?.owner === owner && r?.mint === mint)+ .reduce((a, r) => a + BigInt(r.uiTokenAmount?.amount ?? '0'), 0n);+ return sum(meta?.postTokenBalances) - sum(meta?.preTokenBalances);+}++/**+ * Lamports an account received across a landed transaction, with the fee added+ * back when that account paid it (so a crank's inflow is not understated by gas).+ * @param {{ preBalances?: number[], postBalances?: number[], fee?: number }|null|undefined} meta+ * @param {number} accountIndex+ * @param {boolean} isFeePayer+ * @returns {bigint}+ */+export function lamportDelta(meta, accountIndex, isFeePayer) {+ if (!meta || accountIndex < 0) return 0n;+ const pre = BigInt(meta.preBalances?.[accountIndex] ?? 0);+ const post = BigInt(meta.postBalances?.[accountIndex] ?? 0);+ return post - pre + (isFeePayer ? BigInt(meta.fee ?? 0) : 0n);+}++function clampBps(bps) {+ if (bps < 0n) return 0n;+ if (bps > BPS) return BPS;+ return bps;+}++/** USDC atomics to a 2dp dollar number, for display only. */+export function usdcToUsd(atomics) {+ return Number(BigInt(atomics ?? 0)) / 1e6;+}diff --git a/api/_lib/migrations/20260917150000_fee_bridge.sql b/api/_lib/migrations/20260917150000_fee_bridge.sqlnew file mode 100644index 000000000..fa24fed32--- /dev/null+++ b/api/_lib/migrations/20260917150000_fee_bridge.sql@@ -0,0 +1,121 @@+-- Fee Bridge: pay a pump.fun coin's creator fees to an X account in USDC.+--+-- A coin routes 100% of its creator fees (a pump.fun fee-sharing config) to the+-- three.ws fee-bridge wallet and names an X handle. /api/cron/fee-bridge cranks+-- each registered coin's distribution into the bridge wallet, converts the SOL to+-- USDC on Jupiter, spends 20% of it buying $THREE for the treasury, and credits the+-- other 80% to the handle. The handle's owner signs in with X and withdraws to their+-- Solana wallet; once linked, balances past the auto-payout floor are sent without+-- them asking. Docs: docs/fee-bridge.md.+--+-- Every on-chain step persists its signature and blockhash BEFORE broadcasting, so+-- a tick that dies mid-flight is resumed from the chain's answer, never re-sent.++-- Coins whose creator fees route to the bridge, and the handle they pay.+create table if not exists fee_bridge_coins (+ mint text primary key,+ handle text not null,+ handle_lc text not null,+ quote_mint text not null,+ registered_by uuid references users(id) on delete set null,+ agent_id uuid,+ admin_wallet text,+ status text not null default 'active' check (status in ('active', 'unrouted')),+ last_crank_at timestamptz,+ last_error text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);+create index if not exists fee_bridge_coins_handle_idx on fee_bridge_coins (handle_lc);+create index if not exists fee_bridge_coins_crank_idx on fee_bridge_coins (status, last_crank_at nulls first);++-- One row per distribution crank the bridge sent. The row is written as 'sent'+-- before broadcast and settled from the landed transaction: amount_raw is in the+-- quote mint's base units (lamports for SOL, atomics for USDC) and gas_lamports is+-- what the bridge spent landing it, charged back to that coin before conversion.+create table if not exists fee_bridge_inflows (+ id uuid primary key default gen_random_uuid(),+ mint text not null references fee_bridge_coins(mint) on delete cascade,+ quote_mint text not null,+ status text not null default 'sent' check (status in ('sent', 'landed', 'dropped')),+ amount_raw numeric(40) not null default 0 check (amount_raw >= 0),+ gas_lamports bigint not null default 0,+ signature text not null unique,+ blockhash text not null,+ batch_id uuid,+ created_at timestamptz not null default now(),+ landed_at timestamptz+);+create index if not exists fee_bridge_inflows_unbatched_idx on fee_bridge_inflows (created_at) where batch_id is null and status = 'landed';+create index if not exists fee_bridge_inflows_sent_idx on fee_bridge_inflows (created_at) where status = 'sent';+create index if not exists fee_bridge_inflows_mint_idx on fee_bridge_inflows (mint, created_at desc);++-- A conversion run. Stages advance claimed -> swapped -> bought -> swept -> credited.+create table if not exists fee_bridge_batches (+ id uuid primary key default gen_random_uuid(),+ stage text not null default 'claimed'+ check (stage in ('claimed', 'swapped', 'bought', 'swept', 'credited', 'failed')),+ sol_net_lamports numeric(40) not null default 0,+ usdc_in_atomics numeric(40) not null default 0,+ usdc_from_sol_atomics numeric(40) not null default 0,+ buyback_usdc_atomics numeric(40) not null default 0,+ three_bought_atomics numeric(40) not null default 0,+ recipient_usdc_atomics numeric(40) not null default 0,+ swap_sig text,+ swap_blockhash text,+ buy_sig text,+ buy_blockhash text,+ sweep_sig text,+ sweep_blockhash text,+ error text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ completed_at timestamptz+);+-- At most one conversion in flight: the second tick's insert fails instead of racing.+create unique index if not exists fee_bridge_batches_one_open_idx+ on fee_bridge_batches ((true)) where stage in ('claimed', 'swapped', 'bought', 'swept');+create index if not exists fee_bridge_batches_created_idx on fee_bridge_batches (created_at desc);++-- USDC credited to a handle by a completed batch.+create table if not exists fee_bridge_credits (+ id uuid primary key default gen_random_uuid(),+ batch_id uuid not null references fee_bridge_batches(id) on delete cascade,+ mint text not null,+ handle_lc text not null,+ usdc_atomics numeric(40) not null check (usdc_atomics >= 0),+ created_at timestamptz not null default now(),+ unique (batch_id, mint)+);+create index if not exists fee_bridge_credits_handle_idx on fee_bridge_credits (handle_lc, created_at desc);++-- The X account a handle is bound to, pinned on its first payout so a renamed+-- handle taken over by someone else can never withdraw the original owner's balance.+create table if not exists fee_bridge_recipients (+ handle_lc text primary key,+ handle text not null,+ x_user_id text not null unique,+ user_id uuid references users(id) on delete set null,+ bound_at timestamptz not null default now()+);++-- USDC sent to a recipient wallet.+create table if not exists fee_bridge_payouts (+ id uuid primary key default gen_random_uuid(),+ handle_lc text not null,+ user_id uuid references users(id) on delete set null,+ wallet text not null,+ usdc_atomics numeric(40) not null check (usdc_atomics > 0),+ trigger text not null check (trigger in ('auto', 'withdraw')),+ status text not null default 'pending' check (status in ('pending', 'confirmed', 'failed')),+ signature text,+ blockhash text,+ error text,+ created_at timestamptz not null default now(),+ confirmed_at timestamptz+);+-- One payout in flight per handle, so two withdraw clicks can never both spend a balance.+create unique index if not exists fee_bridge_payouts_one_pending_idx+ on fee_bridge_payouts (handle_lc) where status = 'pending';+create index if not exists fee_bridge_payouts_created_idx on fee_bridge_payouts (created_at desc);+create index if not exists fee_bridge_payouts_handle_idx on fee_bridge_payouts (handle_lc, created_at desc);diff --git a/api/_lib/solana-signers.js b/api/_lib/solana-signers.jsindex 43fdb9f50..edfcfb1bb 100644--- a/api/_lib/solana-signers.js+++ b/api/_lib/solana-signers.js@@ -33,6 +33,9 @@* balances (revenue, payout float, tip inventory). The sweepback module* (api/_lib/economy-sweepback.js) never takes its tokens in excess mode —* only an explicit drain consolidates them to the master.+ * @property {boolean} [holdsUserFunds] this wallet holds money owed to third+ * parties (unpaid Fee Bridge recipients), so no sweepback or reclaim mode ever+ * moves its SOL or tokens to the master, drain included.*//** @type {SignerSpec[]} */@@ -112,6 +115,16 @@ export const SOLANA_SIGNERS = [purpose: 'holds platform USDC revenue; pays gas for the run-three-buyback cron (market-buy $THREE → treasury)',network: 'mainnet',},+ {+ name: 'fee-bridge',+ env: 'FEE_BRIDGE_SECRET_KEY_B64',+ minSol: 0.05,+ holdsTokens: true,+ holdsUserFunds: true,+ purpose:+ 'Fee Bridge wallet: receives coin creator fees routed to X handles, cranks distribution, swaps SOL to USDC and buys $THREE for the treasury, and holds unpaid recipient USDC until it is withdrawn (fee-bridge cron)',+ network: 'mainnet',+ },{name: 'club-treasury',env: 'CLUB_SOLANA_TREASURY_SECRET_KEY_B64',diff --git a/api/auth/x/[action].js b/api/auth/x/[action].jsindex 6ac19b494..25040d502 100644--- a/api/auth/x/[action].js+++ b/api/auth/x/[action].js@@ -40,13 +40,14 @@ function b64urlDecode(s) {return Buffer.from(s, 'base64url').toString('utf8');}-async function signState({ state, codeVerifier, userId, agentId, scopeSet }) {+async function signState({ state, codeVerifier, userId, agentId, scopeSet, returnTo }) {const payload = {s: state,v: codeVerifier,u: userId,a: agentId,k: scopeSet,+ r: returnTo || null,e: Math.floor(Date.now() / 1000) + STATE_TTL_SEC,};const body = b64urlEncode(JSON.stringify(payload));@@ -75,6 +76,7 @@ async function verifyState(token, expectedState) {userId: payload.u,agentId: payload.a,scopeSet: resolveScopeSet(payload.k).name,+ returnTo: resolveReturnTo(payload.r),};}@@ -128,7 +130,17 @@ export function decryptToken(ciphertext) {// editor's posting tab, which is about the write access that grant deliberately// does not carry. The callback and the connect endpoint both route through this// so a refusal lands on the same surface a success would.-function connectReturnUrl({ scopeSet, agentId, outcome }) {+// Surfaces that start a connect for their own flow and want the browser back on+// them. An allowlist, never a raw path, so the parameter cannot become an open+// redirect.+const RETURN_SURFACES = new Set(['/fee-bridge']);++function resolveReturnTo(value) {+ return typeof value === 'string' && RETURN_SURFACES.has(value) ? value : null;+}++function connectReturnUrl({ scopeSet, agentId, outcome, returnTo = null }) {+ if (returnTo) return `${returnTo}?x=${outcome}`;if (scopeSet === 'read') {const q = new URLSearchParams({ tab: 'connected-accounts', x: outcome });if (agentId) q.set('agent_id', agentId);@@ -148,6 +160,7 @@ async function handleConnect(req, res) {const url = new URL(req.url, env.APP_ORIGIN);const agentId = url.searchParams.get('agent_id') || null;const scopeSet = resolveScopeSet(url.searchParams.get('scope'));+ const returnTo = resolveReturnTo(url.searchParams.get('return_to'));if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {// Every Connect X button on the site is an anchor or a location assignment,@@ -158,7 +171,7 @@ async function handleConnect(req, res) {if (wantsHtmlNavigation(req)) {return redirect(res,- connectReturnUrl({ scopeSet: scopeSet.name, agentId, outcome: 'unconfigured' }),+ connectReturnUrl({ scopeSet: scopeSet.name, agentId, outcome: 'unconfigured', returnTo }),);}return error(res, 501, 'not_configured', 'X OAuth is not configured');@@ -180,6 +193,7 @@ async function handleConnect(req, res) {userId: user.id,agentId,scopeSet: scopeSet.name,+ returnTo,});res.setHeader('set-cookie', stateCookie(signed));@@ -221,11 +235,11 @@ async function handleCallback(req, res) {res.setHeader('set-cookie', stateCookie('', { clear: true }));if (!stateData) return error(res, 400, 'invalid_state', 'OAuth state expired or invalid');- const { codeVerifier, userId, agentId: stateAgentId, scopeSet } = stateData;+ const { codeVerifier, userId, agentId: stateAgentId, scopeSet, returnTo } = stateData;// Return to the surface that started the connect, the same one a refusal at// /connect lands on.const backTo = (outcome) =>- connectReturnUrl({ scopeSet, agentId: stateAgentId, outcome });+ connectReturnUrl({ scopeSet, agentId: stateAgentId, outcome, returnTo });const successRedirect = backTo('connected');const errorRedirect = backTo('error');const deniedRedirect = backTo('denied');diff --git a/api/cron/fee-bridge.js b/api/cron/fee-bridge.jsnew file mode 100644index 000000000..3d59f7189--- /dev/null+++ b/api/cron/fee-bridge.js@@ -0,0 +1,26 @@+// @ts-check+// GET/POST /api/cron/fee-bridge: one Fee Bridge engine pass (every 10 minutes).+//+// Settles earlier sends, cranks each registered coin's creator-fee distribution+// into the bridge wallet, advances the SOL -> USDC -> $THREE conversion batch, and+// pays linked recipients past the auto-payout floor. See api/_lib/fee-bridge/engine.js+// and docs/fee-bridge.md.+//+// Off until FEE_BRIDGE_ENABLED is truthy and FEE_BRIDGE_SECRET_KEY_B64 is set.+// `?dry=1` reports what the pass would do from live chain + DB state without+// signing anything, and runs even while the bridge is disabled.+//+// Auth: CRON_SECRET Bearer.++import { json, method, wrapCron } from '../_lib/http.js';+import { requireCron } from '../_lib/cron-auth.js';+import { runTick } from '../_lib/fee-bridge/engine.js';++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;+ const url = new URL(req.url, 'http://x');+ const dryRun = /^(1|true)$/i.test(url.searchParams.get('dry') || '');+ const out = await runTick({ dryRun });+ return json(res, 200, out);+});diff --git a/api/fee-bridge/[action].js b/api/fee-bridge/[action].jsnew file mode 100644index 000000000..51ea6e9d1--- /dev/null+++ b/api/fee-bridge/[action].js@@ -0,0 +1,205 @@+// /api/fee-bridge/:action serves the Fee Bridge, a coin's creator fees, paid to an X+// account in USDC. Docs: docs/fee-bridge.md.+//+// GET config bridge wallet, split, floors (public)+// GET stats totals + newest payouts (public)+// GET coins[?handle=] registered coins and what each has earned (public)+// GET coin?mint= one coin's registration + on-chain routing (public)+// GET recipient?handle= a handle's credited / paid / unpaid USDC (public)+// GET me the signed-in user's handle, balance, wallets, payouts+// POST register {mint, handle} register a coin already routing 100% to the bridge+// POST withdraw {wallet?} pay the signed-in user's unpaid balance++import { z } from 'zod';++import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { parse } from '../_lib/validate.js';+import { bridgeAddress, loadBridgeSigner, publicConfig, isEnabled } from '../_lib/fee-bridge/config.js';+import { readSharingState, routesOnlyTo } from '../_lib/fee-bridge/chain.js';+import { parseXHandle } from '../_lib/fee-bridge/math.js';+import { payClaimant, registerCoin } from '../_lib/fee-bridge/engine.js';+import {+ handleBalance,+ listCoins,+ payoutsFor,+ publicStats,+ recentPayouts,+ resolveClaimant,+ solanaWallets,+} from '../_lib/fee-bridge/ledger.js';++const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const PUBLIC_CACHE = { 'cache-control': 'public, max-age=15, s-maxage=30' };++const registerSchema = z.object({+ mint: z.string().regex(MINT_RE, 'invalid mint'),+ handle: z.string().trim().min(1).max(60),+});+const withdrawSchema = z.object({+ wallet: z.string().regex(MINT_RE, 'invalid wallet').optional(),+});++// Typed engine errors (status < 500 or a known 5xx code) go back as-is; anything+// else rethrows to wrap(), which logs it and returns a sanitized envelope.+function sendTyped(res, e) {+ if (e?.status && e?.code) return error(res, e.status, e.code, e.message);+ throw e;+}++async function handleConfig(req, res) {+ return json(res, 200, publicConfig(await bridgeAddress()), PUBLIC_CACHE);+}++async function handleStats(req, res) {+ const [totals, payouts, address] = await Promise.all([publicStats(), recentPayouts(20), bridgeAddress()]);+ return json(res, 200, { config: publicConfig(address), totals, recent_payouts: payouts }, PUBLIC_CACHE);+}++async function handleCoins(req, res, url) {+ const raw = url.searchParams.get('handle');+ const handle = raw ? parseXHandle(raw) : null;+ if (raw && !handle) return error(res, 400, 'invalid_handle', 'invalid X handle');+ const limit = Math.max(1, Math.min(100, Number(url.searchParams.get('limit')) || 50));+ const coins = await listCoins({ limit, handleLc: handle ? handle.toLowerCase() : null });+ return json(res, 200, { coins }, PUBLIC_CACHE);+}++async function handleCoin(req, res, url) {+ const mint = url.searchParams.get('mint') || '';+ if (!MINT_RE.test(mint)) return error(res, 400, 'validation_error', 'valid mint required');+ const address = await bridgeAddress();+ const [row] = await sql`+ select c.mint, c.handle, c.status, c.quote_mint, c.created_at, c.last_crank_at, c.last_error,+ coalesce((select sum(usdc_atomics) from fee_bridge_credits k where k.mint = c.mint), 0)::text as credited+ from fee_bridge_coins c where c.mint = ${mint}+ `;+ let routed = null;+ if (address) {+ const state = await readSharingState(mint).catch(() => null);+ routed = state ? routesOnlyTo(state, address) : null;+ }+ return json(res, 200, {+ mint,+ bridge_wallet: address,+ routes_to_bridge: routed,+ registration: row+ ? {+ handle: row.handle,+ status: row.status,+ quote: row.quote_mint === 'So11111111111111111111111111111111111111112' ? 'SOL' : 'USDC',+ credited_usdc_atomics: row.credited,+ registered_at: row.created_at,+ last_crank_at: row.last_crank_at,+ }+ : null,+ }, { 'cache-control': 'private, no-store' });+}++async function handleRecipient(req, res, url) {+ const handle = parseXHandle(url.searchParams.get('handle'));+ if (!handle) return error(res, 400, 'invalid_handle', 'a valid X handle is required');+ const lc = handle.toLowerCase();+ const [balance, coins, [bound]] = await Promise.all([+ handleBalance(lc),+ listCoins({ limit: 50, handleLc: lc }),+ sql`select handle, bound_at from fee_bridge_recipients where handle_lc = ${lc}`,+ ]);+ return json(res, 200, {+ handle: bound?.handle || handle,+ claimed: !!bound,+ credited_usdc_atomics: balance.credited.toString(),+ paid_usdc_atomics: balance.paid.toString(),+ unpaid_usdc_atomics: balance.unpaid.toString(),+ coins,+ }, PUBLIC_CACHE);+}++async function handleMe(req, res) {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ const address = await bridgeAddress();+ const [[xConn], claimant, wallets] = await Promise.all([+ sql`select username from social_connections where user_id = ${user.id} and provider = 'x' and disconnected_at is null limit 1`,+ resolveClaimant({ userId: user.id }),+ solanaWallets(user.id),+ ]);+ const base = { config: publicConfig(address), x_connected: !!xConn, x_username: xConn?.username || null, wallets };+ if (!claimant) {+ return json(res, 200, { ...base, handle: null, handle_conflict: !!xConn, balance: null, coins: [], payouts: [] }, { 'cache-control': 'private, no-store' });+ }+ const [balance, coins, payouts] = await Promise.all([+ handleBalance(claimant.handleLc),+ listCoins({ limit: 50, handleLc: claimant.handleLc }),+ payoutsFor(claimant.handleLc, 20),+ ]);+ return json(res, 200, {+ ...base,+ handle: claimant.handle,+ handle_conflict: false,+ balance: {+ credited_usdc_atomics: balance.credited.toString(),+ paid_usdc_atomics: balance.paid.toString(),+ in_flight_usdc_atomics: balance.inFlight.toString(),+ unpaid_usdc_atomics: balance.unpaid.toString(),+ },+ coins,+ payouts: payouts.map((p) => ({ ...p })),+ }, { 'cache-control': 'private, no-store' });+}++async function handleRegister(req, res) {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+ const body = parse(registerSchema, await readJson(req));+ try {+ const out = await registerCoin({ userId: user.id, mint: body.mint, handle: body.handle });+ return json(res, out.created ? 201 : 200, out);+ } catch (e) {+ return sendTyped(res, e);+ }+}++async function handleWithdraw(req, res) {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+ const body = parse(withdrawSchema, await readJson(req));+ if (!isEnabled()) return error(res, 503, 'fee_bridge_paused', 'Payouts are paused right now. Your balance is safe; try again later.');+ const claimant = await resolveClaimant({ userId: user.id });+ if (!claimant) {+ return error(res, 409, 'x_not_connected', 'Connect the X account your fees are addressed to before withdrawing.');+ }+ try {+ const signer = await loadBridgeSigner();+ const out = await payClaimant({ signer, claimant, trigger: 'withdraw', wallet: body.wallet });+ return json(res, out.status === 'confirmed' ? 200 : 202, out);+ } catch (e) {+ return sendTyped(res, e);+ }+}++const GET = { config: handleConfig, stats: handleStats, coins: handleCoins, coin: handleCoin, recipient: handleRecipient, me: handleMe };+const POST = { register: handleRegister, withdraw: handleWithdraw };++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const url = new URL(req.url, 'http://x');+ const action = req.query?.action || url.pathname.split('/').filter(Boolean)[2];+ const table = req.method === 'POST' ? POST : GET;+ const handler = table[action];+ if (!handler) return error(res, 404, 'not_found', `unknown fee-bridge action: ${action}`);++ if (req.method === 'GET') {+ const rl = await limits.authedReadIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+ }+ return handler(req, res, url);+});diff --git a/data/changelog.json b/data/changelog.jsonindex 76f9eaed0..9d5aaef80 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-09-17",+ "title": "Fee Bridge: pay a coin's creator fees to any X account in USDC",+ "summary": "A coin's creator fees can now go to a person by their X handle instead of a wallet address. Route the fees to the Fee Bridge from a coin's Fees & rewards panel (or register any pump.fun coin on /fee-bridge), and every ten minutes the bridge converts them to USDC: 80% is credited to the handle and 20% buys $THREE for the treasury. The handle's owner signs in with X, links a Solana wallet and withdraws, and balances over $5 are then paid automatically. Anyone can look up what a handle has earned, and every payout links to its transaction.",+ "tags": [+ "feature"+ ],+ "link": "/fee-bridge"+ },{"date": "2026-09-17","title": "Agent wallets that cannot sign no longer look tradeable",diff --git a/data/pages.json b/data/pages.jsonindex 2a57f1f0f..61bd7f252 100644--- a/data/pages.json+++ b/data/pages.json@@ -1487,6 +1487,14 @@"changefreq": "daily","added": "2026-06-12"},+ {+ "path": "/fee-bridge",+ "title": "Fee Bridge",+ "description": "Route a pump.fun coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana, no wallet needed up front; 20% of every converted dollar buys $THREE for the treasury.",+ "priority": 0.7,+ "changefreq": "daily",+ "added": "2026-09-17"+ },{"path": "/drops","title": "3D Drops",@@ -2989,6 +2997,14 @@"changefreq": "monthly","added": "2026-09-16"},+ {+ "path": "/docs/fee-bridge",+ "title": "Docs · Fee Bridge",+ "description": "How the Fee Bridge pays a coin's creator fees to an X handle in USDC: routing a coin, the 80/20 conversion, claiming with X, the API, and the exactly-once safety model.",+ "priority": 0.6,+ "changefreq": "monthly",+ "added": "2026-09-17"+ },{"path": "/docs/analytics-retention","title": "Docs · Week-2 retention on minted agents",diff --git a/docs/build.md b/docs/build.mdindex 4410160e7..be05f0393 100644--- a/docs/build.md+++ b/docs/build.md@@ -47,7 +47,7 @@ front-end, the `vercel.json` route table, and every `api/**` handler from sourceprovisioned from the `crons` array in `vercel.json` by[scripts/create-gcp-scheduler.mjs](../scripts/create-gcp-scheduler.mjs); thatarray is the count, so read it there rather than trusting a number quoted here-(118 entries on 2026-09-16). There is **no GitHub Actions CI**. Full runbook: [docs/ops/gcp-production.md](./ops/gcp-production.md).+(119 entries on 2026-09-17). There is **no GitHub Actions CI**. Full runbook: [docs/ops/gcp-production.md](./ops/gcp-production.md).`.npmrc` sets `legacy-peer-deps=true` (npm never auto-installs peers — thereason `audit:deploy` checks the peer tree), and `engines.node` pins Nodediff --git a/docs/fee-bridge.md b/docs/fee-bridge.mdnew file mode 100644index 000000000..02f652989--- /dev/null+++ b/docs/fee-bridge.md@@ -0,0 +1,127 @@+# Fee Bridge++The Fee Bridge pays a pump.fun coin's creator fees to an **X account**, in **USDC on Solana**. The person behind that handle doesn't need a wallet or a three.ws account when the coin launches. They sign in with X whenever they like and withdraw what has built up.++- Page: [three.ws/fee-bridge](https://three.ws/fee-bridge)+- API: `/api/fee-bridge/*` ([api/fee-bridge/[action].js](../api/fee-bridge/%5Baction%5D.js))+- Engine: [api/_lib/fee-bridge/](../api/_lib/fee-bridge/engine.js), run every 10 minutes by [api/cron/fee-bridge.js](../api/cron/fee-bridge.js)+- Schema: [20260917150000_fee_bridge.sql](../api/_lib/migrations/20260917150000_fee_bridge.sql)++## Who it is for++- **Creators** who want a coin's fees to go to a developer, artist, cause or community member, identified by X handle rather than by a wallet address.+- **Recipients** who would rather receive dollars than hold whatever a coin trades against.++## How the money moves++1. **Route.** The coin's pump.fun fee-sharing config lists one shareholder, the bridge wallet, at 100%. The coin is then registered to an X handle.+2. **Crank.** Every 10 minutes the bridge runs pump.fun's distribution for each registered coin that has passed the protocol minimum. Accrued fees land in the bridge wallet, and the bridge records how much came from which coin.+3. **Convert.** Once pending fees are worth at least `FEE_BRIDGE_MIN_BATCH_USD` ($5 by default), one batch runs:+ - The SOL is swapped to USDC on Jupiter. Fees from USDC-quoted coins are already USDC and skip this step.+ - Each coin is credited its pro-rata share of the USDC that actually arrived, after the gas the bridge spent landing that coin's distributions.+ - **80%** of each coin's USDC is credited to its handle. **20%** buys $THREE on Jupiter, and that $THREE goes to the treasury. Nothing is burned: the platform never destroys supply (see [api/_lib/token/config.js](../api/_lib/token/config.js)).+4. **Claim.** The recipient signs in on three.ws, connects X (read-only), links a Solana wallet and withdraws. After a wallet is linked, balances of `FEE_BRIDGE_AUTO_PAYOUT_USD` ($5) or more are sent automatically on the next pass.++A balance never expires. It stays in the bridge wallet as USDC until its owner claims it.++### Who can claim a handle++The first payout binds the handle to the numeric id of the X account that withdrew it. After that, only that X account can withdraw, even if it later changes its handle. If someone else picks up the old handle, they cannot claim the original owner's balance.++## Routing a coin++### Launched on three.ws++Open the coin's **Fees & rewards** panel (tokens dashboard, agent page, or Studio). Choose **Pay an X account in USDC**, enter the handle and confirm. The panel writes the fee split with whichever wallet controls the coin (the agent's wallet signs server-side, or your connected creator wallet signs), then registers the handle. If the split is already routed but the handle was never registered, the panel offers to finish registration.++### Any other pump.fun coin++1. With the creator wallet, set the coin's fee-sharing config to one shareholder: the bridge wallet (shown on [/fee-bridge](https://three.ws/fee-bridge) and returned by `GET /api/fee-bridge/config`) at 10000 bps.+2. Link that creator wallet to your three.ws account.+3. Register the coin on [/fee-bridge](https://three.ws/fee-bridge#route), or call the API.++Registration checks the chain rather than trusting the request. The coin must exist, be quoted in SOL or USDC, and route 100% of its fees to the bridge. The caller must also control the coin: either they launched it through three.ws, or its fee-sharing admin wallet is linked to their account. **A coin's handle cannot be changed once registered.** On most coins, a pump.fun fee-sharing update also locks the split permanently.++## API++All amounts are strings in USDC atomics (6 decimals). Errors use the standard `{ "error": code, "error_description": message }` envelope.++| Method | Path | Auth | Returns |+| --- | --- | --- | --- |+| GET | `/api/fee-bridge/config` | none | Bridge wallet, split, payout floors, whether the bridge is enabled |+| GET | `/api/fee-bridge/stats` | none | Totals plus the 20 newest confirmed payouts |+| GET | `/api/fee-bridge/coins?handle=&limit=` | none | Registered coins and what each has credited its handle |+| GET | `/api/fee-bridge/coin?mint=` | none | One coin's registration and whether it routes to the bridge on chain right now |+| GET | `/api/fee-bridge/recipient?handle=` | none | A handle's credited, paid and unpaid USDC, and the coins paying it |+| GET | `/api/fee-bridge/me` | session | Your handle (from your X connection), balance, linked wallets, coins, payouts |+| POST | `/api/fee-bridge/register` | session | Registers `{ mint, handle }` |+| POST | `/api/fee-bridge/withdraw` | session | Pays your unpaid balance to `{ wallet? }` (defaults to your primary Solana wallet) |++Look up what a handle has earned:++```bash+curl -s "https://three.ws/api/fee-bridge/recipient?handle=three_ws"+```++```json+{+ "handle": "three_ws",+ "claimed": false,+ "credited_usdc_atomics": "0",+ "paid_usdc_atomics": "0",+ "unpaid_usdc_atomics": "0",+ "coins": []+}+```++Withdraw from a signed-in browser session:++```js+const res = await fetch('/api/fee-bridge/withdraw', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({}),+});+const payout = await res.json();+// 200 { status: 'confirmed', signature, wallet, usdc_atomics }+// 202 { status: 'pending', ... } while the transfer is still confirming+```++Withdrawal errors you can act on: `x_not_connected` (connect X first), `no_wallet` (link a Solana wallet), `below_floor` (under the $1 minimum), `payout_in_flight` (one is already on its way), `fee_bridge_paused`.++## Safety model++- **Exactly-once sending.** Every crank, swap, buyback, sweep and payout saves its signature and blockhash before it is broadcast. If a pass dies partway, the next pass checks the chain for that signature. A transaction that landed is recorded. One whose blockhash expired without landing is safely retried. Nothing is ever sent twice.+- **No double spend.** A payout's balance check and its insert run as one statement, and a partial unique index allows only one pending payout per handle.+- **Balances are derived, not stored.** Unpaid is always credits minus pending and confirmed payouts, so no running total can drift from the rows behind it.+- **The bridge wallet is exempt from the economy sweeps.** Its signer is registered with `holdsUserFunds` in [api/_lib/solana-signers.js](../api/_lib/solana-signers.js), so neither the treasury sweep nor the idle-SOL reclaim can move recipients' money.+- **Conversion waits for gas.** A batch only starts when the bridge holds the batch's SOL plus a gas reserve (`FEE_BRIDGE_GAS_RESERVE_SOL`).++## Operating it++| Env var | Default | Purpose |+| --- | --- | --- |+| `FEE_BRIDGE_ENABLED` | off | Master switch for cranks, conversion, auto payouts and withdrawals |+| `FEE_BRIDGE_SECRET_KEY_B64` | none | The bridge wallet keypair. Any encoding `solana-signers.js` accepts |+| `FEE_BRIDGE_RECIPIENT_BPS` | 8000 | Recipient share (5000 to 10000); the rest buys $THREE |+| `FEE_BRIDGE_AUTO_PAYOUT_USD` | 5 | Auto payout floor for linked recipients |+| `FEE_BRIDGE_WITHDRAW_MIN_USD` | 1 | Smallest manual withdrawal |+| `FEE_BRIDGE_MIN_BATCH_USD` | 5 | Pending value needed before a conversion runs |+| `FEE_BRIDGE_SLIPPAGE_BPS` | 100 | Jupiter slippage for both swaps |+| `FEE_BRIDGE_GAS_RESERVE_SOL` | 0.03 | SOL kept back for gas and rent |+| `FEE_BRIDGE_CRANK_INTERVAL_MIN` | 30 | Minutes between cranks of one coin |+| `FEE_BRIDGE_CRANK_PER_TICK` / `FEE_BRIDGE_PAYOUTS_PER_TICK` | 10 / 10 | Per-pass work caps |++Preview a pass without signing anything (this works even while the bridge is disabled):++```bash+curl -s -H "authorization: Bearer $CRON_SECRET" "https://three.ws/api/cron/fee-bridge?dry=1"+```++The response lists each due coin's distributable fees, whether a conversion would run and at what quoted value, and which recipients would be paid.++## Related++- [Launchpad](./launchpad.md): launching a pump.fun coin on three.ws+- [STRUCTURE.md](../STRUCTURE.md): where every surface livesdiff --git a/docs/start-here.md b/docs/start-here.mdindex 2b189882e..637b819b1 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -216,6 +216,7 @@ Deeper references that don't fit a track above but answer real questions:- [ERC-8004 validation attestation](./erc8004/validation-attestation.md): the attestation written when an agent registers on-chain- [zauth](./zauth/index.md): the vendored security infrastructure docs our agent auth builds on- [The /launch launchpad](./launchpad.md): launch a pump.fun coin for a 3D agent from your wallet or the agent's wallet, pay a disclosed 1% dev-buy fee, and claim creator rewards on three.ws, with automatic Solana transaction v1 for launches that overflow v0+- [Fee Bridge](./fee-bridge.md): pay a coin's creator fees to an X account in USDC, with 20% buying $THREE for the treasury; routing, claiming with X, the API and the exactly-once safety model- [Agent tokens](./agent-tokens.md): configure the coin an agent will become, rehearse the launch for free against a real cluster, then launch it on Solana- [pump.fun program docs](./pumpfun-program/README.md): the vendored on-chain program reference behind the launch surfaces- [pump-fun-mcp at the edge](./pump-fun-mcp-edge.md): the Cloudflare Workers mirror of the pump.fun MCP endpointdiff --git a/pages/fee-bridge.html b/pages/fee-bridge.htmlnew file mode 100644index 000000000..5be952c4e--- /dev/null+++ b/pages/fee-bridge.html@@ -0,0 +1,167 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot, no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Fee Bridge · three.ws</title>+ <meta name="description" content="Route a coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana, no wallet needed up front. 80% to the recipient, 20% buys $THREE for the treasury." />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/fee-bridge" />+ <meta property="og:title" content="Fee Bridge · three.ws" />+ <meta property="og:description" content="Route a coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana." />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Fee+Bridge&d=Creator+fees%2C+paid+to+an+X+account+in+USDC.&p=%2Ffee-bridge" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta property="og:image:alt" content="Fee Bridge on three.ws" />+ <meta property="og:locale" content="en_US" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Fee Bridge · three.ws" />+ <meta name="twitter:description" content="Route a coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Fee+Bridge&d=Creator+fees%2C+paid+to+an+X+account+in+USDC.&p=%2Ffee-bridge" />+ <meta name="theme-color" content="#0a0a0a" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <link rel="canonical" href="https://three.ws/fee-bridge" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/fee-bridge.css" />+ <link rel="stylesheet" href="/footer.css" />+ <script defer src="/footer-newsletter.js"></script>+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Fee Bridge","description":"Route a coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana.","url":"https://three.ws/fee-bridge","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="fb-shell" aria-labelledby="fb-title">+ <section class="fb-hero">+ <p class="fb-kicker">Fee Bridge · Solana</p>+ <h1 id="fb-title" class="fb-title">Creator fees, paid to an X account in USDC.</h1>+ <p class="fb-sub">+ Point a coin's creator fees at the bridge and name an X handle. The owner of that handle signs in+ with X and withdraws dollars on Solana. They never need a wallet before the money shows up.+ </p>+ <div class="fb-ctas">+ <a class="fb-btn fb-btn-primary" href="#claim">Claim your payouts</a>+ <a class="fb-btn" href="#route">Route a coin's fees</a>+ <a class="fb-btn fb-btn-quiet" href="/docs/fee-bridge">How it works</a>+ </div>+ <div id="fb-banner" class="fb-banner" hidden role="status"></div>+ </section>++ <section class="fb-stats" aria-label="Fee Bridge totals">+ <div class="fb-stat"><span class="fb-stat-n" id="fb-stat-paid" data-skel> </span><span class="fb-stat-l">Paid out in USDC</span></div>+ <div class="fb-stat"><span class="fb-stat-n" id="fb-stat-unpaid" data-skel> </span><span class="fb-stat-l">Waiting to be claimed</span></div>+ <div class="fb-stat"><span class="fb-stat-n" id="fb-stat-coins" data-skel> </span><span class="fb-stat-l">Coins routing fees</span></div>+ <div class="fb-stat"><span class="fb-stat-n" id="fb-stat-buyback" data-skel> </span><span class="fb-stat-l">Spent buying $THREE</span></div>+ </section>++ <section class="fb-grid">+ <article id="claim" class="fb-card fb-claim" aria-labelledby="fb-claim-title">+ <header class="fb-card-head">+ <h2 id="fb-claim-title">Your payouts</h2>+ <span class="fb-chip" id="fb-claim-chip" hidden></span>+ </header>+ <div id="fb-claim-body" class="fb-claim-body" aria-live="polite">+ <div class="fb-skel fb-skel-lg"></div>+ <div class="fb-skel"></div>+ <div class="fb-skel fb-skel-sm"></div>+ </div>+ </article>++ <article class="fb-card fb-lookup" aria-labelledby="fb-lookup-title">+ <header class="fb-card-head"><h2 id="fb-lookup-title">Check any handle</h2></header>+ <form id="fb-lookup-form" class="fb-inline-form" novalidate>+ <label class="fb-sr" for="fb-lookup-input">X handle</label>+ <span class="fb-at" aria-hidden="true">@</span>+ <input id="fb-lookup-input" name="handle" autocomplete="off" spellcheck="false" placeholder="handle" maxlength="60" />+ <button class="fb-btn" type="submit">Look up</button>+ </form>+ <div id="fb-lookup-out" class="fb-lookup-out" aria-live="polite">+ <p class="fb-muted">See what any X account has earned through the bridge, and which coins pay it.</p>+ </div>+ </article>+ </section>++ <section class="fb-how" aria-labelledby="fb-how-title">+ <h2 id="fb-how-title" class="fb-h2">How the money moves</h2>+ <ol class="fb-steps">+ <li>+ <span class="fb-step-n">1</span>+ <h3>Fees route to the bridge</h3>+ <p>The coin's pump.fun fee-sharing config sends 100% of creator fees to the bridge wallet, and the coin is registered to an X handle.</p>+ </li>+ <li>+ <span class="fb-step-n">2</span>+ <h3>Converted to dollars</h3>+ <p>Every ten minutes the bridge distributes accrued fees, swaps the SOL to USDC on Jupiter, and credits the handle.</p>+ </li>+ <li>+ <span class="fb-step-n">3</span>+ <h3>Claimed with X</h3>+ <p>The handle's owner signs in with X and withdraws to a Solana wallet. Once a wallet is linked, balances over the auto-payout floor are sent automatically.</p>+ </li>+ </ol>+ <div class="fb-split" id="fb-split" aria-label="How each dollar is split">+ <div class="fb-split-bar"><span class="fb-split-a" id="fb-split-a" style="--w: 80%"></span><span class="fb-split-b" id="fb-split-b" style="--w: 20%"></span></div>+ <div class="fb-split-legend">+ <span><i class="fb-dot fb-dot-a"></i><b id="fb-split-a-l">80%</b> to the recipient, in USDC</span>+ <span><i class="fb-dot fb-dot-b"></i><b id="fb-split-b-l">20%</b> buys $THREE for the treasury</span>+ </div>+ </div>+ </section>++ <section id="route" class="fb-card fb-route" aria-labelledby="fb-route-title">+ <header class="fb-card-head"><h2 id="fb-route-title">Route a coin's fees</h2></header>+ <div class="fb-route-grid">+ <div>+ <h3 class="fb-h3">Launched on three.ws?</h3>+ <p class="fb-muted">Open the coin's <b>Fees & rewards</b> panel from your <a href="/dashboard/tokens">tokens dashboard</a> or the agent page and choose <b>Pay an X account in USDC</b>. It writes the split and registers the handle in one step.</p>+ <h3 class="fb-h3">Any other pump.fun coin</h3>+ <ol class="fb-list">+ <li>With the coin's creator wallet, set its fee-sharing config to one shareholder: the bridge wallet below, at 100%.</li>+ <li>Link that creator wallet to your three.ws account, then register the coin here.</li>+ </ol>+ <div class="fb-wallet-copy">+ <code id="fb-bridge-addr" class="fb-addr">loading bridge wallet</code>+ <button class="fb-btn fb-btn-sm" id="fb-copy-addr" type="button" disabled>Copy</button>+ </div>+ <p class="fb-warn">A pump.fun fee-sharing update is usually final. Check the handle before you sign: a registered coin cannot be pointed at a different handle later.</p>+ </div>+ <form id="fb-register" class="fb-form" novalidate>+ <label for="fb-reg-mint">Coin mint</label>+ <input id="fb-reg-mint" name="mint" autocomplete="off" spellcheck="false" placeholder="Mint address" maxlength="44" required />+ <label for="fb-reg-handle">Pay this X handle</label>+ <div class="fb-inline-input"><span class="fb-at" aria-hidden="true">@</span><input id="fb-reg-handle" name="handle" autocomplete="off" spellcheck="false" placeholder="handle" maxlength="60" required /></div>+ <button class="fb-btn fb-btn-primary" type="submit" id="fb-reg-submit">Register coin</button>+ <div id="fb-reg-out" class="fb-form-out" aria-live="polite"></div>+ </form>+ </div>+ </section>++ <section class="fb-ledger" aria-labelledby="fb-ledger-title">+ <div class="fb-ledger-col">+ <h2 id="fb-ledger-title" class="fb-h2">Latest payouts</h2>+ <ul id="fb-payouts" class="fb-rows"><li class="fb-skel"></li><li class="fb-skel"></li><li class="fb-skel"></li></ul>+ </div>+ <div class="fb-ledger-col">+ <h2 class="fb-h2">Coins routing fees</h2>+ <ul id="fb-coins" class="fb-rows"><li class="fb-skel"></li><li class="fb-skel"></li><li class="fb-skel"></li></ul>+ </div>+ </section>+ </main>++ <script type="module" src="/src/fee-bridge.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex 6f2f3a9b0..efe51ed47 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,14 +1,44 @@{- "generated_at": "2026-09-17T01:21:37.042Z",+ "generated_at": "2026-09-17T04:38:40.527Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 3689,+ "total": 3693,"complete": false,"full_feed": "/changelog.json","entries": [+ {+ "date": "2026-09-17",+ "type": "launch",+ "title": "Docs · Fee Bridge",+ "summary": "How the Fee Bridge pays a coin's creator fees to an X handle in USDC: routing a coin, the 80/20 conversion, claiming with X, the API, and the exactly-once safety model.",+ "link": "/docs/fee-bridge",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-09-17",+ "type": "launch",+ "title": "Fee Bridge",+ "summary": "Route a pump.fun coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana, no wallet needed up front; 20% of every converted dollar buys $THREE for the treasury.",+ "link": "/fee-bridge",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-09-17",+ "type": "update",+ "title": "Agent wallets that cannot sign no longer look tradeable",+ "summary": "A small number of agent wallets hold a balance that three.ws cannot currently sign for. Their Portfolio tab used to show a live net worth with Trade buttons, and the Trade tab showed a working form, so the first sign of trouble was a failed withdrawal. Portfolio and Trade now say up front that trading and withdrawals are paused for that wallet, hide the actions that cannot work, and link straight to support. The explanation is also clearer: the balance has not moved, it is still on chain at the same address, and you should not create a replacement wallet while access is being restored.",+ "link": "/agents",+ "tags": [+ "fix"+ ]+ },{"date": "2026-09-17","type": "update",@@ -20,6 +50,16 @@"fix"]},+ {+ "date": "2026-09-17",+ "type": "update",+ "title": "Fee Bridge: pay a coin's creator fees to any X account in USDC",+ "summary": "A coin's creator fees can now go to a person by their X handle instead of a wallet address. Route the fees to the Fee Bridge from a coin's Fees & rewards panel (or register any pump.fun coin on /fee-bridge), and every ten minutes the bridge converts them to USDC: 80% is credited to the handle and 20% buys $THREE for the treasury. The handle's owner signs in with X, links a Solana wallet and withdraws, and balances over $5 are then paid automatically. Anyone can look up what a handle has earned, and every payout links to its transaction.",+ "link": "/fee-bridge",+ "tags": [+ "feature"+ ]+ },{"date": "2026-09-16","type": "launch",@@ -1580,46 +1620,6 @@"fix","improvement"]- },- {- "date": "2026-09-07",- "type": "launch",- "title": "Awesome 3D Agents",- "summary": "A curated, link-checked list of everything you need to give an AI agent a body: text-to-3D models, capture and Gaussian splatting, avatars, rigging, motion generation, lipsync and voice, web renderers, asset pipelines, and the agent frameworks that drive them. Searchable and filterable, and published as an awesome list on GitHub.",- "link": "/awesome",- "tags": [- "launch"- ]- },- {- "date": "2026-09-07",- "type": "launch",- "title": "Docs · Robinhood Portfolios",- "summary": "How Robinhood Portfolios works: the manifest that makes a generated basket binding, in-kind issuance that needs no price oracle, the descending-price rebalance auction nobody can front-run, what happens when a tokenized equity is halted, and the lineage fee budget that leaves sybils nothing to farm.",- "link": "/docs/robinhood-portfolios",- "tags": [- "launch"- ]- },- {- "date": "2026-09-07",- "type": "launch",- "title": "Docs · SEO and crawler rendering",- "summary": "How a JavaScript site is served to search engines: the four server-side render paths, the contract that keeps a page and its sitemap entry agreeing, and how to audit the live origin.",- "link": "/docs/seo",- "tags": [- "launch"- ]- },- {- "date": "2026-09-07",- "type": "launch",- "title": "Hood Desk",- "summary": "A live onchain trading desk for any Robinhood Chain (4663) wallet: book value, native balance history rebuilt from the indexer, an activity tape of swaps and transfers, positions priced against Chainlink NAV and the deepest Uniswap pool, the NAV premium ridge layered by pool depth, counterparty flow, and memecoin movers.",- "link": "/markets/robinhood/desk",- "tags": [- "launch"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex 4fa8cbf50..75a9750ae 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,41 @@{- "generated_at": "2026-09-17T01:21:37.021Z",+ "generated_at": "2026-09-17T04:38:40.501Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-09-17",+ "type": "launch",+ "title": "Docs · Fee Bridge",+ "summary": "How the Fee Bridge pays a coin's creator fees to an X handle in USDC: routing a coin, the 80/20 conversion, claiming with X, the API, and the exactly-once safety model.",+ "link": "/docs/fee-bridge",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-09-17",+ "type": "launch",+ "title": "Fee Bridge",+ "summary": "Route a pump.fun coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana, no wallet needed up front; 20% of every converted dollar buys $THREE for the treasury.",+ "link": "/fee-bridge",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-09-17",+ "type": "update",+ "title": "Agent wallets that cannot sign no longer look tradeable",+ "summary": "A small number of agent wallets hold a balance that three.ws cannot currently sign for. Their Portfolio tab used to show a live net worth with Trade buttons, and the Trade tab showed a working form, so the first sign of trouble was a failed withdrawal. Portfolio and Trade now say up front that trading and withdrawals are paused for that wallet, hide the actions that cannot work, and link straight to support. The explanation is also clearer: the balance has not moved, it is still on chain at the same address, and you should not create a replacement wallet while access is being restored.",+ "link": "/agents",+ "tags": [+ "fix"+ ]+ },{"date": "2026-09-17","type": "update",@@ -17,6 +47,16 @@"fix"]},+ {+ "date": "2026-09-17",+ "type": "update",+ "title": "Fee Bridge: pay a coin's creator fees to any X account in USDC",+ "summary": "A coin's creator fees can now go to a person by their X handle instead of a wallet address. Route the fees to the Fee Bridge from a coin's Fees & rewards panel (or register any pump.fun coin on /fee-bridge), and every ten minutes the bridge converts them to USDC: 80% is credited to the handle and 20% buys $THREE for the treasury. The handle's owner signs in with X, links a Solana wallet and withdraws, and balances over $5 are then paid automatically. Anyone can look up what a handle has earned, and every payout links to its transaction.",+ "link": "/fee-bridge",+ "tags": [+ "feature"+ ]+ },{"date": "2026-09-16","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex f96bdb5a6..d43234fbd 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,30 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws: features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Docs · Fee Bridge</title>+ <link>https://three.ws/docs/fee-bridge</link>+ <guid isPermaLink="false">2026-09-17:Docs · Fee Bridge</guid>+ <pubDate>Thu, 17 Sep 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>How the Fee Bridge pays a coin's creator fees to an X handle in USDC: routing a coin, the 80/20 conversion, claiming with X, the API, and the exactly-once safety model.</description>+ </item>+ <item>+ <title>Fee Bridge</title>+ <link>https://three.ws/fee-bridge</link>+ <guid isPermaLink="false">2026-09-17:Fee Bridge</guid>+ <pubDate>Thu, 17 Sep 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Route a pump.fun coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana, no wallet needed up front; 20% of every converted dollar buys $THREE for the treasury.</description>+ </item>+ <item>+ <title>Agent wallets that cannot sign no longer look tradeable</title>+ <link>https://three.ws/agents</link>+ <guid isPermaLink="false">2026-09-17:Agent wallets that cannot sign no longer look tradeable</guid>+ <pubDate>Thu, 17 Sep 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>A small number of agent wallets hold a balance that three.ws cannot currently sign for. Their Portfolio tab used to show a live net worth with Trade buttons, and the Trade tab showed a working form, so the first sign of trouble was a failed withdrawal. Portfolio and Trade now say up front that trading and withdrawals are paused for that wallet, hide the actions that cannot work, and link straight to support. The explanation is also clearer: the balance has not moved, it is still on chain at the same address, and you should not create a replacement wallet while access is being restored.</description>+ </item><item><title>Ask your AI assistant to show the picture inside a Solana transaction</title><link>https://three.ws/docs/mcp-solana-memo-media</link>@@ -14,6 +38,14 @@<category>feature</category><description>Some Solana transactions carry a small image written straight into their memo, which explorers show as thousands of characters of unreadable text. A new free MCP server, @three-ws/solana-memo-media-mcp, lets Claude, Cursor or any other MCP client fetch a transaction by its signature and show you the image directly, alongside who signed it and a fingerprint of the exact bytes. It can also scan an account's recent history and pick out only the transactions that carry images. It needs no account, key or wallet, never writes anything, and only shows PNG, JPEG, WebP and GIF files whose contents match their label. The Onchain Viewer at /onchain was also fixed: it only recognised the newest memo program, so memos written through the standard Solana memo program were reported as missing. It now reads all three.</description></item>+ <item>+ <title>Fee Bridge: pay a coin's creator fees to any X account in USDC</title>+ <link>https://three.ws/fee-bridge</link>+ <guid isPermaLink="false">2026-09-17:Fee Bridge: pay a coin's creator fees to any X account in USDC</guid>+ <pubDate>Thu, 17 Sep 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A coin's creator fees can now go to a person by their X handle instead of a wallet address. Route the fees to the Fee Bridge from a coin's Fees & rewards panel (or register any pump.fun coin on /fee-bridge), and every ten minutes the bridge converts them to USDC: 80% is credited to the handle and 20% buys $THREE for the treasury. The handle's owner signs in with X, links a Solana wallet and withdraws, and balances over $5 are then paid automatically. Anyone can look up what a handle has earned, and every payout links to its transaction.</description>+ </item><item><title>Docs · The /launch launchpad</title><link>https://three.ws/docs/launchpad</link>diff --git a/public/features.json b/public/features.jsonindex a39b36645..0ed3dc78b 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-09-17T01:21:37.004Z",+ "generated_at": "2026-09-17T04:38:40.488Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1797,6 +1797,16 @@"tags": [],"showcase": false},+ {+ "path": "/fee-bridge",+ "title": "Fee Bridge",+ "description": "Route a pump.fun coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana, no wallet needed up front; 20% of every converted dollar buys $THREE for the treasury.",+ "added": "2026-09-17",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/drops","title": "3D Drops",@@ -3638,6 +3648,16 @@"tags": [],"showcase": false},+ {+ "path": "/docs/fee-bridge",+ "title": "Docs · Fee Bridge",+ "description": "How the Fee Bridge pays a coin's creator fees to an X handle in USDC: routing a coin, the 80/20 conversion, claiming with X, the API, and the exactly-once safety model.",+ "added": "2026-09-17",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/docs/analytics-retention","title": "Docs · Week-2 retention on minted agents",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 43a7b5a79..f0609a758 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -1100,6 +1100,12 @@ URL: https://three.ws/launchesLive public feed of every coin launched by a three.ws agent: market caps, graduation status, and the agent behind each launch.+### Fee Bridge++URL: https://three.ws/fee-bridge++Route a pump.fun coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana, no wallet needed up front; 20% of every converted dollar buys $THREE for the treasury.+### 3D DropsURL: https://three.ws/drops@@ -2230,6 +2236,12 @@ URL: https://three.ws/docs/launchpadHow three.ws/launch launches a pump.fun coin for a 3D agent: agent-linked metadata, the 1% dev-buy fee, v0 lookup-table and Solana transaction v1 formats, claiming creator rewards on three.ws, and the API behind it.+### Docs · Fee Bridge++URL: https://three.ws/docs/fee-bridge++How the Fee Bridge pays a coin's creator fees to an X handle in USDC: routing a coin, the 80/20 conversion, claiming with X, the API, and the exactly-once safety model.+### Docs · Week-2 retention on minted agentsURL: https://three.ws/docs/analytics-retentiondiff --git a/public/llms.txt b/public/llms.txtindex 5aea9156c..4bd067851 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -206,6 +206,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Launch a Coin](https://three.ws/launch): The pump.fun launchpad for 3D AI agents: pick your agent, name the coin, launch it from your wallet or the agent's wallet, and claim creator rewards on three.ws.- [Launch Studio: 50 ways to mint a coin](https://three.ws/launch-studio): A catalog of 50 coin-launch use cases: reward coins for trending GitHub repos and creators, and coins riding live cultural, news, and onchain narratives. Preview what each would mint right now from live data, then launch on pump.fun in one click.- [Agent Launches](https://three.ws/launches): Live public feed of every coin launched by a three.ws agent: market caps, graduation status, and the agent behind each launch.+- [Fee Bridge](https://three.ws/fee-bridge): Route a pump.fun coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana, no wallet needed up front; 20% of every converted dollar buys $THREE for the treasury.- [3D Drops](https://three.ws/drops): Launch a supply-capped collection of AI-forged 3D characters. Pick a style, define weighted trait layers, and three.ws rolls the whole supply from a published seed: verifiable rarity, rigged animation-ready art, forged on reveal.- [Minted 3D Assets](https://three.ws/minted): Live public gallery of every generated 3D avatar minted as a Metaplex Core NFT through three.ws: interactive viewer, baked provenance, and enforced creator royalties on every card.- [Print Certificates](https://three.ws/cert): Check the certificate of authenticity that ships with every three.ws physical print. Scan the code on the box or type the certificate number to see the original 3D model spinning, its edition number, the SHA-256 of the exact bytes that went to the printer, and the Solana transaction attesting both. Each certificate lives at /cert/<id>.@@ -387,6 +388,7 @@ Docs, tutorials, and reference.- [Docs · pump.fun first-claims channel](https://three.ws/docs/pump-claims-channel): A live Telegram feed of first-time pump.fun creator fee claims: how the delivery lane scans, dedupes by transaction signature, and drains a backlog in order, plus the configuration it needs and why the direct on-chain fallback cannot serve the feed.- [Docs · Agent tokens](https://three.ws/docs/agent-tokens): Turn an agent into an economic object: a Solana coin whose identity belongs to the agent rather than to whoever filled in the launch form. Covers configuring a coin before it exists, rehearsing the launch for free, and the single command that launches it for real.- [Docs · The /launch launchpad](https://three.ws/docs/launchpad): How three.ws/launch launches a pump.fun coin for a 3D agent: agent-linked metadata, the 1% dev-buy fee, v0 lookup-table and Solana transaction v1 formats, claiming creator rewards on three.ws, and the API behind it.+- [Docs · Fee Bridge](https://three.ws/docs/fee-bridge): How the Fee Bridge pays a coin's creator fees to an X handle in USDC: routing a coin, the 80/20 conversion, claiming with X, the API, and the exactly-once safety model.- [Docs · Week-2 retention on minted agents](https://three.ws/docs/analytics-retention): How three.ws measures the one number that gates phase 2 of the roadmap: whether users come back to converse with the agent they minted. Defines the cohort, the return event, and the query behind the reported figure.- [Docs · GitHub memory seeding](https://three.ws/docs/github-memory-seeding): Give an agent your work: your public GitHub profile plus the repositories and READMEs you pick, distilled into long-term memory so the agent speaks concretely about what you build instead of guessing. Consent is explicit and revoking it deletes every memory the grant produced.- [Docs · Reputation Staking Market](https://three.ws/docs/reputation-staking-market): Stake conviction on an agent and earn from its attested action history. Principal sits in a market escrow, yield is derived per epoch from the agent's signed on-chain attestations, and positions build on the existing threews.stake.v1 conviction signal.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 79ed15f29..6ce92ac5e 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -96,7 +96,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 937 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 939 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -108,7 +108,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 937 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 939 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd id="sm-filter-kbd" aria-hidden="true">/</kbd></div><p class="sm-filter-count" role="status" aria-live="polite"><span id="sm-filter-count"></span><span id="sm-filter-hint" aria-hidden="true"></span></p>@@ -116,6 +116,22 @@<h2 id="sm-new-title">Newest<a class="sm-new-more" href="/changelog">full changelog →</a></h2><p class="sm-section-desc">The 9 most recently launched pages, straight to the live surface.</p><ul class="sm-list">+ <li>+ <a href="/fee-bridge">+ <span class="sm-new-date">Sep 17, 2026</span>+ <span class="sm-title">Fee Bridge</span>+ <span class="sm-path">/fee-bridge</span>+ <span class="sm-desc">Route a pump.fun coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana, no wallet needed up front; 20% of every converted dollar buys $THREE for the treasury.</span>+ </a>+ </li>+ <li>+ <a href="/docs/fee-bridge">+ <span class="sm-new-date">Sep 17, 2026</span>+ <span class="sm-title">Docs · Fee Bridge</span>+ <span class="sm-path">/docs/fee-bridge</span>+ <span class="sm-desc">How the Fee Bridge pays a coin's creator fees to an X handle in USDC: routing a coin, the 80/20 conversion, claiming with X, the API, and the exactly-once safety model.</span>+ </a>+ </li><li><a href="/docs/launchpad"><span class="sm-new-date">Sep 16, 2026</span>@@ -172,22 +188,6 @@<span class="sm-desc">Control a 3D agent with your hands and no camera. three.ws plays an inaudible carrier tone through your speakers and reads the Doppler shift of your hand off the microphone, so a sweep, a push or a lift moves the avatar on screen.</span></a></li>- <li>- <a href="/fade">- <span class="sm-new-date">Sep 9, 2026</span>- <span class="sm-title">Fade Radar: the wallets that are never right</span>- <span class="sm-path">/fade</span>- <span class="sm-desc">The inverse of the Smart Money Radar. Every pump.fun coin ranked by how much of its buy side comes from wallets with a judged on-chain record and not one winner in it, with the measured, out-of-sample odds behind each verdict.</span>- </a>- </li>- <li>- <a href="/docs/fade-radar">- <span class="sm-new-date">Sep 9, 2026</span>- <span class="sm-title">Docs · Fade Radar</span>- <span class="sm-path">/docs/fade-radar</span>- <span class="sm-desc">How the Fade Radar scores a coin's buy side: what makes a wallet a reverse indicator, the 0 to 100 fade score, the verdict bands, and the out-of-sample measurement behind them.</span>- </a>- </li></ul></section><nav class="sm-toc" aria-label="Sections">@@ -1373,7 +1373,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>146</span></h2>+ <h2>Crypto<span class="sm-count" data-count>147</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -1468,6 +1468,13 @@<span class="sm-desc">Live public feed of every coin launched by a three.ws agent: market caps, graduation status, and the agent behind each launch.</span></a></li>+ <li>+ <a href="/fee-bridge">+ <span class="sm-title">Fee Bridge</span>+ <span class="sm-path">/fee-bridge</span>+ <span class="sm-desc">Route a pump.fun coin's creator fees to any X account. Recipients sign in with X and withdraw USDC on Solana, no wallet needed up front; 20% of every converted dollar buys $THREE for the treasury.</span>+ </a>+ </li><li><a href="/drops"><span class="sm-title">3D Drops</span>@@ -2583,7 +2590,7 @@<section class="sm-section" id="learn"><header>- <h2>Learn<span class="sm-count" data-count>433</span></h2>+ <h2>Learn<span class="sm-count" data-count>434</span></h2><p class="sm-section-desc">Docs, tutorials, and reference.</p></header><ul class="sm-list">@@ -2769,6 +2776,13 @@<span class="sm-desc">How three.ws/launch launches a pump.fun coin for a 3D agent: agent-linked metadata, the 1% dev-buy fee, v0 lookup-table and Solana transaction v1 formats, claiming creator rewards on three.ws, and the API behind it.</span></a></li>+ <li>+ <a href="/docs/fee-bridge">+ <span class="sm-title">Docs · Fee Bridge</span>+ <span class="sm-path">/docs/fee-bridge</span>+ <span class="sm-desc">How the Fee Bridge pays a coin's creator fees to an X handle in USDC: routing a coin, the 80/20 conversion, claiming with X, the API, and the exactly-once safety model.</span>+ </a>+ </li><li><a href="/docs/analytics-retention"><span class="sm-title">Docs · Week-2 retention on minted agents</span>diff --git a/public/studio/fees-panel.js b/public/studio/fees-panel.jsindex fcf8abf94..3ab53a4bb 100644--- a/public/studio/fees-panel.js+++ b/public/studio/fees-panel.js@@ -14,6 +14,9 @@// resolve-github-shareholder so the split pays a real, claimable address.// • Distribute / claim-if-delegated — anyone (creator, agent, or a delegated// shareholder) can crank distribution to release accrued shares.+// • Pay an X account in USDC: route 100% of creator fees to the three.ws Fee+// Bridge and register the handle (/api/fee-bridge/*). The bridge converts the+// fees to USDC the handle's owner withdraws after signing in with X.//// Entry:// mountFeesPanel(el, {@@ -275,6 +278,8 @@ export function mountFeesPanel(container, opts = {}) {rows: [], // [{ address, pct, gh?:{login,avatar} }]githubRepo: '', githubBusy: false, githubError: '',ghMode: 'contributors', // 'contributors' = split a repo; 'owner' = repo owner/creator gets 100%+ bridge: null, // /api/fee-bridge/coin payload, mainnet only+ usdOpen: false, usdHandle: '', usdError: '',};let _alive = true;@@ -308,6 +313,19 @@ export function mountFeesPanel(container, opts = {}) {}s.loading = false;render();+ loadBridge();+ }++ // The Fee Bridge runs on mainnet only. A failure leaves the option hidden+ // rather than blocking the panel, which works without it.+ async function loadBridge() {+ if (network !== 'mainnet') return;+ try {+ const r = await fetch(`/api/fee-bridge/coin?mint=${encodeURIComponent(mint)}`, { credentials: 'include' });+ if (!r.ok) return;+ s.bridge = await r.json();+ render();+ } catch { /* option stays hidden */ }}// Resolve the agent custodial wallet address once, so we know whether to use@@ -448,46 +466,138 @@ export function mountFeesPanel(container, opts = {}) {s.busy = 'Saving split…'; s.actionError = ''; s.actionOk = null; render();try {- if (isAgentCreator()) {- const r = await fetch('/api/pump/fee-sharing-agent', {- method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },- body: JSON.stringify({ ...agentBody(), mint, network, shareholders }),- });- const d = await r.json();- if (!r.ok) throw new Error(d.error_description || d.error || `HTTP ${r.status}`);- s.editing = false;- finishAction('Reward split saved on-chain', d.signatures?.[d.signatures.length - 1]);- } else {- // Connected-wallet creator: create config (if needed) then set shares,- // signing each step in the wallet.- if (!s.wallet) { await connectWallet(); if (!s.wallet) { s.busy = ''; render(); return; } }- if (!s.info?.has_sharing_config) {- s.busy = 'Creating config…'; render();- const cr = await fetch('/api/pump/create-fee-sharing-prep', {- method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },- body: JSON.stringify({ mint, creator_address: creator, wallet_address: s.wallet.address, network }),- });- const cd = await cr.json();- if (!cr.ok) throw new Error(cd.error_description || cd.error || `HTTP ${cr.status}`);- await signSendPrep(cd.tx_base64);- }- s.busy = 'Setting shares…'; render();- const current = (s.info?.sharing_config?.shareholders || []).map((h) => h.address);- const ur = await fetch('/api/pump/update-fee-shares-prep', {+ const sig = await writeSplit(shareholders);+ if (sig === null) { s.busy = ''; render(); return; }+ s.editing = false;+ finishAction('Reward split saved on-chain', sig);+ } catch (e) { failAction(e); }+ }++ // Write a shareholder split on-chain with whichever signer controls the coin.+ // Returns the last signature, or null when the user dismissed the wallet connect.+ async function writeSplit(shareholders) {+ if (isAgentCreator()) {+ const r = await fetch('/api/pump/fee-sharing-agent', {+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ ...agentBody(), mint, network, shareholders }),+ });+ const d = await r.json();+ if (!r.ok) throw new Error(d.error_description || d.error || `HTTP ${r.status}`);+ return d.signatures?.[d.signatures.length - 1];+ } else {+ // Connected-wallet creator: create config (if needed) then set shares,+ // signing each step in the wallet.+ if (!s.wallet) { await connectWallet(); if (!s.wallet) return null; }+ if (!s.info?.has_sharing_config) {+ s.busy = 'Creating config…'; render();+ const cr = await fetch('/api/pump/create-fee-sharing-prep', {method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },- body: JSON.stringify({- mint, wallet_address: s.wallet.address, network,- current_shareholders: current.length ? current : [creator],- new_shareholders: shareholders,- }),+ body: JSON.stringify({ mint, creator_address: creator, wallet_address: s.wallet.address, network }),});- const ud = await ur.json();- if (!ur.ok) throw new Error(ud.error_description || ud.error || `HTTP ${ur.status}`);- const sig = await signSendPrep(ud.tx_base64);- s.editing = false;- finishAction('Reward split saved on-chain', sig);+ const cd = await cr.json();+ if (!cr.ok) throw new Error(cd.error_description || cd.error || `HTTP ${cr.status}`);+ await signSendPrep(cd.tx_base64);}- } catch (e) { failAction(e); }+ s.busy = 'Setting shares…'; render();+ const current = (s.info?.sharing_config?.shareholders || []).map((h) => h.address);+ const ur = await fetch('/api/pump/update-fee-shares-prep', {+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ mint, wallet_address: s.wallet.address, network,+ current_shareholders: current.length ? current : [creator],+ new_shareholders: shareholders,+ }),+ });+ const ud = await ur.json();+ if (!ur.ok) throw new Error(ud.error_description || ud.error || `HTTP ${ur.status}`);+ return signSendPrep(ud.tx_base64);+ }+ }++ // ── Fee Bridge: pay an X account in USDC ────────────────────────────────────++ function parseXHandle(raw) {+ const h = String(raw || '').trim()+ .replace(/^https?:\/\//i, '').replace(/^(?:www\.|mobile\.)?(?:x|twitter)\.com\//i, '')+ .replace(/^@/, '').split(/[/?#]/)[0];+ return /^[A-Za-z0-9_]{1,15}$/.test(h) ? h : null;+ }++ async function registerBridgeHandle(handle) {+ const r = await fetch('/api/fee-bridge/register', {+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ mint, handle }),+ });+ const d = await r.json();+ if (!r.ok) throw new Error(d.error_description || d.error || `HTTP ${r.status}`);+ return d;+ }++ // Route 100% of creator fees to the bridge wallet, then register the handle.+ // A coin whose split already routes to the bridge only needs the registration.+ async function routeToBridge() {+ if (s.busy) return;+ const handle = parseXHandle(s.usdHandle);+ if (!handle) { s.usdError = 'Enter the X handle to pay, like @handle.'; render(); return; }+ const bridgeWallet = s.bridge?.bridge_wallet;+ if (!bridgeWallet) { s.usdError = 'The Fee Bridge is not available right now.'; render(); return; }+ s.usdError = ''; s.actionError = ''; s.actionOk = null;+ try {+ let sig;+ if (!s.bridge.routes_to_bridge) {+ s.busy = 'Routing fees…'; render();+ sig = await writeSplit([{ address: bridgeWallet, share_bps: 10_000 }]);+ if (sig === null) { s.busy = ''; render(); return; }+ }+ s.busy = 'Registering @' + handle + '…'; render();+ const reg = await registerBridgeHandle(handle);+ s.usdOpen = false;+ finishAction(`Creator fees now pay @${reg.handle} in USDC`, sig);+ loadBridge();+ } catch (e) {+ s.busy = '';+ s.usdError = friendlyError(e.message || String(e));+ render();+ loadBridge();+ }+ }++ function renderBridge(info) {+ const b = s.bridge;+ if (!b?.bridge_wallet || info.is_cashback_coin || info.is_holder_reward) return '';+ if (b.registration) {+ return `<div class="fp-note you">Paying <b>@${esc(b.registration.handle)}</b> in USDC through the Fee Bridge.+ ${b.registration.status === 'active' ? '' : ' Fees no longer route to the bridge.'}+ <a href="/fee-bridge?handle=${encodeURIComponent(b.registration.handle)}" target="_blank" rel="noopener">View payouts ↗</a></div>`;+ }+ const canSign = isAgentCreator() || connectedIsCreator();+ // A config still seeded with just the creator can be re-pointed; a real split+ // or a revoked admin cannot, so the option is not offered there.+ const holders = info.sharing_config?.shareholders || [];+ const onlyCreator = holders.length === 1 && holders[0].address === creator;+ const locked = info.has_sharing_config && !b.routes_to_bridge && (info.sharing_config?.admin_revoked || (holders.length && !onlyCreator));+ if (locked || (!b.routes_to_bridge && !info.is_graduated)) return '';+ if (!s.usdOpen && !b.routes_to_bridge) {+ return `<div class="fp-cta" id="fp-usd" role="button" tabindex="0">+ <span class="fp-cta-ic">$</span>+ <div class="fp-cta-b">+ <div class="fp-cta-t">Pay an X account in USDC</div>+ <div class="fp-cta-s">Route creator fees to any X handle. They sign in with X and withdraw dollars, no wallet needed up front.</div>+ </div>+ <span class="fp-cta-arrow">→</span>+ </div>`;+ }+ const busy = !!s.busy;+ return `<div class="fp-deleg">+ <div class="fp-deleg-title">${b.routes_to_bridge ? 'Finish setup: name the X account these fees pay' : 'Pay an X account in USDC'}</div>+ <div class="fp-gh">+ <input id="fp-usd-input" placeholder="@handle" value="${esc(s.usdHandle)}" spellcheck="false" autocomplete="off" />+ <button class="fp-btn primary${busy ? ' busy' : ''}" id="fp-usd-go" ${busy || (!canSign && !b.routes_to_bridge) ? 'disabled' : ''}>${busy ? esc(s.busy) : b.routes_to_bridge ? 'Register' : 'Route fees'}</button>+ </div>+ ${s.usdError ? `<div class="fp-err">${esc(s.usdError)}</div>` : ''}+ <div class="fp-note">100% of creator fees go to the Fee Bridge. Each batch converts to USDC: <b>80%</b> is credited to the handle and <b>20%</b> buys $THREE for the treasury. ${b.routes_to_bridge ? '' : '<b>This fee split is usually permanent</b>, so check the handle before you sign.'}</div>+ ${b.routes_to_bridge ? '' : `<div class="fp-deleg-foot"><button class="fp-btn ghost" id="fp-usd-cancel" ${busy ? 'disabled' : ''}>Cancel</button></div>`}+ </div>`;}// ── GitHub import ─────────────────────────────────────────────────────────────@@ -682,6 +792,7 @@ export function mountFeesPanel(container, opts = {}) {<div class="fp-head"><span class="fp-head-t">Fees & rewards</span>${badge}</div>${renderClaim(info)}${okBlock}${errBlock}+ ${s.editing ? '' : renderBridge(info)}${renderDelegation(info)}${renderSignerHint(info)}</div>`;@@ -839,6 +950,18 @@ export function mountFeesPanel(container, opts = {}) {}q('#fp-connect')?.addEventListener('click', connectWallet);+ // Fee Bridge+ const usd = q('#fp-usd');+ if (usd) {+ const open = () => { s.usdOpen = true; s.usdError = ''; render(); q('#fp-usd-input')?.focus(); };+ usd.addEventListener('click', open);+ usd.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(); } });+ }+ q('#fp-usd-input')?.addEventListener('input', (e) => { s.usdHandle = e.target.value; });+ q('#fp-usd-input')?.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); routeToBridge(); } });+ q('#fp-usd-go')?.addEventListener('click', routeToBridge);+ q('#fp-usd-cancel')?.addEventListener('click', () => { s.usdOpen = false; s.usdError = ''; render(); });+// Editorq('#fp-add')?.addEventListener('click', addRow);q('#fp-cancel')?.addEventListener('click', () => { s.editing = false; s.actionError = ''; render(); });diff --git a/src/fee-bridge.css b/src/fee-bridge.cssnew file mode 100644index 000000000..34315ed19--- /dev/null+++ b/src/fee-bridge.css@@ -0,0 +1,778 @@+/* /fee-bridge: creator fees paid to an X account in USDC.+ Token-driven (public/tokens.css via nav.css); light theme remaps through tokens. */++body {+ margin: 0;+ background: var(--bg-0);+ color: var(--ink);+ font-family: var(--font-body);+ overflow-x: hidden;+}++.fb-shell {+ max-width: 1120px;+ margin: 0 auto;+ padding: calc(var(--nav-h, 64px) + var(--space-6)) var(--space-4) var(--space-8);+ display: flex;+ flex-direction: column;+ gap: var(--space-6);+}++.fb-sr {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+}++/* ── Hero ─────────────────────────────────────────────────────────────────── */++.fb-hero {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ max-width: 780px;+}++.fb-kicker {+ margin: 0;+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: var(--ink-dim);+}++.fb-title {+ margin: 0;+ font-family: var(--font-display);+ font-size: clamp(2rem, 5.2vw, 3.6rem);+ line-height: var(--leading-tight);+ letter-spacing: -0.03em;+ color: var(--ink-bright);+}++.fb-sub {+ margin: 0;+ font-size: var(--text-md);+ line-height: var(--leading-normal);+ color: var(--ink-dim);+ max-width: 640px;+}++.fb-ctas {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2);+ margin-top: var(--space-2);+}++.fb-banner {+ margin-top: var(--space-2);+ padding: var(--space-3) var(--space-4);+ border-radius: var(--radius-md);+ border: 1px solid var(--color-warning);+ background: color-mix(in srgb, var(--color-warning) 10%, transparent);+ color: var(--ink);+ font-size: var(--text-sm);+}+.fb-banner[data-tone='ok'] {+ border-color: var(--color-success);+ background: color-mix(in srgb, var(--color-success) 10%, transparent);+}++/* ── Buttons ──────────────────────────────────────────────────────────────── */++.fb-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: var(--space-2);+ min-height: 40px;+ padding: 0 var(--space-4);+ border-radius: var(--radius-control);+ border: 1px solid var(--stroke-strong);+ background: var(--surface-2);+ color: var(--ink-bright);+ font: inherit;+ font-size: var(--text-sm);+ font-weight: var(--weight-semibold);+ text-decoration: none;+ white-space: nowrap;+ cursor: pointer;+ transition:+ background var(--duration-fast) var(--ease-standard),+ border-color var(--duration-fast) var(--ease-standard),+ transform var(--duration-fast) var(--ease-standard);+}+.fb-btn:hover:not(:disabled) {+ background: var(--surface-3);+ border-color: var(--ink-faint);+}+.fb-btn:active:not(:disabled) {+ transform: translateY(1px);+}+.fb-btn:focus-visible,+.fb-link:focus-visible,+.fb-shell a:focus-visible,+.fb-shell input:focus-visible,+.fb-shell select:focus-visible {+ outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, var(--accent));+ outline-offset: var(--focus-ring-offset, 2px);+}+.fb-btn:disabled {+ opacity: var(--disabled-opacity, 0.5);+ cursor: var(--disabled-cursor, not-allowed);+}+.fb-btn-primary {+ background: var(--ink-bright);+ border-color: var(--ink-bright);+ color: var(--bg-0);+}+.fb-btn-primary:hover:not(:disabled) {+ background: var(--btn-primary-bg-hover, var(--ink));+ border-color: var(--btn-primary-bg-hover, var(--ink));+}+.fb-btn-primary:active:not(:disabled) {+ background: var(--btn-primary-bg-active, var(--ink-dim));+}+.fb-btn-quiet {+ background: transparent;+ border-color: transparent;+ color: var(--ink-dim);+}+.fb-btn-quiet:hover:not(:disabled) {+ color: var(--ink-bright);+ background: var(--surface-1);+}+.fb-btn-sm {+ min-height: 32px;+ padding: 0 var(--space-3);+ font-size: var(--text-xs);+}+.fb-btn-block {+ width: 100%;+}+.fb-btn.is-busy {+ cursor: progress;+}++.fb-link {+ background: none;+ border: 0;+ padding: 0;+ color: inherit;+ font: inherit;+ text-decoration: underline;+ cursor: pointer;+}++/* ── Stats ────────────────────────────────────────────────────────────────── */++.fb-stats {+ display: grid;+ grid-template-columns: repeat(4, minmax(0, 1fr));+ gap: 1px;+ border-radius: var(--radius-card);+ overflow: hidden;+ background: var(--hairline);+ border: 1px solid var(--hairline);+}++.fb-stat {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ padding: var(--space-4);+ background: var(--bg-1);+}++.fb-stat-n {+ font-family: var(--font-display);+ font-size: var(--text-2xl);+ font-variant-numeric: tabular-nums;+ color: var(--ink-bright);+ min-height: 1.2em;+}++.fb-stat-l {+ font-size: var(--text-xs);+ color: var(--ink-dim);+}++[data-skel] {+ border-radius: var(--radius-sm);+ background: linear-gradient(90deg, var(--skeleton-base) 0%, var(--skeleton-sheen) 50%, var(--skeleton-base) 100%);+ background-size: 200% 100%;+ animation: fb-sheen 1.4s linear infinite;+ width: 60%;+}++/* ── Cards ────────────────────────────────────────────────────────────────── */++.fb-grid {+ display: grid;+ grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr);+ gap: var(--space-4);+ align-items: start;+}++.fb-card {+ border-radius: var(--radius-card);+ border: 1px solid var(--stroke);+ background: var(--surface-1);+ padding: var(--space-5);+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ scroll-margin-top: calc(var(--nav-h, 64px) + var(--space-4));+}++.fb-card-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-2);+}++.fb-card h2,+.fb-h2 {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-lg);+ color: var(--ink-bright);+ letter-spacing: -0.01em;+}++.fb-h3 {+ margin: var(--space-3) 0 0;+ font-size: var(--text-sm);+ font-weight: var(--weight-semibold);+ color: var(--ink-bright);+}++.fb-chip {+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ padding: 2px var(--space-2);+ border-radius: var(--radius-pill);+ border: 1px solid var(--stroke-strong);+ color: var(--ink);+}+.fb-chip[data-tone='ok'] {+ border-color: var(--color-success);+ color: var(--color-success);+}+.fb-chip[data-tone='warn'] {+ border-color: var(--color-warning);+ color: var(--color-warning);+}++.fb-claim-body,+.fb-lookup-out {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+}++.fb-lead {+ margin: 0;+ font-size: var(--text-md);+ color: var(--ink);+ line-height: var(--leading-normal);+}++.fb-muted {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--ink-dim);+ line-height: var(--leading-normal);+}+.fb-muted a,+.fb-card a:not(.fb-btn) {+ color: var(--ink-bright);+}++.fb-balance {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ padding: var(--space-4);+ border-radius: var(--radius-md);+ background: var(--bg-1);+ border: 1px solid var(--hairline);+ animation: fb-enter var(--duration-base) var(--ease-emphasized);+}+.fb-balance-n {+ font-family: var(--font-display);+ font-size: clamp(2rem, 4vw, 2.8rem);+ font-variant-numeric: tabular-nums;+ color: var(--ink-bright);+ letter-spacing: -0.02em;+}+.fb-balance-sm .fb-balance-n {+ font-size: var(--text-2xl);+}+.fb-balance-l {+ font-size: var(--text-xs);+ color: var(--ink-dim);+}++.fb-kv {+ margin: 0;+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: var(--space-2);+}+.fb-kv div {+ padding: var(--space-2) var(--space-3);+ border-radius: var(--radius-sm);+ background: var(--surface-2);+}+.fb-kv dt {+ font-size: var(--text-2xs);+ color: var(--ink-dim);+ text-transform: uppercase;+ letter-spacing: 0.06em;+}+.fb-kv dd {+ margin: 2px 0 0;+ font-variant-numeric: tabular-nums;+ color: var(--ink-bright);+ font-size: var(--text-sm);+}++.fb-label,+.fb-form label {+ font-size: var(--text-xs);+ color: var(--ink-dim);+}++.fb-select,+.fb-form input,+.fb-inline-form input {+ min-height: 40px;+ width: 100%;+ box-sizing: border-box;+ padding: 0 var(--space-3);+ border-radius: var(--radius-control);+ border: 1px solid var(--stroke-strong);+ background: var(--bg-1);+ color: var(--ink-bright);+ font: inherit;+ font-size: var(--text-sm);+ transition: border-color var(--duration-fast) var(--ease-standard);+}+.fb-form input,+.fb-inline-form input {+ font-family: var(--font-mono);+}+.fb-select:hover,+.fb-form input:hover,+.fb-inline-form input:hover {+ border-color: var(--ink-faint);+}++.fb-inline-form,+.fb-inline-input {+ display: flex;+ align-items: center;+ gap: var(--space-2);+}+.fb-inline-input {+ gap: 0;+}+.fb-at {+ font-family: var(--font-mono);+ color: var(--ink-faint);+ padding-right: var(--space-1);+}++.fb-note {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-3);+ border-radius: var(--radius-md);+ border: 1px dashed var(--stroke-strong);+ font-size: var(--text-sm);+ color: var(--ink);+}++.fb-ok,+.fb-error {+ padding: var(--space-3);+ border-radius: var(--radius-md);+ font-size: var(--text-sm);+ line-height: var(--leading-normal);+ animation: fb-enter var(--duration-base) var(--ease-emphasized);+}+.fb-ok {+ border: 1px solid var(--color-success);+ background: color-mix(in srgb, var(--color-success) 9%, transparent);+}+.fb-error {+ border: 1px solid var(--color-danger);+ background: color-mix(in srgb, var(--color-danger) 9%, transparent);+ list-style: none;+}+.fb-ok a,+.fb-error a {+ color: var(--ink-bright);+}++.fb-warn {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--color-warning);+ line-height: var(--leading-normal);+}++/* ── How it works ─────────────────────────────────────────────────────────── */++.fb-how {+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+}++.fb-steps {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: var(--space-4);+}+.fb-steps li {+ padding: var(--space-4);+ border-radius: var(--radius-card);+ border: 1px solid var(--hairline);+ background: var(--bg-1);+ transition: border-color var(--duration-fast) var(--ease-standard), transform var(--duration-base) var(--ease-standard);+}+.fb-steps li:hover {+ border-color: var(--stroke-strong);+ transform: translateY(-2px);+}+.fb-steps h3 {+ margin: var(--space-2) 0 var(--space-1);+ font-size: var(--text-base);+ color: var(--ink-bright);+}+.fb-steps p {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--ink-dim);+ line-height: var(--leading-normal);+}+.fb-step-n {+ display: inline-grid;+ place-items: center;+ width: 28px;+ height: 28px;+ border-radius: var(--radius-full);+ border: 1px solid var(--stroke-strong);+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink-bright);+}++.fb-split {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+}+.fb-split-bar {+ display: flex;+ height: 12px;+ border-radius: var(--radius-pill);+ overflow: hidden;+ background: var(--surface-2);+}+.fb-split-a,+.fb-split-b {+ display: block;+ width: var(--w);+ transition: width var(--duration-slow) var(--ease-emphasized);+}+.fb-split-a {+ background: var(--ink-bright);+}+.fb-split-b {+ background: rgb(var(--gold-rgb));+}+.fb-split-legend {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2) var(--space-5);+ font-size: var(--text-sm);+ color: var(--ink-dim);+}+.fb-split-legend b {+ color: var(--ink-bright);+}+.fb-dot {+ display: inline-block;+ width: 8px;+ height: 8px;+ border-radius: var(--radius-full);+ margin-right: var(--space-1);+ vertical-align: middle;+}+.fb-dot-a {+ background: var(--ink-bright);+}+.fb-dot-b {+ background: rgb(var(--gold-rgb));+}++/* ── Route ────────────────────────────────────────────────────────────────── */++.fb-route-grid {+ display: grid;+ grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr);+ gap: var(--space-5);+}+.fb-route-grid .fb-h3:first-child {+ margin-top: 0;+}++.fb-list {+ margin: var(--space-2) 0;+ padding-left: var(--space-5);+ font-size: var(--text-sm);+ color: var(--ink-dim);+ line-height: var(--leading-normal);+}++.fb-wallet-copy {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ margin: var(--space-2) 0;+ padding: var(--space-2) var(--space-3);+ border-radius: var(--radius-md);+ background: var(--bg-1);+ border: 1px solid var(--hairline);+}+.fb-addr {+ flex: 1;+ min-width: 0;+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink-bright);+ overflow-wrap: anywhere;+}++.fb-form {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-4);+ border-radius: var(--radius-md);+ background: var(--bg-1);+ border: 1px solid var(--hairline);+ align-self: start;+}+.fb-form .fb-btn {+ margin-top: var(--space-2);+}++/* ── Ledger rows ──────────────────────────────────────────────────────────── */++.fb-ledger {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: var(--space-5);+}+.fb-ledger-col {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+}++.fb-rows {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+}+.fb-rows .fb-skel {+ height: 44px;+}++.fb-row {+ display: flex;+ align-items: center;+ gap: var(--space-3);+ padding: var(--space-2) var(--space-3);+ min-height: 44px;+ box-sizing: border-box;+ border-radius: var(--radius-sm);+ border: 1px solid var(--hairline);+ background: var(--bg-1);+ font-size: var(--text-sm);+ animation: fb-enter var(--duration-base) var(--ease-emphasized);+ transition: border-color var(--duration-fast) var(--ease-standard);+}+.fb-row:hover {+ border-color: var(--stroke-strong);+}+.fb-row.is-off {+ opacity: 0.6;+}+.fb-rows-tight .fb-row {+ min-height: 38px;+}+.fb-row-main {+ font-weight: var(--weight-semibold);+ color: var(--ink-bright);+ text-decoration: none;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.fb-row-main:hover {+ text-decoration: underline;+}+.fb-row-to {+ flex: 1;+ min-width: 0;+ color: var(--ink-dim);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.fb-row-to a {+ color: var(--ink);+}+.fb-row-amt {+ margin-left: auto;+ font-variant-numeric: tabular-nums;+ color: var(--ink-bright);+}+.fb-row-meta {+ font-size: var(--text-xs);+ color: var(--ink-dim);+ text-decoration: none;+ white-space: nowrap;+}+.fb-row-meta:hover {+ color: var(--ink-bright);+}+.fb-tag,+.fb-status {+ font-size: var(--text-2xs);+ font-family: var(--font-mono);+ text-transform: uppercase;+ letter-spacing: 0.05em;+ padding: 1px var(--space-2);+ border-radius: var(--radius-pill);+ border: 1px solid var(--stroke-strong);+ color: var(--ink-dim);+}+.fb-status[data-status='confirmed'] {+ border-color: var(--color-success);+ color: var(--color-success);+}+.fb-status[data-status='failed'] {+ border-color: var(--color-danger);+ color: var(--color-danger);+}++.fb-empty {+ padding: var(--space-4);+ border-radius: var(--radius-md);+ border: 1px dashed var(--stroke-strong);+ font-size: var(--text-sm);+ color: var(--ink-dim);+}+.fb-empty a {+ color: var(--ink-bright);+}++/* ── Skeletons + motion ───────────────────────────────────────────────────── */++.fb-skel {+ height: 16px;+ border-radius: var(--skeleton-radius, var(--radius-sm));+ background: linear-gradient(90deg, var(--skeleton-base) 0%, var(--skeleton-sheen) 50%, var(--skeleton-base) 100%);+ background-size: 200% 100%;+ animation: fb-sheen 1.4s linear infinite;+ list-style: none;+}+.fb-skel-lg {+ height: 72px;+}+.fb-skel-sm {+ width: 50%;+}++@keyframes fb-sheen {+ to {+ background-position: -200% 0;+ }+}++@keyframes fb-enter {+ from {+ opacity: 0;+ transform: translateY(4px);+ }+ to {+ opacity: 1;+ transform: none;+ }+}++@media (prefers-reduced-motion: reduce) {+ .fb-skel,+ [data-skel],+ .fb-row,+ .fb-balance,+ .fb-ok,+ .fb-error {+ animation: none;+ }+ .fb-steps li:hover {+ transform: none;+ }+}++/* ── Responsive ───────────────────────────────────────────────────────────── */++@media (max-width: 900px) {+ .fb-grid,+ .fb-route-grid,+ .fb-ledger {+ grid-template-columns: minmax(0, 1fr);+ }+ .fb-steps {+ grid-template-columns: minmax(0, 1fr);+ }+ .fb-stats {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+}++@media (max-width: 480px) {+ .fb-card {+ padding: var(--space-4);+ }+ .fb-kv {+ grid-template-columns: minmax(0, 1fr);+ }+ .fb-row-to {+ display: none;+ }+ .fb-stat-n {+ font-size: var(--text-xl);+ }+}diff --git a/src/fee-bridge.js b/src/fee-bridge.jsnew file mode 100644index 000000000..e3f19210a--- /dev/null+++ b/src/fee-bridge.js@@ -0,0 +1,459 @@+/**+ * /fee-bridge: a coin's creator fees, paid to an X account in USDC.+ *+ * Data flow (all real, see api/fee-bridge/[action].js):+ * GET /api/fee-bridge/stats totals, config, latest payouts+ * GET /api/fee-bridge/coins coins routing fees to the bridge+ * GET /api/fee-bridge/me the signed-in user's handle, balance, wallets+ * GET /api/fee-bridge/recipient?handle any handle's public balance+ * POST /api/fee-bridge/register register a routed coin to a handle+ * POST /api/fee-bridge/withdraw pay the signed-in user's balance+ * POST /api/auth/wallets/nonce-solana + link-solana link a payout wallet (SIWS)+ * GET /api/auth/x/connect?scope=read&return_to=/fee-bridge prove the handle+ */++const $ = (id) => document.getElementById(id);++const esc = (s) =>+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);++const usd = (atomics) => {+ const n = Number(BigInt(atomics ?? 0)) / 1e6;+ return n.toLocaleString('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2 });+};+const shortAddr = (a) => (a && a.length > 10 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a || '');+const solscanTx = (sig) => `https://solscan.io/tx/${encodeURIComponent(sig)}`;+const HANDLE_RE = /^[A-Za-z0-9_]{1,15}$/;++function parseHandle(raw) {+ let s = String(raw || '').trim();+ s = s.replace(/^https?:\/\//i, '').replace(/^(?:www\.|mobile\.)?(?:x|twitter)\.com\//i, '').replace(/^@/, '').split(/[/?#]/)[0];+ return HANDLE_RE.test(s) ? s : null;+}++function timeAgo(iso) {+ if (!iso) return '';+ const s = Math.max(1, Math.round((Date.now() - new Date(iso).getTime()) / 1000));+ if (s < 60) return `${s}s ago`;+ if (s < 3600) return `${Math.round(s / 60)}m ago`;+ if (s < 86400) return `${Math.round(s / 3600)}h ago`;+ return `${Math.round(s / 86400)}d ago`;+}++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,+ });+ let data = null;+ try {+ data = await res.json();+ } catch {+ data = null;+ }+ if (!res.ok) {+ const err = new Error(data?.error_description || `Request failed (${res.status})`);+ err.status = res.status;+ err.code = data?.error;+ err.body = data;+ throw err;+ }+ return data;+}++const state = { config: null, me: null, busy: false };++// ── Stats + ledger ──────────────────────────────────────────────────────────++function setStat(id, text) {+ const el = $(id);+ el.textContent = text;+ el.removeAttribute('data-skel');+}++function renderConfig(config) {+ state.config = config;+ const addr = $('fb-bridge-addr');+ const copy = $('fb-copy-addr');+ if (config.bridge_wallet) {+ addr.textContent = config.bridge_wallet;+ copy.disabled = false;+ } else {+ addr.textContent = 'Bridge wallet not configured on this deployment';+ }+ const a = config.recipient_bps / 100;+ const b = config.buyback_bps / 100;+ $('fb-split-a').style.setProperty('--w', `${a}%`);+ $('fb-split-b').style.setProperty('--w', `${b}%`);+ $('fb-split-a-l').textContent = `${a}%`;+ $('fb-split-b-l').textContent = `${b}%`;++ const banner = $('fb-banner');+ if (!config.enabled && !banner.dataset.status) {+ banner.dataset.status = 'shown';+ const status = config.bridge_wallet+ ? 'Payouts are paused right now. Balances keep accruing and are safe; withdrawals reopen shortly.'+ : 'The Fee Bridge is not live on this deployment yet. Nothing below can be routed or withdrawn until it is.';+ // Keep an X-connect outcome that is already showing, and add the status after it.+ banner.textContent = banner.hidden ? status : `${banner.textContent} ${status}`;+ banner.dataset.tone = 'warn';+ banner.hidden = false;+ }+}++function renderPayouts(rows) {+ const ul = $('fb-payouts');+ if (!rows.length) {+ ul.innerHTML = `<li class="fb-empty">No payouts yet. The first one lands here the moment a recipient withdraws.</li>`;+ return;+ }+ ul.innerHTML = rows+ .map(+ (p) => `<li class="fb-row">+ <a class="fb-row-main" href="https://x.com/${esc(p.handle)}" target="_blank" rel="noopener">@${esc(p.handle)}</a>+ <span class="fb-row-amt">${usd(p.usdc_atomics)}</span>+ <a class="fb-row-meta" href="${solscanTx(p.signature)}" target="_blank" rel="noopener" title="View transaction">${esc(timeAgo(p.confirmed_at))} ↗</a>+ </li>`,+ )+ .join('');+}++function coinLabel(c) {+ return c.symbol ? `$${esc(c.symbol)}` : esc(shortAddr(c.mint));+}++function renderCoinRows(ul, coins, emptyText) {+ if (!coins.length) {+ ul.innerHTML = `<li class="fb-empty">${emptyText}</li>`;+ return;+ }+ ul.innerHTML = coins+ .map(+ (c) => `<li class="fb-row${c.status === 'active' ? '' : ' is-off'}">+ <a class="fb-row-main" href="/launches/${esc(c.mint)}">${coinLabel(c)}</a>+ <span class="fb-row-to">to <a href="https://x.com/${esc(c.handle)}" target="_blank" rel="noopener">@${esc(c.handle)}</a></span>+ <span class="fb-row-amt">${usd(c.credited_usdc_atomics)}</span>+ ${c.status === 'active' ? '' : '<span class="fb-tag">no longer routed</span>'}+ </li>`,+ )+ .join('');+}++async function loadPublic() {+ try {+ const [stats, coins] = await Promise.all([api('/api/fee-bridge/stats'), api('/api/fee-bridge/coins?limit=25')]);+ renderConfig(stats.config);+ setStat('fb-stat-paid', usd(stats.totals.paid_usdc_atomics));+ setStat('fb-stat-unpaid', usd(stats.totals.unpaid_usdc_atomics));+ setStat('fb-stat-coins', String(stats.totals.coins));+ setStat('fb-stat-buyback', usd(stats.totals.buyback_usdc_atomics));+ renderPayouts(stats.recent_payouts);+ renderCoinRows($('fb-coins'), coins.coins, 'No coins route fees here yet. <a href="#route">Be the first</a>.');+ } catch (e) {+ for (const id of ['fb-stat-paid', 'fb-stat-unpaid', 'fb-stat-coins', 'fb-stat-buyback']) setStat(id, '-');+ const msg = `<li class="fb-error">Could not load the ledger (${esc(e.message)}). <button class="fb-link" data-retry>Retry</button></li>`;+ $('fb-payouts').innerHTML = msg;+ $('fb-coins').innerHTML = msg;+ document.querySelectorAll('[data-retry]').forEach((b) => b.addEventListener('click', loadPublic, { once: true }));+ }+}++// ── Claim panel ─────────────────────────────────────────────────────────────++function claimChip(text, tone) {+ const chip = $('fb-claim-chip');+ chip.hidden = !text;+ chip.textContent = text || '';+ chip.dataset.tone = tone || '';+}++function renderClaim(html) {+ $('fb-claim-body').innerHTML = html;+}++function connectXHref() {+ return '/api/auth/x/connect?scope=read&return_to=%2Ffee-bridge';+}++function renderPayoutHistory(payouts) {+ if (!payouts.length) return '';+ return `<h3 class="fb-h3">Your payouts</h3><ul class="fb-rows fb-rows-tight">${payouts+ .map(+ (p) => `<li class="fb-row">+ <span class="fb-row-main">${usd(p.usdc_atomics)}</span>+ <span class="fb-row-to">to ${esc(shortAddr(p.wallet))}</span>+ <span class="fb-status" data-status="${esc(p.status)}">${esc(p.status)}</span>+ ${p.signature ? `<a class="fb-row-meta" href="${solscanTx(p.signature)}" target="_blank" rel="noopener">${esc(timeAgo(p.created_at))} ↗</a>` : `<span class="fb-row-meta">${esc(timeAgo(p.created_at))}</span>`}+ </li>`,+ )+ .join('')}</ul>`;+}++function renderMe(me) {+ state.me = me;+ const cfg = me.config;++ if (!me.x_connected) {+ claimChip('', '');+ renderClaim(`+ <p class="fb-lead">Fees addressed to your X handle wait here until you claim them.</p>+ <a class="fb-btn fb-btn-primary fb-btn-x" href="${connectXHref()}">Connect X to see your balance</a>+ <p class="fb-muted">Read-only access. The bridge only needs to know which handle is yours; it never posts.</p>`);+ return;+ }++ if (me.handle_conflict) {+ claimChip('Handle already claimed', 'warn');+ renderClaim(`+ <p class="fb-lead">@${esc(me.x_username)} was claimed by a different X account.</p>+ <p class="fb-muted">Balances bind to the X account that first withdrew them, so a renamed handle cannot be claimed by its new owner. If this is your original account, reconnect it on X.</p>+ <a class="fb-btn" href="${connectXHref()}">Reconnect X</a>`);+ return;+ }++ const bal = me.balance;+ const unpaid = BigInt(bal.unpaid_usdc_atomics);+ const minWithdraw = BigInt(Math.round(cfg.withdraw_min_usd * 1e6));+ const canWithdraw = cfg.enabled && unpaid >= minWithdraw && me.wallets.length > 0;+ claimChip(`@${me.handle}`, 'ok');++ const walletBlock = me.wallets.length+ ? `<label class="fb-label" for="fb-wallet">Pay to</label>+ <select id="fb-wallet" class="fb-select">${me.wallets+ .map((w) => `<option value="${esc(w.address)}">${esc(shortAddr(w.address))}${w.primary ? ' (primary)' : ''}</option>`)+ .join('')}</select>`+ : `<div class="fb-note">Link a Solana wallet to receive USDC. Your wallet signs a message; no funds move.+ <button class="fb-btn fb-btn-sm" id="fb-link-wallet" type="button">Link Solana wallet</button></div>`;++ const hint = !cfg.enabled+ ? 'Withdrawals are paused right now. Your balance is safe.'+ : unpaid === 0n+ ? me.coins.length+ ? 'Nothing to withdraw yet. Fees convert to USDC once a coin has earned at least a few dollars.'+ : 'No coin pays this handle yet. Share the bridge with a creator, or route one of your own coins below.'+ : unpaid < minWithdraw+ ? `Withdrawals start at ${usd(minWithdraw)}.`+ : `Balances over ${usd(BigInt(Math.round(cfg.auto_payout_usd * 1e6)))} are sent to your primary wallet automatically.`;++ renderClaim(`+ <div class="fb-balance">+ <span class="fb-balance-n">${usd(unpaid)}</span>+ <span class="fb-balance-l">ready to withdraw, USDC on Solana</span>+ </div>+ <dl class="fb-kv">+ <div><dt>Earned</dt><dd>${usd(bal.credited_usdc_atomics)}</dd></div>+ <div><dt>Paid out</dt><dd>${usd(bal.paid_usdc_atomics)}</dd></div>+ <div><dt>Coins paying you</dt><dd>${me.coins.length}</dd></div>+ </dl>+ ${walletBlock}+ <button class="fb-btn fb-btn-primary fb-btn-block" id="fb-withdraw" type="button" ${canWithdraw ? '' : 'disabled'}>Withdraw ${usd(unpaid)}</button>+ <p class="fb-muted" id="fb-claim-hint">${esc(hint)}</p>+ <div id="fb-claim-out" aria-live="polite"></div>+ ${me.coins.length ? `<h3 class="fb-h3">Coins paying you</h3><ul class="fb-rows fb-rows-tight" id="fb-my-coins"></ul>` : ''}+ ${renderPayoutHistory(me.payouts)}`);++ if (me.coins.length) renderCoinRows($('fb-my-coins'), me.coins, '');+ $('fb-withdraw')?.addEventListener('click', withdraw);+ $('fb-link-wallet')?.addEventListener('click', linkWallet);+}++async function loadMe() {+ try {+ renderMe(await api('/api/fee-bridge/me'));+ } catch (e) {+ if (e.status === 401) {+ claimChip('', '');+ renderClaim(`+ <p class="fb-lead">Sign in, connect your X account, and anything addressed to your handle is yours to withdraw.</p>+ <a class="fb-btn fb-btn-primary" href="/login?next=${encodeURIComponent('/fee-bridge#claim')}">Sign in to claim</a>`);+ return;+ }+ renderClaim(`<div class="fb-error">Could not load your balance (${esc(e.message)}). <button class="fb-link" id="fb-me-retry">Retry</button></div>`);+ $('fb-me-retry')?.addEventListener('click', loadMe, { once: true });+ }+}++async function withdraw(ev) {+ if (state.busy) return;+ const btn = ev.currentTarget;+ const out = $('fb-claim-out');+ const wallet = $('fb-wallet')?.value;+ state.busy = true;+ btn.disabled = true;+ btn.classList.add('is-busy');+ btn.textContent = 'Sending USDC…';+ out.innerHTML = '';+ try {+ const r = await api('/api/fee-bridge/withdraw', { method: 'POST', body: wallet ? { wallet } : {} });+ out.innerHTML =+ r.status === 'confirmed'+ ? `<div class="fb-ok">Sent ${usd(r.usdc_atomics)} to ${esc(shortAddr(r.wallet))}. <a href="${solscanTx(r.signature)}" target="_blank" rel="noopener">View transaction ↗</a></div>`+ : `<div class="fb-ok">Payout of ${usd(r.usdc_atomics)} submitted and confirming. <a href="${solscanTx(r.signature)}" target="_blank" rel="noopener">Track it ↗</a></div>`;+ state.busy = false;+ await Promise.all([loadMe(), loadPublic()]);+ const again = $('fb-claim-out');+ if (again) again.innerHTML = out.innerHTML;+ } catch (e) {+ state.busy = false;+ btn.disabled = false;+ btn.classList.remove('is-busy');+ btn.textContent = 'Try again';+ out.innerHTML = `<div class="fb-error">${esc(e.message)}</div>`;+ }+}++function solanaProvider() {+ return window.phantom?.solana || window.solana || window.backpack || window.solflare || null;+}++async function linkWallet(ev) {+ const btn = ev.currentTarget;+ const provider = solanaProvider();+ if (!provider) {+ window.open('https://phantom.app/', '_blank', 'noopener');+ return;+ }+ const label = btn.textContent;+ btn.disabled = true;+ btn.textContent = 'Check your wallet…';+ const link = async (takeover) => {+ const res = await provider.connect();+ const address = res?.publicKey?.toString?.() || provider.publicKey?.toString?.();+ if (!address) throw new Error('Your wallet did not return an address.');+ const nonce = await api('/api/auth/wallets/nonce-solana', { method: 'POST', body: { address, chainId: 'mainnet' } });+ const signed = await provider.signMessage(new TextEncoder().encode(nonce.message), 'utf8');+ const signature = btoa(String.fromCharCode(...signed.signature));+ await api('/api/auth/wallets/link-solana', { method: 'POST', body: { message: nonce.message, signature, takeover } });+ };+ try {+ try {+ await link(false);+ } catch (e) {+ if (e?.body?.takeover_available !== true) throw e;+ if (!confirm('That wallet is linked to another three.ws account. Move it to this one?')) throw Object.assign(new Error('cancelled'), { code: 4001 });+ await link(true);+ }+ await loadMe();+ } catch (e) {+ btn.disabled = false;+ btn.textContent = label;+ if (e?.code === 4001 || /reject|denied|cancel/i.test(e?.message || '')) return;+ const out = $('fb-claim-out');+ if (out) out.innerHTML = `<div class="fb-error">${esc(e.message)}</div>`;+ }+}++// ── Lookup ──────────────────────────────────────────────────────────────────++async function lookup(ev) {+ ev.preventDefault();+ const out = $('fb-lookup-out');+ const handle = parseHandle($('fb-lookup-input').value);+ if (!handle) {+ out.innerHTML = `<div class="fb-error">Enter an X handle: letters, digits and underscores, up to 15 characters.</div>`;+ return;+ }+ out.innerHTML = `<div class="fb-skel fb-skel-lg"></div><div class="fb-skel"></div>`;+ try {+ const r = await api(`/api/fee-bridge/recipient?handle=${encodeURIComponent(handle)}`);+ const earned = BigInt(r.credited_usdc_atomics);+ out.innerHTML = `+ <div class="fb-balance fb-balance-sm">+ <span class="fb-balance-n">${usd(r.unpaid_usdc_atomics)}</span>+ <span class="fb-balance-l">waiting for <a href="https://x.com/${esc(r.handle)}" target="_blank" rel="noopener">@${esc(r.handle)}</a></span>+ </div>+ <dl class="fb-kv">+ <div><dt>Earned</dt><dd>${usd(r.credited_usdc_atomics)}</dd></div>+ <div><dt>Paid out</dt><dd>${usd(r.paid_usdc_atomics)}</dd></div>+ <div><dt>Claimed</dt><dd>${r.claimed ? 'Yes' : 'Not yet'}</dd></div>+ </dl>+ ${r.coins.length ? '<ul class="fb-rows fb-rows-tight" id="fb-lookup-coins"></ul>' : `<p class="fb-muted">${earned > 0n ? '' : `No coin routes fees to @${esc(r.handle)} yet.`}</p>`}`;+ if (r.coins.length) renderCoinRows($('fb-lookup-coins'), r.coins, '');+ } catch (e) {+ out.innerHTML = `<div class="fb-error">${esc(e.message)}</div>`;+ }+}++// ── Register ────────────────────────────────────────────────────────────────++async function register(ev) {+ ev.preventDefault();+ const out = $('fb-reg-out');+ const submit = $('fb-reg-submit');+ const mint = $('fb-reg-mint').value.trim();+ const handle = parseHandle($('fb-reg-handle').value);+ if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(mint)) {+ out.innerHTML = `<div class="fb-error">That is not a Solana mint address.</div>`;+ $('fb-reg-mint').focus();+ return;+ }+ if (!handle) {+ out.innerHTML = `<div class="fb-error">Enter the X handle this coin should pay.</div>`;+ $('fb-reg-handle').focus();+ return;+ }+ submit.disabled = true;+ submit.textContent = 'Checking the chain…';+ out.innerHTML = '';+ try {+ const r = await api('/api/fee-bridge/register', { method: 'POST', body: { mint, handle } });+ out.innerHTML = `<div class="fb-ok">${r.created ? 'Registered.' : 'Already registered.'} Fees from this coin now pay <b>@${esc(r.handle)}</b> in USDC. <a href="/launches/${esc(r.mint)}">Open the coin</a></div>`;+ loadPublic();+ } catch (e) {+ out.innerHTML =+ e.status === 401+ ? `<div class="fb-error">Sign in with the account that launched this coin, or that holds its creator wallet. <a href="/login?next=${encodeURIComponent('/fee-bridge#route')}">Sign in</a></div>`+ : `<div class="fb-error">${esc(e.message)}</div>`;+ } finally {+ submit.disabled = false;+ submit.textContent = 'Register coin';+ }+}++// ── Boot ────────────────────────────────────────────────────────────────────++function showConnectOutcome() {+ const params = new URLSearchParams(location.search);+ const x = params.get('x');+ if (!x) return;+ const banner = $('fb-banner');+ const messages = {+ connected: 'X connected. Your balance is below.',+ denied: 'X connection was cancelled. Connect again whenever you are ready.',+ error: 'X did not complete the connection. Try again in a moment.',+ unconfigured: 'X sign-in is not available on this deployment right now.',+ };+ if (messages[x]) {+ banner.hidden = false;+ banner.dataset.tone = x === 'connected' ? 'ok' : 'warn';+ banner.textContent = messages[x];+ }+ params.delete('x');+ history.replaceState(null, '', `${location.pathname}${params.size ? `?${params}` : ''}#claim`);+ $('claim')?.scrollIntoView({ block: 'start' });+}++$('fb-lookup-form').addEventListener('submit', lookup);+$('fb-register').addEventListener('submit', register);+$('fb-copy-addr').addEventListener('click', async (ev) => {+ const btn = ev.currentTarget;+ try {+ await navigator.clipboard.writeText(state.config?.bridge_wallet || '');+ btn.textContent = 'Copied';+ } catch {+ btn.textContent = 'Select and copy';+ }+ setTimeout(() => (btn.textContent = 'Copy'), 1600);+});++const presetHandle = new URLSearchParams(location.search).get('handle');+if (presetHandle && parseHandle(presetHandle)) {+ $('fb-lookup-input').value = parseHandle(presetHandle);+ $('fb-lookup-form').requestSubmit();+}++showConnectOutcome();+loadPublic();+loadMe();diff --git a/tests/fee-bridge-math.test.js b/tests/fee-bridge-math.test.jsnew file mode 100644index 000000000..2e69b8a32--- /dev/null+++ b/tests/fee-bridge-math.test.js@@ -0,0 +1,152 @@+import { describe, it, expect } from 'vitest';++import {+ allocateProRata,+ computeBatchCredits,+ lamportDelta,+ netOfGas,+ parseXHandle,+ payoutDecision,+ splitRecipientBuyback,+ tokenDelta,+} from '../api/_lib/fee-bridge/math.js';++describe('parseXHandle', () => {+ it('accepts bare handles, @handles and profile URLs', () => {+ expect(parseXHandle('three_ws')).toBe('three_ws');+ expect(parseXHandle(' @Three_WS ')).toBe('Three_WS');+ expect(parseXHandle('https://x.com/nirholas')).toBe('nirholas');+ expect(parseXHandle('twitter.com/nirholas/status/123')).toBe('nirholas');+ expect(parseXHandle('https://mobile.twitter.com/nirholas?s=20')).toBe('nirholas');+ });++ it('rejects anything that is not an X handle', () => {+ expect(parseXHandle('')).toBeNull();+ expect(parseXHandle(null)).toBeNull();+ expect(parseXHandle('has space')).toBeNull();+ expect(parseXHandle('sixteen_chars_xx')).toBeNull();+ expect(parseXHandle('dash-name')).toBeNull();+ });+});++describe('splitRecipientBuyback', () => {+ it('splits 80/20 exactly on round amounts', () => {+ expect(splitRecipientBuyback(10_000_000n, 8000)).toEqual({ recipient: 8_000_000n, buyback: 2_000_000n });+ });++ it('floors the recipient so rounding dust goes to the buyback, never over-crediting', () => {+ const { recipient, buyback } = splitRecipientBuyback(7n, 8000);+ expect(recipient).toBe(5n);+ expect(buyback).toBe(2n);+ expect(recipient + buyback).toBe(7n);+ });++ it('clamps bps and ignores negative totals', () => {+ expect(splitRecipientBuyback(100n, 12_000)).toEqual({ recipient: 100n, buyback: 0n });+ expect(splitRecipientBuyback(-5n, 8000)).toEqual({ recipient: 0n, buyback: 0n });+ });+});++describe('netOfGas', () => {+ it('charges gas back and never goes negative', () => {+ expect(netOfGas(1_000_000n, 5_000n)).toBe(995_000n);+ expect(netOfGas(4_000n, 5_000n)).toBe(0n);+ expect(netOfGas(4_000n, -1n)).toBe(4_000n);+ });+});++describe('allocateProRata', () => {+ it('sums to exactly the total with largest-remainder rounding', () => {+ const out = allocateProRata(100n, [+ { key: 'a', weight: 1n },+ { key: 'b', weight: 1n },+ { key: 'c', weight: 1n },+ ]);+ expect([...out.values()].reduce((x, y) => x + y, 0n)).toBe(100n);+ expect(out.get('a')).toBe(34n);+ expect(out.get('b')).toBe(33n);+ expect(out.get('c')).toBe(33n);+ });++ it('gives zero-weight keys nothing and handles an empty pool', () => {+ const out = allocateProRata(50n, [+ { key: 'a', weight: 3n },+ { key: 'z', weight: 0n },+ ]);+ expect(out.get('a')).toBe(50n);+ expect(out.get('z')).toBe(0n);+ expect(allocateProRata(0n, [{ key: 'a', weight: 1n }]).get('a')).toBe(0n);+ });+});++describe('computeBatchCredits', () => {+ it('shares swapped USDC by net SOL, adds USDC inflows at face value, and splits each coin', () => {+ const { credits, recipientTotal, buybackTotal, usdcTotal } = computeBatchCredits({+ coins: [+ { mint: 'MintA', handle_lc: 'alice', sol_net: 3_000_000_000n, usdc_in: 0n },+ { mint: 'MintB', handle_lc: 'bob', sol_net: 1_000_000_000n, usdc_in: 0n },+ { mint: 'MintC', handle_lc: 'carol', sol_net: 0n, usdc_in: 10_000_000n },+ ],+ usdcFromSol: 600_000_000n,+ recipientBps: 8000,+ });+ const by = Object.fromEntries(credits.map((c) => [c.mint, c.usdc_atomics]));+ expect(by.MintA).toBe(360_000_000n);+ expect(by.MintB).toBe(120_000_000n);+ expect(by.MintC).toBe(8_000_000n);+ expect(usdcTotal).toBe(610_000_000n);+ expect(recipientTotal + buybackTotal).toBe(610_000_000n);+ expect(buybackTotal).toBe(122_000_000n);+ });++ it('never credits more than the batch produced', () => {+ const { recipientTotal, buybackTotal } = computeBatchCredits({+ coins: [+ { mint: 'A', handle_lc: 'a', sol_net: 1n, usdc_in: 0n },+ { mint: 'B', handle_lc: 'b', sol_net: 1n, usdc_in: 0n },+ { mint: 'C', handle_lc: 'c', sol_net: 1n, usdc_in: 0n },+ ],+ usdcFromSol: 1_000_001n,+ recipientBps: 8000,+ });+ expect(recipientTotal + buybackTotal).toBe(1_000_001n);+ expect(recipientTotal).toBeLessThanOrEqual(800_001n);+ });+});++describe('payoutDecision', () => {+ const floors = { autoFloor: 5_000_000n, withdrawFloor: 1_000_000n };++ it('auto-pays only past the auto floor', () => {+ expect(payoutDecision({ balance: 4_999_999n, trigger: 'auto', ...floors })).toMatchObject({ pay: false, reason: 'below_floor' });+ expect(payoutDecision({ balance: 5_000_000n, trigger: 'auto', ...floors })).toEqual({ pay: true, amount: 5_000_000n });+ });++ it('lets a manual withdrawal go from the lower floor', () => {+ expect(payoutDecision({ balance: 1_500_000n, trigger: 'withdraw', ...floors })).toEqual({ pay: true, amount: 1_500_000n });+ expect(payoutDecision({ balance: 0n, trigger: 'withdraw', ...floors })).toMatchObject({ pay: false, reason: 'no_balance' });+ });+});++describe('transaction deltas', () => {+ it('reads an owner token delta, treating a new account as starting from zero', () => {+ const meta = {+ preTokenBalances: [{ owner: 'bridge', mint: 'usdc', uiTokenAmount: { amount: '100' } }],+ postTokenBalances: [+ { owner: 'bridge', mint: 'usdc', uiTokenAmount: { amount: '350' } },+ { owner: 'bridge', mint: 'three', uiTokenAmount: { amount: '9' } },+ { owner: 'other', mint: 'usdc', uiTokenAmount: { amount: '999' } },+ ],+ };+ expect(tokenDelta(meta, 'bridge', 'usdc')).toBe(250n);+ expect(tokenDelta(meta, 'bridge', 'three')).toBe(9n);+ expect(tokenDelta(null, 'bridge', 'usdc')).toBe(0n);+ });++ it('adds the fee back for the fee payer so a crank inflow is not understated', () => {+ const meta = { preBalances: [1_000_000, 5], postBalances: [1_495_000, 5], fee: 5_000 };+ expect(lamportDelta(meta, 0, true)).toBe(500_000n);+ expect(lamportDelta(meta, 0, false)).toBe(495_000n);+ expect(lamportDelta(meta, -1, true)).toBe(0n);+ });+});diff --git a/vercel.json b/vercel.jsonindex 755f25ebf..ee43d8bfa 100644--- a/vercel.json+++ b/vercel.json@@ -37,7 +37,7 @@"api/tournaments/[id]/[action].js": {"maxDuration": 120},- "{api/agents/networth,api/avatars/from-forge,api/pay/execute,api/pay/simulate,api/cron/launcher-claimer,api/seed/synthesize,api/cron/x402-ring-tick}.js": {+ "{api/agents/networth,api/avatars/from-forge,api/pay/execute,api/pay/simulate,api/cron/launcher-claimer,api/cron/fee-bridge,api/seed/synthesize,api/cron/x402-ring-tick}.js": {"maxDuration": 60},"{api/club/tips-stream,api/feed-stream,api/pump/trades-stream,api/oracle/stream,api/oracle/action-stream,api/sniper/stream,api/sniper/radar-stream,api/agent-screen-stream}.js": {@@ -4876,6 +4876,14 @@"src": "/contributors/","dest": "/contributors.html"},+ {+ "src": "/fee-bridge",+ "dest": "/fee-bridge.html"+ },+ {+ "src": "/fee-bridge/",+ "dest": "/fee-bridge.html"+ },{"src": "/bazaar","dest": "/bazaar.html"@@ -5024,6 +5032,10 @@"src": "/api/three-token/([^/]+)","dest": "/api/three-token/[action]?action=$1"},+ {+ "src": "/api/fee-bridge/([^/]+)",+ "dest": "/api/fee-bridge/[action]?action=$1"+ },{"src": "/api/token/([^/]+)","dest": "/api/token/[action]?action=$1"@@ -6487,6 +6499,10 @@"path": "/api/cron/launcher-claimer","schedule": "*/5 * * * *"},+ {+ "path": "/api/cron/fee-bridge",+ "schedule": "*/10 * * * *"+ },{"path": "/api/cron/solana-agents-crawl","schedule": "*/30 * * * *"diff --git a/vite.config.js b/vite.config.jsindex c483ecce3..815fa660b 100644--- a/vite.config.js+++ b/vite.config.js@@ -919,6 +919,7 @@ const appConfig = {'launch-week': resolve(__dirname, 'pages/three-ws-launch-week.html'),community: resolve(__dirname, 'pages/community.html'),contributors: resolve(__dirname, 'pages/contributors.html'),+ 'fee-bridge': resolve(__dirname, 'pages/fee-bridge.html'),profile: resolve(__dirname, 'pages/profile.html'),feed: resolve(__dirname, 'pages/feed.html'),'threews-claim': resolve(__dirname, 'pages/threews-claim.html'),