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
Programmatic $THREE micro-buy: x402 service, per-minute loop, ledger migration
nirholasd1e4b64e3915
diff --git a/api/_lib/migrations/20260717233000_three_microbuy.sql b/api/_lib/migrations/20260717233000_three_microbuy.sqlnew file mode 100644index 000000000..6ac23e54d--- /dev/null+++ b/api/_lib/migrations/20260717233000_three_microbuy.sql@@ -0,0 +1,48 @@+-- Programmatic $THREE micro-buy ledger.+--+-- The x402 micro-buy service (api/x402/three-buy.js), driven by the per-minute+-- loop (api/cron/three-buy-loop.js), fires many tiny, real USDC->$THREE market+-- buys on Jupiter so the platform shows continuous, verifiable buy pressure on+-- $THREE. It is the high-frequency, small-ticket sibling of the daily buyback+-- (three_buyback_runs). BUY-ONLY -- nothing here sells $THREE; bought tokens are+-- swept to the treasury.+--+-- One immutable row per settled call. Confirmed/pending rows are the DB fallback+-- for the UTC-daily spend cap (the Redis counter is the fast path); skipped and+-- failed rows record why a call did not buy (never a silent no-op).++begin;++create table if not exists three_microbuy_runs (+ id uuid primary key default gen_random_uuid(),+ -- 'confirmed' | 'pending' | 'skipped' | 'failed'+ status text not null,+ -- machine-readable skip/fail reason: 'disabled' | 'not_configured'+ -- | 'insufficient_usdc' | 'treasury_unavailable' | 'no_quote'+ -- | 'daily_cap_reached' | 'swap_failed' | 'tx_reverted' | 'plan_failed'+ reason text,+ -- USDC deployed into this buy (atomics, 6dp). Counted toward the daily cap for+ -- confirmed + pending rows.+ usdc_spent_atomics bigint not null default 0,+ -- $THREE received (atomics). Zero for pending buys not yet confirmed.+ three_bought_atomics bigint not null default 0,+ -- Effective execution price (USD per whole $THREE) from the quote.+ price_usd numeric,+ slippage_bps integer,+ -- Jupiter buy tx signature.+ buy_signature text,+ created_at timestamptz not null default now()+);++create index if not exists three_microbuy_runs_created+ on three_microbuy_runs (created_at desc);++create index if not exists three_microbuy_runs_status_created+ on three_microbuy_runs (status, created_at desc);++-- Powers the daily-spend DB fallback sum (status + day range).+create index if not exists three_microbuy_runs_day+ on three_microbuy_runs (created_at)+ where status in ('confirmed', 'pending');++commit;diff --git a/api/_lib/token/microbuy.js b/api/_lib/token/microbuy.jsnew file mode 100644index 000000000..de297bf3a--- /dev/null+++ b/api/_lib/token/microbuy.js@@ -0,0 +1,374 @@+// Programmatic $THREE micro-buy primitive — the buy-only engine behind the x402+// micro-buy loop.+//+// WHAT IT IS. A small, fixed-size market buy of $THREE on Jupiter (USDC → $THREE,+// ExactIn), executed once per settled x402 call so the platform can run a high+// cadence of tiny, continuous buys (target ~60/min) that show up as constant,+// real on-chain buy pressure. It reuses the same Jupiter client (jupiter.js) and+// treasury policy (config.js) as the daily buyback (buyback.js); it is the+// high-frequency, small-ticket sibling of that low-frequency, large-ticket lane.+//+// BUY-ONLY. This engine never sells $THREE. It quotes USDC→$THREE, buys, and lets+// the tokens accrue in the micro-buy wallet; the treasury sweep (buyback.sweep-+// StrandedThree) is the only thing that moves them, and it moves them TO the+// treasury, never back to USDC. There is no sell path.+//+// CUSTODY. Buys are funded by the micro-buy wallet's own USDC balance+// (THREE_MICROBUY_SECRET_KEY_B64, or the shared buyback wallet+// THREE_BUYBACK_SECRET_KEY_B64 when the dedicated key is unset). The x402 toll the+// caller pays for each buy routes to the ring treasury (X402_PAY_TO_SOLANA) exactly+// like every other ring endpoint — it is NOT the buy funding, so the two money+// streams stay independent and auditable.+//+// SAFETY. Every buy is bounded by a per-buy size cap AND a UTC-daily USD ceiling+// enforced atomically (Redis reserve-before-execute, DB-sum fallback) so a flood+// of calls — from the loop or a direct payer — can never drain the wallet or burn+// unbounded SOL beyond the day's cap. Execution is gated by THREE_MICROBUY_ENABLED;+// until an operator funds the wallet and opts in, the engine is a recorded no-op.++import {+ createAssociatedTokenAccountIdempotentInstruction,+ createTransferInstruction,+ getAssociatedTokenAddressSync,+} from '@solana/spl-token';++import { getConnection, solanaPubkey } from '../pump.js';+import { confirmOrThrow } from '../solana/confirm.js';+import { submitProtected } from '../execution-engine.js';+import { getRedis } from '../redis.js';+import { sql } from '../db.js';+import { SOLANA_USDC_MINT } from '../../payments/_config.js';+import { TOKEN_MINT, TOKEN_DECIMALS, treasuryWallet, treasuryWalletOrNull } from './config.js';+import { jupiterQuote, jupiterSwapTx } from './jupiter.js';+import {+ envUsd,+ envSlippageBps,+ usdToUsdcAtomics,+ usdcAtomicsToUsd,+ atomicsToTokens,+} from './buyback-math.js';++const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';++// ── policy knobs (env, with safe defaults) ──────────────────────────────────++/** Execution gate. A run is a recorded no-op unless this is truthy. */+export function isEnabled() {+ return ['1', 'true', 'yes', 'on'].includes(+ String(process.env.THREE_MICROBUY_ENABLED || '').toLowerCase(),+ );+}++/** USD spent per single micro-buy (default $0.01). Bounded to a sane band. */+export function buyUsd() {+ const v = envUsd(process.env.THREE_MICROBUY_USD, 0.01);+ // Never let a fat-fingered env turn a "micro" buy into a wallet-drainer.+ return Math.min(v, 5);+}++/** Per-buy size in USDC atomics (6dp). */+export function buyUsdcAtomics() {+ return usdToUsdcAtomics(buyUsd());+}++/** UTC-daily ceiling on total micro-buy USD (default $50). */+export function dailyCapUsd() {+ return envUsd(process.env.THREE_MICROBUY_DAILY_CAP_USD, 50);+}++/** Jupiter slippage tolerance in bps (default 3%). */+export function slippageBps() {+ return envSlippageBps(process.env.THREE_MICROBUY_SLIPPAGE_BPS, 300);+}++/** Seconds to wait for buy confirmation before returning `pending` (default 12). */+function confirmTimeoutMs() {+ const n = Number(process.env.THREE_MICROBUY_CONFIRM_TIMEOUT_MS);+ return Number.isFinite(n) && n >= 1_000 && n <= 60_000 ? n : 12_000;+}++/**+ * Load the micro-buy signer. Prefers a DEDICATED key so micro-buys and the daily+ * buyback don't fight over one wallet's USDC; falls back to the buyback wallet so+ * a single funded wallet powers both lanes out of the box. Null when neither is set.+ */+export async function loadMicrobuySigner() {+ const b64 =+ process.env.THREE_MICROBUY_SECRET_KEY_B64 || process.env.THREE_BUYBACK_SECRET_KEY_B64;+ if (!b64) return null;+ const { Keypair } = await import('@solana/web3.js');+ const raw = Buffer.from(b64, 'base64');+ if (raw.byteLength !== 64) {+ throw Object.assign(+ new Error(`micro-buy signer: expected 64-byte secret key, got ${raw.byteLength}`),+ { code: 'bad_signer' },+ );+ }+ return Keypair.fromSecretKey(raw);+}++// ── daily spend ceiling (atomic reserve-before-execute) ─────────────────────++const utcDay = () => new Date().toISOString().slice(0, 10); // YYYY-MM-DD (UTC)+const dailyKey = () => `three:microbuy:daily:${utcDay()}`;++/**+ * DB fallback for today's micro-buy spend when Redis is unavailable — sums the+ * confirmed/pending rows so the cap still holds (best-effort; the Redis counter is+ * the fast path). Returns atomics.+ */+async function dbDailySpentAtomics() {+ try {+ const rows = await sql`+ SELECT COALESCE(SUM(usdc_spent_atomics), 0)::bigint AS spent+ FROM three_microbuy_runs+ WHERE status IN ('confirmed', 'pending') AND created_at >= date_trunc('day', now())+ `;+ return BigInt(rows[0]?.spent || 0);+ } catch {+ return 0n;+ }+}++/**+ * Atomically reserve `atomics` of today's budget. Returns { ok, dailySpentAtomics,+ * dailyCapAtomics }. When the reservation would cross the daily cap it is rolled+ * back and ok:false is returned, so the caller never buys past the ceiling. Redis+ * is the fast atomic path; if it is down we fall back to a (racy) DB sum so the cap+ * degrades to best-effort rather than failing open.+ */+export async function reserveDailySpend(atomics) {+ const capAtomics = usdToUsdcAtomics(dailyCapUsd());+ const need = BigInt(atomics);+ const redis = getRedis();+ if (redis) {+ try {+ const key = dailyKey();+ const total = BigInt(await redis.incrby(key, Number(need)));+ // First writer sets a 2-day TTL so the key self-expires after the UTC day.+ if (total === need) {+ try { await redis.expire(key, 86_400 * 2); } catch { /* non-fatal */ }+ }+ if (total > capAtomics) {+ try { await redis.incrby(key, -Number(need)); } catch { /* best-effort rollback */ }+ return { ok: false, dailySpentAtomics: total - need, dailyCapAtomics: capAtomics };+ }+ return { ok: true, dailySpentAtomics: total, dailyCapAtomics: capAtomics };+ } catch {+ /* fall through to DB */+ }+ }+ const spent = await dbDailySpentAtomics();+ if (spent + need > capAtomics) {+ return { ok: false, dailySpentAtomics: spent, dailyCapAtomics: capAtomics };+ }+ return { ok: true, dailySpentAtomics: spent + need, dailyCapAtomics: capAtomics };+}++/** Release a previously-reserved amount (a buy that never broadcast). Redis only. */+export async function releaseDailySpend(atomics) {+ const redis = getRedis();+ if (!redis) return;+ try { await redis.incrby(dailyKey(), -Number(BigInt(atomics))); } catch { /* non-fatal */ }+}++/** Today's micro-buy spend so far (atomics) for status/read paths. */+export async function dailySpentAtomics() {+ const redis = getRedis();+ if (redis) {+ try {+ const v = await redis.get(dailyKey());+ if (v != null) return BigInt(v);+ } catch { /* fall through */ }+ }+ return dbDailySpentAtomics();+}++// ── helpers ─────────────────────────────────────────────────────────────────++const usd = (a) => usdcAtomicsToUsd(a);+const threeTokens = (a) => atomicsToTokens(a, TOKEN_DECIMALS);++/** SPL balance of `owner` for `mint`, in atomics. Missing ATA → 0n (never throws). */+async function splBalanceAtomics(connection, ownerPk, mintPk) {+ const ata = getAssociatedTokenAddressSync(mintPk, ownerPk, true);+ try {+ const bal = await connection.getTokenAccountBalance(ata);+ return BigInt(bal.value.amount);+ } catch {+ return 0n;+ }+}++/** Bounded confirmation: resolve 'confirmed' or throw/timeout without hanging the request. */+async function confirmBounded(connection, sig) {+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(+ () => reject(Object.assign(new Error('confirm_timeout'), { code: 'tx_unconfirmed' })),+ confirmTimeoutMs(),+ );+ });+ try {+ await Promise.race([confirmOrThrow(connection, sig, 'confirmed'), timeout]);+ } finally {+ clearTimeout(timer);+ }+}++// ── plan + execute ──────────────────────────────────────────────────────────++/**+ * Size + quote a single micro-buy against the wallet's live USDC balance. Pure of+ * signing/sending. Returns { ok, reason?, spendUsdcAtomics, walletUsdcAtomics,+ * quote?, expectedThreeAtomics?, priceUsd? }.+ */+export async function planMicrobuy(signerPubkey) {+ if (!treasuryWalletOrNull()) {+ return { ok: false, reason: 'treasury_unavailable', walletUsdcAtomics: 0n, spendUsdcAtomics: 0n };+ }+ const spend = buyUsdcAtomics();+ const connection = getConnection({ network: 'mainnet' });+ const walletUsdc = await splBalanceAtomics(+ connection,+ solanaPubkey(signerPubkey),+ solanaPubkey(SOLANA_USDC_MINT),+ );+ if (walletUsdc < spend) {+ return { ok: false, reason: 'insufficient_usdc', walletUsdcAtomics: walletUsdc, spendUsdcAtomics: spend };+ }+ const quote = await jupiterQuote({+ inputMint: SOLANA_USDC_MINT,+ outputMint: TOKEN_MINT,+ amount: spend,+ slippageBps: slippageBps(),+ });+ const expectedThree = BigInt(quote.outAmount ?? 0);+ if (expectedThree <= 0n) {+ return { ok: false, reason: 'no_quote', walletUsdcAtomics: walletUsdc, spendUsdcAtomics: spend };+ }+ return {+ ok: true,+ walletUsdcAtomics: walletUsdc,+ spendUsdcAtomics: spend,+ quote,+ expectedThreeAtomics: expectedThree,+ priceUsd: usd(spend) / threeTokens(expectedThree),+ };+}++/**+ * Execute one micro-buy: reserve the daily budget, sign + broadcast the Jupiter+ * buy, and confirm within a bounded window. The bought $THREE accrues in the+ * micro-buy wallet (swept to the treasury on a cadence by the loop). Returns a+ * receipt; on a hard failure throws with a `.code` so the caller records the reason+ * and (on a never-broadcast failure) releases the reservation.+ *+ * @returns {Promise<{ status:'confirmed'|'pending', buySignature:string, spendUsdcAtomics:bigint, boughtAtomics:bigint, priceUsd:number|null }>}+ */+export async function executeMicrobuy(signer, plan) {+ const { VersionedTransaction } = await import('@solana/web3.js');+ const connection = getConnection({ network: 'mainnet' });+ const payer = signer.publicKey;++ // Reserve budget BEFORE broadcasting so concurrent buys can't collectively+ // overshoot the daily cap. Released by the caller only if we never broadcast.+ const reservation = await reserveDailySpend(plan.spendUsdcAtomics);+ if (!reservation.ok) {+ throw Object.assign(new Error('daily micro-buy cap reached'), {+ code: 'daily_cap_reached',+ dailySpentAtomics: reservation.dailySpentAtomics,+ dailyCapAtomics: reservation.dailyCapAtomics,+ });+ }++ let swapB64;+ try {+ swapB64 = await jupiterSwapTx({ quote: plan.quote, userPublicKey: payer.toBase58() });+ } catch (err) {+ await releaseDailySpend(plan.spendUsdcAtomics);+ throw err;+ }++ const buyTx = VersionedTransaction.deserialize(Buffer.from(swapB64, 'base64'));+ buyTx.sign([signer]);++ let buySig;+ try {+ buySig = await connection.sendRawTransaction(buyTx.serialize(), { maxRetries: 5 });+ } catch (err) {+ // Never broadcast → the budget was not spent; give it back.+ await releaseDailySpend(plan.spendUsdcAtomics);+ throw Object.assign(new Error(`micro-buy broadcast failed: ${err?.message || err}`), {+ code: 'swap_failed',+ });+ }++ // Broadcast succeeded — the USDC is committed, so the reservation STANDS even if+ // confirmation times out (the buy is in flight, not free).+ try {+ await confirmBounded(connection, buySig);+ } catch (waitErr) {+ if (waitErr?.code === 'tx_reverted') {+ // A revert means the transfer did not happen — reclaim the reservation.+ await releaseDailySpend(plan.spendUsdcAtomics);+ throw waitErr;+ }+ return {+ status: 'pending',+ buySignature: buySig,+ spendUsdcAtomics: plan.spendUsdcAtomics,+ boughtAtomics: 0n,+ priceUsd: plan.priceUsd ?? null,+ };+ }++ const boughtAtomics = await splBalanceAtomics(connection, payer, solanaPubkey(TOKEN_MINT));+ return {+ status: 'confirmed',+ buySignature: buySig,+ spendUsdcAtomics: plan.spendUsdcAtomics,+ boughtAtomics,+ priceUsd: plan.priceUsd ?? null,+ };+}++/**+ * Sweep all $THREE held by the micro-buy wallet into the treasury. Buy-only lane:+ * this is the ONLY thing that moves the accrued tokens, and it only moves them to+ * the treasury. Returns the sweep signature, or null when there is nothing to sweep+ * or the wallet already IS the treasury. Reuses submitProtected (priority fee + CU+ * estimate, blockhash-refresh rebroadcast, hard throw on revert).+ */+export async function sweepMicrobuyThree(signer) {+ const treasury = treasuryWalletOrNull();+ if (!treasury || treasury === signer.publicKey.toBase58()) return null;+ const { TransactionInstruction, PublicKey } = await import('@solana/web3.js');+ const connection = getConnection({ network: 'mainnet' });+ const payer = signer.publicKey;+ const mintPk = new PublicKey(TOKEN_MINT);+ const held = await splBalanceAtomics(connection, payer, mintPk);+ if (held <= 0n) return null;++ const treasuryPk = new PublicKey(treasury);+ const fromAta = getAssociatedTokenAddressSync(mintPk, payer, true);+ const toAta = getAssociatedTokenAddressSync(mintPk, treasuryPk, true);+ const ixs = [+ createAssociatedTokenAccountIdempotentInstruction(payer, toAta, treasuryPk, mintPk),+ createTransferInstruction(fromAta, toAta, payer, held),+ new TransactionInstruction({+ keys: [],+ programId: new PublicKey(MEMO_PROGRAM_ID),+ data: Buffer.from('three.ws micro-buy → treasury', 'utf8'),+ }),+ ];+ const { signature } = await submitProtected({+ network: 'mainnet',+ connection,+ payer: signer,+ instructions: ixs,+ });+ return signature;+}++export { usd as usdcAtomicsToUsd, threeTokens as threeAtomicsToTokens };diff --git a/api/_lib/x402/ring-catalog.js b/api/_lib/x402/ring-catalog.jsindex 0a4556b58..3d3212eff 100644--- a/api/_lib/x402/ring-catalog.js+++ b/api/_lib/x402/ring-catalog.js@@ -821,6 +821,22 @@ export const RING_CATALOG = [businessEffect: 'Full-text search over the 662k-article crypto-news archive (Sept 2017 →) with sentiment/ticker/date filters.',note: 'autobuy:false — freemium rail: 60 searches/day per IP are free, so a ring call usually gets a free 200, not a 402; the paid twin only engages over quota.',},+ {+ slug: 'three-buy',+ sourceFile: 'api/x402/three-buy.js',+ path: '/api/x402/three-buy',+ method: 'POST',+ body: () => ({ note: 'microbuy' }),+ priceAtomicDefault: 1_000,+ priceSlug: 'three-buy',+ tier: 'commerce',+ kind: 'commerce',+ network: 'solana',+ autobuy: false,+ weight: 0,+ businessEffect: 'Each settled call executes one small, real USDC→$THREE market buy on Jupiter (buy-only) funded by the micro-buy wallet, then the tokens are swept to the treasury.',+ note: 'autobuy:false — every settled call spends real USDC on a live $THREE market buy (bounded by THREE_MICROBUY_DAILY_CAP_USD). It has its own dedicated driver, api/cron/three-buy-loop.js, so the generic ring rotation must not also fire it.',+ },{slug: 'pump-launch',sourceFile: 'api/x402/pump-launch.js',diff --git a/api/cron/three-buy-loop.js b/api/cron/three-buy-loop.jsnew file mode 100644index 000000000..9a6603fcd--- /dev/null+++ b/api/cron/three-buy-loop.js@@ -0,0 +1,244 @@+// GET /api/cron/three-buy-loop+//+// The per-minute $THREE micro-buy driver: many tiny, real x402-settled buys per+// minute so the platform shows continuous, verifiable buy pressure on $THREE.+//+// Each call pays the small x402 toll to /api/x402/three-buy (ring treasury,+// X402_PAY_TO_SOLANA) exactly like the ring tick; the endpoint delivers the paid+// good by executing ONE small, real USDC→$THREE market buy on Jupiter (buy-only)+// funded by the micro-buy wallet. So this loop is "buy $THREE, paid through the+// x402 loop": the x402 payment is the trigger, the on-chain buy is the good.+//+// CADENCE. Fires THREE_MICROBUY_PER_TICK buys per minute (default 10, hard-capped+// at 60) across THREE_MICROBUY_CONCURRENCY concurrent workers (default 8), so a+// full tick finishes inside the economy-tick 60s call budget. Set PER_TICK=60 for+// the "~60 buys/min" target.+//+// SAFETY (defense in depth — the endpoint self-guards too):+// • Kill switches: X402_AUTONOMOUS_ENABLED=false (global) OR THREE_MICROBUY_ENABLED+// not truthy OR THREE_MICROBUY_LOOP_ENABLED=false → clean skip.+// • The real market spend is bounded by the endpoint's UTC-daily ceiling+// (THREE_MICROBUY_DAILY_CAP_USD, atomic reserve-before-buy). This loop pre-checks+// it and stops firing once the day's budget is exhausted.+// • The tolls (internal recirculation) are bounded per tick by+// X402_THREE_BUY_TOLL_CAP_ATOMIC.+// • A buy that can't happen never charges a toll — the endpoint re-emits 402.+//+// BUY-ONLY. Nothing here sells $THREE. Accrued tokens are swept to the treasury+// every THREE_MICROBUY_SWEEP_EVERY_N_TICKS ticks.+//+// Real on-chain payments only — no mocks. Shares the ONE payment + recording path+// (pipelines/volume-shared.js) with the ring drivers, tagged pipeline='three-buy'.++import { randomUUID } from 'node:crypto';+import { PublicKey } from '@solana/web3.js';+import { getMint } from '@solana/spl-token';++import { json, wrapCron } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';+import { getRedis } from '../_lib/redis.js';+import { solanaConnection } from '../_lib/solana/connection.js';+import { logger } from '../_lib/usage.js';+import { priceFor } from '../_lib/x402-prices.js';+import { loadSeedKeypair, payX402, USDC_MINT, SOLANA_RPC } from '../_lib/x402/pay.js';+import { ensureVolumeSchema, settleAndRecord } from '../_lib/x402/pipelines/volume-shared.js';+import {+ isEnabled as microbuyEnabled,+ dailyCapUsd,+ dailySpentAtomics,+ loadMicrobuySigner,+ sweepMicrobuyThree,+} from '../_lib/token/microbuy.js';+import { usdToUsdcAtomics } from '../_lib/token/buyback-math.js';++const log = logger('three-buy-loop');+const ORIGIN = () => (env.APP_ORIGIN || 'https://three.ws').replace(/\/+$/, '');++const THREE_BUY_EP = {+ key: 'three-buy',+ name: 'Three Buy',+ path: '/api/x402/three-buy',+ method: 'POST',+ body: { note: 'microbuy' },+};++// Loop knobs (env, safe defaults).+const perTick = () => {+ const n = Number(process.env.THREE_MICROBUY_PER_TICK);+ if (!Number.isFinite(n) || n <= 0) return 10;+ return Math.min(Math.floor(n), 60); // hard cap the per-minute burst+};+const concurrency = () => {+ const n = Number(process.env.THREE_MICROBUY_CONCURRENCY);+ return Number.isFinite(n) && n >= 1 && n <= 20 ? Math.floor(n) : 8;+};+const tollCapAtomic = () => {+ const n = Number(process.env.X402_THREE_BUY_TOLL_CAP_ATOMIC);+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 1_000_000; // $1.00 of tolls/tick+};+const sweepEveryN = () => {+ const n = Number(process.env.THREE_MICROBUY_SWEEP_EVERY_N_TICKS);+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 30; // ~ every 30 min+};++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) { json(res, 503, { error: 'CRON_SECRET unset' }); return false; }+ const auth = req.headers['authorization'] || '';+ const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(token, secret)) { json(res, 401, { error: 'unauthorized' }); return false; }+ return true;+}++// A monotonic tick counter so the periodic sweep fires on a stable cadence across+// warm instances (Redis INCR, in-memory fallback — mirrors the ring tick).+const TICK_SEQ_KEY = 'three:microbuy:tick:seq';+let _memTickSeq = 0;+async function nextTickSeq() {+ const redis = getRedis();+ if (redis) {+ try { return Number(await redis.incr(TICK_SEQ_KEY)); } catch { /* fall through */ }+ }+ return (_memTickSeq += 1);+}++export default wrapCron(async (req, res) => {+ if (req.method !== 'GET') return json(res, 405, { error: 'method_not_allowed' });+ if (!requireCron(req, res)) return;++ // ── Kill switches ───────────────────────────────────────────────────────+ if (process.env.X402_AUTONOMOUS_ENABLED === 'false') {+ return json(res, 200, { ok: true, skipped: true, reason: 'X402_AUTONOMOUS_ENABLED=false' });+ }+ if (String(process.env.THREE_MICROBUY_LOOP_ENABLED || '').toLowerCase() === 'false') {+ return json(res, 200, { ok: true, skipped: true, reason: 'THREE_MICROBUY_LOOP_ENABLED=false' });+ }+ if (!microbuyEnabled()) {+ return json(res, 200, { ok: true, skipped: true, reason: 'THREE_MICROBUY_ENABLED not set' });+ }++ const origin = ORIGIN();+ const runId = randomUUID();++ // ── Toll payer ──────────────────────────────────────────────────────────+ let payer;+ try { payer = loadSeedKeypair(); } catch (err) {+ return json(res, 200, { ok: false, skipped: true, reason: err.message });+ }++ try { await ensureVolumeSchema(sql); } catch (err) {+ return json(res, 200, { ok: false, skipped: true, reason: `schema_failed: ${err?.message}` });+ }++ // ── Daily market-spend cap pre-check (the endpoint enforces it atomically;+ // this stops the loop from firing tolls once the day's buys are exhausted) ──+ let dailySpent = 0n;+ try { dailySpent = await dailySpentAtomics(); } catch { dailySpent = 0n; }+ const capAtomic = usdToUsdcAtomics(dailyCapUsd());+ if (dailySpent >= capAtomic) {+ return json(res, 200, {+ ok: true, skipped: true, reason: 'daily_cap_reached', run_id: runId,+ daily_spent_usd: Number(dailySpent) / 1e6, daily_cap_usd: dailyCapUsd(),+ });+ }++ // ── Shared Solana state for the tolls ─────────────────────────────────────+ const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });+ let mintInfo;+ try {+ mintInfo = await getMint(conn, new PublicKey(USDC_MINT));+ } catch (err) {+ return json(res, 200, { ok: false, skipped: true, reason: `rpc_preflight_failed: ${err?.message}`, run_id: runId });+ }++ const want = perTick();+ const conc = concurrency();+ const tollCap = tollCapAtomic();+ const tollPriceAtomic = Number(priceFor('three-buy', 1_000));++ let fired = 0, paid = 0, buys = 0, pending = 0, errors = 0, tollSpent = 0;+ let capHitMidTick = false;++ // Fire the buys in waves of `conc`, refetching a blockhash per wave so a long+ // tick never signs tolls against an expired blockhash.+ let idx = 0;+ while (idx < want && !capHitMidTick) {+ if (tollSpent + tollPriceAtomic > tollCap) break;++ let blockhash;+ try {+ ({ blockhash } = await conn.getLatestBlockhash('confirmed'));+ } catch (err) {+ log.warn('three_buy_blockhash_failed', { message: err?.message });+ break;+ }++ const waveSize = Math.min(conc, want - idx);+ const wave = await Promise.all(+ Array.from({ length: waveSize }, async () => {+ const remaining = Math.max(0, tollCap - tollSpent);+ const { result, paidAmount } = await settleAndRecord({+ sql, runId, ep: THREE_BUY_EP, origin, remaining,+ ctx: { buyer: payer, conn, blockhash, mintInfo },+ pipeline: 'three-buy', namePrefix: 'MicroBuy', payFn: payX402, log,+ });+ return { result, paidAmount };+ }),+ );++ for (const { result, paidAmount } of wave) {+ fired += 1;+ if (result.paid) { paid += 1; tollSpent += paidAmount; }+ if (!result.success) {+ errors += 1;+ // The endpoint re-emits 402 when the daily cap is reached — stop firing.+ const hay = `${result.errorMsg || ''} ${JSON.stringify(result.responseBody || '')}`;+ if (/daily_cap_reached|three_buy_unavailable/i.test(hay) && /cap/i.test(hay)) {+ capHitMidTick = true;+ }+ }+ // A settled toll means the endpoint delivered a broadcast buy (confirmed+ // or pending); count it as a buy regardless of confirmation latency.+ const status = result?.responseBody?.status;+ if (result.paid && status === 'confirmed') buys += 1;+ else if (result.paid && status === 'pending') { buys += 1; pending += 1; }+ }+ idx += waveSize;+ }++ // ── Periodic treasury sweep of accrued $THREE (buy-only lane) ─────────────+ let sweepSig = null;+ const seq = await nextTickSeq();+ if (seq > 0 && seq % sweepEveryN() === 0) {+ try {+ const signer = await loadMicrobuySigner();+ if (signer) sweepSig = await sweepMicrobuyThree(signer);+ } catch (err) {+ log.warn('three_buy_sweep_failed', { message: err?.message });+ }+ }++ log.info('three_buy_loop_complete', {+ run_id: runId, fired, paid, buys, pending, errors,+ toll_spent_usd: (tollSpent / 1e6).toFixed(4),+ daily_spent_usd: (Number(dailySpent) / 1e6).toFixed(4),+ cap_hit: capHitMidTick, sweep: sweepSig ? sweepSig.slice(0, 12) : null,+ });++ return json(res, 200, {+ ok: true,+ run_id: runId,+ fired,+ paid,+ buys,+ pending,+ errors,+ toll_spent_usd: (tollSpent / 1e6).toFixed(4),+ daily_spent_usd: (Number(dailySpent) / 1e6).toFixed(4),+ daily_cap_usd: dailyCapUsd(),+ cap_hit_mid_tick: capHitMidTick,+ ...(sweepSig ? { sweep_signature: sweepSig } : {}),+ });+});diff --git a/api/x402/three-buy.js b/api/x402/three-buy.jsnew file mode 100644index 000000000..61446a94e--- /dev/null+++ b/api/x402/three-buy.js@@ -0,0 +1,206 @@+// POST /api/x402/three-buy+//+// The x402 micro-buy service: one settled payment → one small, real on-chain buy+// of $THREE. It is the high-frequency, small-ticket sibling of the daily buyback+// (api/cron/run-three-buyback) — where that lane deploys revenue in a few large+// buys per day, this lane fires many tiny buys per minute so the platform shows+// continuous, verifiable buy pressure on $THREE. Driven by api/cron/three-buy-loop.+//+// HOW IT SETTLES. The caller pays the small x402 toll (X402_PRICE_THREE_BUY, default+// $0.001) in USDC to the ring treasury (X402_PAY_TO_SOLANA), exactly like every+// other ring endpoint. The toll is NOT the buy funding — on a paid call the handler+// executes a separate USDC→$THREE swap funded by the micro-buy wallet+// (api/_lib/token/microbuy.js). Two independent, auditable money streams.+//+// BUY-ONLY. The service never sells $THREE. Bought tokens accrue in the micro-buy+// wallet and are swept to the treasury by the loop; there is no sell path.+//+// FAIL-CLOSED ON THE TOLL. The endpoint takes the toll ONLY when a buy actually+// broadcasts. When the engine is disabled, unfunded, or the UTC-daily cap is+// reached, the handler re-emits the 402 challenge (X402Error 402) so settlement+// never runs and the caller keeps their funds — the platform never charges a toll+// for a buy it didn't make. This also caps the amplification a direct payer could+// force: they can trigger buys only up to the same daily ceiling the loop obeys.+//+// discoverable:false — internal buy-pressure machinery, not an organic third-party+// service, so it is not advertised on the public x402 bazaar (same stance as+// ring-settle).++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { X402Error } from '../_lib/x402-spec.js';+import { priceFor } from '../_lib/x402-prices.js';+import { sql } from '../_lib/db.js';+import { logger } from '../_lib/usage.js';+import { TOKEN_MINT } from '../_lib/token/config.js';+import {+ isEnabled,+ loadMicrobuySigner,+ planMicrobuy,+ executeMicrobuy,+ usdcAtomicsToUsd,+ threeAtomicsToTokens,+} from '../_lib/token/microbuy.js';++const log = logger('x402-three-buy');+const ROUTE = '/api/x402/three-buy';++// Default $0.001 — a deliberately tiny toll: this endpoint's value is the on-chain+// buy it triggers, not the toll itself. Operators tune it with X402_PRICE_THREE_BUY.+const DEFAULT_PRICE_ATOMICS = 1_000;++const DESCRIPTION =+ 'three.ws internal $THREE micro-buy primitive. A settled x402 payment triggers ' ++ 'one small, real on-chain market buy of $THREE on Jupiter (buy-only); bought ' ++ 'tokens are swept to the treasury. High-frequency sibling of the daily buyback. ' ++ 'Not a public service.';++const INPUT_EXAMPLE = { note: 'microbuy' };++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ note: { type: 'string', description: 'Optional label echoed into the receipt.' },+ },+};++const OUTPUT_EXAMPLE = {+ ok: true,+ kind: 'three-buy',+ status: 'confirmed',+ mint: TOKEN_MINT,+ buySignature: '5x8…',+ spentUsd: 0.01,+ boughtThree: 5.1956,+ priceUsd: 0.001924,+ boughtAt: '2026-07-17T18:42:09.000Z',+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['ok', 'kind', 'status', 'mint', 'buySignature', 'boughtAt'],+ properties: {+ ok: { type: 'boolean', const: true },+ kind: { type: 'string', const: 'three-buy' },+ status: { type: 'string', enum: ['confirmed', 'pending'] },+ mint: { type: 'string' },+ buySignature: { type: 'string' },+ spentUsd: { type: ['number', 'null'] },+ boughtThree: { type: ['number', 'null'] },+ priceUsd: { type: ['number', 'null'] },+ boughtAt: { type: 'string', format: 'date-time' },+ },+};++const BAZAAR = {+ discoverable: false,+ info: {+ input: { type: 'http', method: 'POST', body: INPUT_EXAMPLE },+ output: { type: 'json', example: OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodyType: 'json',+ bodySchema: INPUT_SCHEMA,+ outputSchema: OUTPUT_SCHEMA,+ }),+};++// Re-emit the 402 challenge so the wrapper never settles the toll — used whenever a+// buy will not happen (disabled, unfunded, cap reached). The caller keeps its funds.+function refuseToll(reason) {+ return new X402Error('three_buy_unavailable', `three-buy: ${reason}`, 402);+}++// Record every buy (and skipped/failed reason) into three_microbuy_runs — never a+// silent no-op. Wrapped so a DB fault never fails a buy that already landed.+async function record(status, fields = {}) {+ try {+ const [row] = await sql`+ INSERT INTO three_microbuy_runs+ (status, reason, usdc_spent_atomics, three_bought_atomics, price_usd,+ slippage_bps, buy_signature)+ VALUES+ (${status}, ${fields.reason ?? null}, ${fields.usdcSpentAtomics ?? 0},+ ${fields.threeBoughtAtomics ?? 0}, ${fields.priceUsd ?? null},+ ${fields.slippageBps ?? null}, ${fields.buySignature ?? null})+ RETURNING id+ `;+ return row?.id ?? null;+ } catch (err) {+ log.warn('three_microbuy_record_failed', { status, message: err?.message });+ return null;+ }+}++export default paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: priceFor('three-buy', DEFAULT_PRICE_ATOMICS),+ networks: ['solana'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ async handler() {+ // Gate: a scheduled/paid call is a recorded no-op — and the toll is refused —+ // until an operator funds the wallet and opts in.+ if (!isEnabled()) {+ await record('skipped', { reason: 'disabled' });+ throw refuseToll('engine disabled (set THREE_MICROBUY_ENABLED)');+ }+ const signer = await loadMicrobuySigner();+ if (!signer) {+ await record('skipped', { reason: 'not_configured' });+ throw refuseToll('signer not configured (set THREE_MICROBUY_SECRET_KEY_B64 or THREE_BUYBACK_SECRET_KEY_B64)');+ }++ let plan;+ try {+ plan = await planMicrobuy(signer.publicKey.toBase58());+ } catch (err) {+ await record('failed', { reason: err.code || 'plan_failed' });+ throw refuseToll(`plan failed (${err.code || err.message})`);+ }+ if (!plan.ok) {+ await record('skipped', { reason: plan.reason });+ throw refuseToll(plan.reason);+ }++ let receipt;+ try {+ receipt = await executeMicrobuy(signer, plan);+ } catch (err) {+ // daily_cap_reached / swap_failed / tx_reverted all reclaim any reservation+ // inside executeMicrobuy and mean no buy went out → refuse the toll.+ await record('failed', {+ reason: err.code || 'execute_failed',+ usdcSpentAtomics: 0,+ });+ throw refuseToll(err.code || 'execute_failed');+ }++ // A buy broadcast (confirmed or in-flight) — the toll is earned; let the+ // wrapper settle it.+ await record(receipt.status, {+ usdcSpentAtomics: receipt.spendUsdcAtomics.toString(),+ threeBoughtAtomics: receipt.boughtAtomics.toString(),+ priceUsd: receipt.priceUsd,+ slippageBps: null,+ buySignature: receipt.buySignature,+ });++ return {+ ok: true,+ kind: 'three-buy',+ status: receipt.status,+ mint: TOKEN_MINT,+ buySignature: receipt.buySignature,+ spentUsd: usdcAtomicsToUsd(receipt.spendUsdcAtomics),+ boughtThree:+ receipt.boughtAtomics > 0n ? threeAtomicsToTokens(receipt.boughtAtomics) : null,+ priceUsd: receipt.priceUsd ?? null,+ boughtAt: new Date().toISOString(),+ };+ },+});diff --git a/public/changelog.json b/public/changelog.jsonindex d69953118..e68ca9140 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-17T23:34:02.259Z",+ "generated_at": "2026-07-17T23:41:32.315Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.json b/public/features.jsonindex 5e6acf5b9..6e3af90cd 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-17T23:34:02.240Z",+ "generated_at": "2026-07-17T23:41:32.302Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",